Bitcoin Core 31.99.0
P2P Digital Currency
psbt.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <coins.h>
6#include <consensus/amount.h>
8#include <node/psbt.h>
9#include <policy/policy.h>
10#include <policy/settings.h>
11#include <tinyformat.h>
12
13#include <numeric>
14
15namespace node {
17{
18 // Go through each input and build status
19 PSBTAnalysis result;
20
21 std::optional<CMutableTransaction> unsigned_tx = psbtx.GetUnsignedTx();
22 if (!unsigned_tx) {
23 result.SetInvalid("PSBT cannot be made into a valid transaction");
24 return result;
25 }
26 CMutableTransaction& mtx = *unsigned_tx;
27
28 bool calc_fee = true;
29
30 CAmount in_amt = 0;
31
32 result.inputs.resize(psbtx.inputs.size());
33
34 // PrecomputePSBTData calls GetUnsignedTx() which we checked already works
36
37 for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
38 PSBTInput& input = psbtx.inputs[i];
39 PSBTInputAnalysis& input_analysis = result.inputs[i];
40
41 // We set next role here and ratchet backwards as required
42 input_analysis.next = PSBTRole::EXTRACTOR;
43
44 // Check for a UTXO
45 CTxOut utxo;
46 if (input.GetUTXO(utxo)) {
47 if (!MoneyRange(utxo.nValue) || !MoneyRange(in_amt + utxo.nValue)) {
48 result.SetInvalid(strprintf("PSBT is not valid. Input %u has invalid value", i));
49 return result;
50 }
51 in_amt += utxo.nValue;
52 input_analysis.has_utxo = true;
53 } else {
54 if (input.non_witness_utxo && input.prev_out >= input.non_witness_utxo->vout.size()) {
55 result.SetInvalid(strprintf("PSBT is not valid. Input %u specifies invalid prevout", i));
56 return result;
57 }
58 input_analysis.has_utxo = false;
59 input_analysis.is_final = false;
60 input_analysis.next = PSBTRole::UPDATER;
61 calc_fee = false;
62 }
63
64 if (!utxo.IsNull() && utxo.scriptPubKey.IsUnspendable()) {
65 result.SetInvalid(strprintf("PSBT is not valid. Input %u spends unspendable output", i));
66 return result;
67 }
68
69 // Check if it is final
70 if (!PSBTInputSignedAndVerified(psbtx, i, &txdata)) {
71 input_analysis.is_final = false;
72
73 // Figure out what is missing
74 SignatureData outdata;
75 bool complete = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, /*options=*/{}, &outdata) == PSBTError::OK;
76
77 // Things are missing
78 if (!complete) {
79 input_analysis.missing_pubkeys = outdata.missing_pubkeys;
80 input_analysis.missing_redeem_script = outdata.missing_redeem_script;
81 input_analysis.missing_witness_script = outdata.missing_witness_script;
82 input_analysis.missing_sigs = outdata.missing_sigs;
83
84 // If we are only missing signatures and nothing else, then next is signer
85 if (outdata.missing_pubkeys.empty() && outdata.missing_redeem_script.IsNull() && outdata.missing_witness_script.IsNull() && !outdata.missing_sigs.empty()) {
86 input_analysis.next = PSBTRole::SIGNER;
87 } else {
88 input_analysis.next = PSBTRole::UPDATER;
89 }
90 } else {
91 input_analysis.next = PSBTRole::FINALIZER;
92 }
93 } else if (!utxo.IsNull()){
94 input_analysis.is_final = true;
95 }
96 }
97
98 // Calculate next role for PSBT by grabbing "minimum" PSBTInput next role
100 for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
101 PSBTInputAnalysis& input_analysis = result.inputs[i];
102 result.next = std::min(result.next, input_analysis.next);
103 }
104 assert(result.next > PSBTRole::CREATOR);
105
106 if (calc_fee) {
107 // Get the output amount
108 CAmount out_amt = std::accumulate(psbtx.outputs.begin(), psbtx.outputs.end(), CAmount(0),
109 [](CAmount a, const PSBTOutput& b) {
110 if (!MoneyRange(a) || !MoneyRange(b.amount) || !MoneyRange(a + b.amount)) {
111 return CAmount(-1);
112 }
113 return a += b.amount;
114 }
115 );
116 if (!MoneyRange(out_amt)) {
117 result.SetInvalid("PSBT is not valid. Output amount invalid");
118 return result;
119 }
120
121 // Get the fee
122 CAmount fee = in_amt - out_amt;
123 result.fee = fee;
124
125 // Estimate the size
127 bool success = true;
128
129 for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
130 PSBTInput& input = psbtx.inputs[i];
131 Coin newcoin;
132
133 if (SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, nullptr, /*options=*/{}) != PSBTError::OK || !input.GetUTXO(newcoin.out)) {
134 success = false;
135 break;
136 } else {
137 mtx.vin[i].scriptSig = input.final_script_sig;
138 mtx.vin[i].scriptWitness = input.final_script_witness;
139 newcoin.nHeight = 1;
140 view.AddCoin(input.GetOutPoint(), std::move(newcoin), true);
141 }
142 }
143
144 if (success) {
145 CTransaction ctx = CTransaction(mtx);
147 result.estimated_vsize = size;
148 // Estimate fee rate
149 CFeeRate feerate(fee, size);
150 result.estimated_feerate = feerate;
151 }
152
153 }
154
155 return result;
156}
157} // namespace node
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:394
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:563
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
An output of a transaction.
Definition: transaction.h:140
CScript scriptPubKey
Definition: transaction.h:143
CAmount nValue
Definition: transaction.h:142
bool IsNull() const
Definition: transaction.h:160
A UTXO entry.
Definition: coins.h:35
CTxOut out
unspent transaction output
Definition: coins.h:38
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:44
static CoinsViewEmpty & Get()
Definition: coins.cpp:17
A structure for PSBTs which contain per-input information.
Definition: psbt.h:280
CScriptWitness final_script_witness
Definition: psbt.h:290
bool GetUTXO(CTxOut &utxo) const
Retrieves the UTXO for this input.
Definition: psbt.cpp:268
CTransactionRef non_witness_utxo
Definition: psbt.h:285
COutPoint GetOutPoint() const
Definition: psbt.cpp:286
uint32_t prev_out
Definition: psbt.h:299
CScript final_script_sig
Definition: psbt.h:289
A structure for PSBTs which contains per output information.
Definition: psbt.h:938
CAmount amount
Definition: psbt.h:955
A version of CTransaction with the PSBT format.
Definition: psbt.h:1239
std::vector< PSBTInput > inputs
Definition: psbt.h:1248
std::optional< CMutableTransaction > GetUnsignedTx() const
Definition: psbt.cpp:121
std::vector< PSBTOutput > outputs
Definition: psbt.h:1249
constexpr bool IsNull() const
Definition: uint256.h:49
uint64_t fee
Definition: messages.h:21
PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
Provides helpful miscellaneous information about where a PSBT is in the signing workflow.
Definition: psbt.cpp:16
unsigned int nBytesPerSigOp
Definition: settings.cpp:10
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:395
static constexpr script_verify_flags STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:118
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction &psbt, unsigned int input_index, const PrecomputedTransactionData *txdata)
Checks whether a PSBTInput is already signed by doing script verification using final fields.
Definition: psbt.cpp:554
std::optional< PrecomputedTransactionData > PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:623
PSBTError SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, const common::PSBTFillOptions &options, SignatureData *out_sigdata)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:644
const SigningProvider & DUMMY_SIGNING_PROVIDER
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxIn > vin
Definition: transaction.h:359
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:98
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:97
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:99
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:96
Holds the results of AnalyzePSBT (miscellaneous information about a PSBT)
Definition: psbt.h:30
std::vector< PSBTInputAnalysis > inputs
More information about the individual inputs of the transaction.
Definition: psbt.h:34
void SetInvalid(std::string err_msg)
Definition: psbt.h:38
std::optional< CAmount > fee
Amount of fee being paid by the transaction.
Definition: psbt.h:33
std::optional< size_t > estimated_vsize
Estimated weight of the transaction.
Definition: psbt.h:31
std::optional< CFeeRate > estimated_feerate
Estimated feerate (fee / weight) of the transaction.
Definition: psbt.h:32
PSBTRole next
Which of the BIP 174 roles needs to handle the transaction next.
Definition: psbt.h:35
Holds an analysis of one input from a PSBT.
Definition: psbt.h:16
uint256 missing_witness_script
SHA256 of witness script, if missing.
Definition: psbt.h:24
std::vector< CKeyID > missing_sigs
Pubkeys whose signatures are missing.
Definition: psbt.h:22
bool has_utxo
Whether we have UTXO information for this input.
Definition: psbt.h:17
PSBTRole next
Which of the BIP 174 roles needs to handle this input next.
Definition: psbt.h:19
std::vector< CKeyID > missing_pubkeys
Pubkeys whose BIP32 derivation path is missing.
Definition: psbt.h:21
uint160 missing_redeem_script
Hash160 of redeem script, if missing.
Definition: psbt.h:23
bool is_final
Whether the input has all required information including signatures.
Definition: psbt.h:18
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:143
assert(!tx.IsCoinBase())