Bitcoin Core  22.99.0
P2P Digital Currency
psbt.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2020 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 <amount.h>
6 #include <coins.h>
7 #include <consensus/tx_verify.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 
16 {
17  // Go through each input and build status
18  PSBTAnalysis result;
19 
20  bool calc_fee = true;
21 
22  CAmount in_amt = 0;
23 
24  result.inputs.resize(psbtx.tx->vin.size());
25 
26  const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
27 
28  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
29  PSBTInput& input = psbtx.inputs[i];
30  PSBTInputAnalysis& input_analysis = result.inputs[i];
31 
32  // We set next role here and ratchet backwards as required
33  input_analysis.next = PSBTRole::EXTRACTOR;
34 
35  // Check for a UTXO
36  CTxOut utxo;
37  if (psbtx.GetInputUTXO(utxo, i)) {
38  if (!MoneyRange(utxo.nValue) || !MoneyRange(in_amt + utxo.nValue)) {
39  result.SetInvalid(strprintf("PSBT is not valid. Input %u has invalid value", i));
40  return result;
41  }
42  in_amt += utxo.nValue;
43  input_analysis.has_utxo = true;
44  } else {
45  if (input.non_witness_utxo && psbtx.tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
46  result.SetInvalid(strprintf("PSBT is not valid. Input %u specifies invalid prevout", i));
47  return result;
48  }
49  input_analysis.has_utxo = false;
50  input_analysis.is_final = false;
51  input_analysis.next = PSBTRole::UPDATER;
52  calc_fee = false;
53  }
54 
55  if (!utxo.IsNull() && utxo.scriptPubKey.IsUnspendable()) {
56  result.SetInvalid(strprintf("PSBT is not valid. Input %u spends unspendable output", i));
57  return result;
58  }
59 
60  // Check if it is final
61  if (!utxo.IsNull() && !PSBTInputSigned(input)) {
62  input_analysis.is_final = false;
63 
64  // Figure out what is missing
65  SignatureData outdata;
66  bool complete = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, 1, &outdata);
67 
68  // Things are missing
69  if (!complete) {
70  input_analysis.missing_pubkeys = outdata.missing_pubkeys;
71  input_analysis.missing_redeem_script = outdata.missing_redeem_script;
72  input_analysis.missing_witness_script = outdata.missing_witness_script;
73  input_analysis.missing_sigs = outdata.missing_sigs;
74 
75  // If we are only missing signatures and nothing else, then next is signer
76  if (outdata.missing_pubkeys.empty() && outdata.missing_redeem_script.IsNull() && outdata.missing_witness_script.IsNull() && !outdata.missing_sigs.empty()) {
77  input_analysis.next = PSBTRole::SIGNER;
78  } else {
79  input_analysis.next = PSBTRole::UPDATER;
80  }
81  } else {
82  input_analysis.next = PSBTRole::FINALIZER;
83  }
84  } else if (!utxo.IsNull()){
85  input_analysis.is_final = true;
86  }
87  }
88 
89  // Calculate next role for PSBT by grabbing "minimum" PSBTInput next role
90  result.next = PSBTRole::EXTRACTOR;
91  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
92  PSBTInputAnalysis& input_analysis = result.inputs[i];
93  result.next = std::min(result.next, input_analysis.next);
94  }
95  assert(result.next > PSBTRole::CREATOR);
96 
97  if (calc_fee) {
98  // Get the output amount
99  CAmount out_amt = std::accumulate(psbtx.tx->vout.begin(), psbtx.tx->vout.end(), CAmount(0),
100  [](CAmount a, const CTxOut& b) {
101  if (!MoneyRange(a) || !MoneyRange(b.nValue) || !MoneyRange(a + b.nValue)) {
102  return CAmount(-1);
103  }
104  return a += b.nValue;
105  }
106  );
107  if (!MoneyRange(out_amt)) {
108  result.SetInvalid(strprintf("PSBT is not valid. Output amount invalid"));
109  return result;
110  }
111 
112  // Get the fee
113  CAmount fee = in_amt - out_amt;
114  result.fee = fee;
115 
116  // Estimate the size
117  CMutableTransaction mtx(*psbtx.tx);
118  CCoinsView view_dummy;
119  CCoinsViewCache view(&view_dummy);
120  bool success = true;
121 
122  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
123  PSBTInput& input = psbtx.inputs[i];
124  Coin newcoin;
125 
126  if (!SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, nullptr, 1) || !psbtx.GetInputUTXO(newcoin.out, i)) {
127  success = false;
128  break;
129  } else {
130  mtx.vin[i].scriptSig = input.final_script_sig;
131  mtx.vin[i].scriptWitness = input.final_script_witness;
132  newcoin.nHeight = 1;
133  view.AddCoin(psbtx.tx->vin[i].prevout, std::move(newcoin), true);
134  }
135  }
136 
137  if (success) {
140  result.estimated_vsize = size;
141  // Estimate fee rate
142  CFeeRate feerate(fee, size);
143  result.estimated_feerate = feerate;
144  }
145 
146  }
147 
148  return result;
149 }
policy.h
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:346
PSBTInput::non_witness_utxo
CTransactionRef non_witness_utxo
Definition: psbt.h:51
assert
assert(!tx.IsCoinBase())
SignatureData::missing_redeem_script
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:79
PSBTInputAnalysis::missing_pubkeys
std::vector< CKeyID > missing_pubkeys
Pubkeys whose BIP32 derivation path is missing.
Definition: psbt.h:20
settings.h
psbt.h
CCoinsViewCache::AddCoin
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:66
PSBTAnalysis
Holds the results of AnalyzePSBT (miscellaneous information about a PSBT)
Definition: psbt.h:29
PSBTAnalysis::fee
std::optional< CAmount > fee
Amount of fee being paid by the transaction.
Definition: psbt.h:32
PSBTRole::UPDATER
@ UPDATER
PartiallySignedTransaction::inputs
std::vector< PSBTInput > inputs
Definition: psbt.h:394
MoneyRange
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
PSBTAnalysis::inputs
std::vector< PSBTInputAnalysis > inputs
More information about the individual inputs of the transaction.
Definition: psbt.h:33
DUMMY_SIGNING_PROVIDER
const SigningProvider & DUMMY_SIGNING_PROVIDER
Definition: signingprovider.cpp:12
PSBTInputAnalysis
Holds an analysis of one input from a PSBT.
Definition: psbt.h:15
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
SignPSBTInput
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, int sighash, SignatureData *out_sigdata)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:250
PSBTAnalysis::next
PSBTRole next
Which of the BIP 174 roles needs to handle the transaction next.
Definition: psbt.h:34
tinyformat.h
PSBTInputAnalysis::has_utxo
bool has_utxo
Whether we have UTXO information for this input.
Definition: psbt.h:16
PSBTAnalysis::estimated_feerate
std::optional< CFeeRate > estimated_feerate
Estimated feerate (fee / weight) of the transaction.
Definition: psbt.h:31
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:157
Coin::out
CTxOut out
unspent transaction output
Definition: coins.h:34
CTxOut::nValue
CAmount nValue
Definition: transaction.h:131
CTxOut::IsNull
bool IsNull() const
Definition: transaction.h:149
PSBTInput::final_script_sig
CScript final_script_sig
Definition: psbt.h:55
AnalyzePSBT
PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
Provides helpful miscellaneous information about where a PSBT is in the signing workflow.
Definition: psbt.cpp:15
SignatureData
Definition: sign.h:65
CTxOut
An output of a transaction.
Definition: transaction.h:128
tx_verify.h
Coin
A UTXO entry.
Definition: coins.h:30
PSBTRole::SIGNER
@ SIGNER
Coin::nHeight
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:132
PartiallySignedTransaction::GetInputUTXO
bool GetInputUTXO(CTxOut &utxo, int input_index) const
Finds the UTXO for a given input index.
Definition: psbt.cpp:60
PSBTInput::final_script_witness
CScriptWitness final_script_witness
Definition: psbt.h:56
PSBTRole::CREATOR
@ CREATOR
PartiallySignedTransaction::tx
std::optional< CMutableTransaction > tx
Definition: psbt.h:393
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
PSBTAnalysis::SetInvalid
void SetInvalid(std::string err_msg)
Definition: psbt.h:37
SignatureData::missing_sigs
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:78
PrecomputedTransactionData
Definition: interpreter.h:150
coins.h
PSBTInputAnalysis::is_final
bool is_final
Whether the input has all required information including signatures.
Definition: psbt.h:17
PSBTRole::EXTRACTOR
@ EXTRACTOR
SignatureData::missing_pubkeys
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:77
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
PSBTInput
A structure for PSBTs which contain per-input information.
Definition: psbt.h:49
PSBTRole::FINALIZER
@ FINALIZER
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
PSBTInputAnalysis::missing_sigs
std::vector< CKeyID > missing_sigs
Pubkeys whose signatures are missing.
Definition: psbt.h:21
PSBTInputAnalysis::next
PSBTRole next
Which of the BIP 174 roles needs to handle this input next.
Definition: psbt.h:18
PartiallySignedTransaction
A version of CTransaction with the PSBT format.
Definition: psbt.h:391
PSBTInputAnalysis::missing_witness_script
uint256 missing_witness_script
SHA256 of witness script, if missing.
Definition: psbt.h:23
PSBTInputSigned
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:197
PSBTAnalysis::estimated_vsize
std::optional< size_t > estimated_vsize
Estimated weight of the transaction.
Definition: psbt.h:30
SignatureData::missing_witness_script
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:80
STANDARD_SCRIPT_VERIFY_FLAGS
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:60
CScript::IsUnspendable
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:544
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:344
PSBTInputAnalysis::missing_redeem_script
uint160 missing_redeem_script
Hash160 of redeem script, if missing.
Definition: psbt.h:22
GetTransactionSigOpCost
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, uint32_t flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:147
amount.h
PrecomputePSBTData
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:233
GetVirtualTransactionSize
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:280
ctx
static secp256k1_context * ctx
Definition: tests.c:42