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