Bitcoin Core  21.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 <psbt.h>
6 
7 #include <util/check.h>
8 #include <util/strencodings.h>
9 
10 
12 {
13  inputs.resize(tx.vin.size());
14  outputs.resize(tx.vout.size());
15 }
16 
18 {
19  return !tx && inputs.empty() && outputs.empty() && unknown.empty();
20 }
21 
23 {
24  // Prohibited to merge two PSBTs over different transactions
25  if (tx->GetHash() != psbt.tx->GetHash()) {
26  return false;
27  }
28 
29  for (unsigned int i = 0; i < inputs.size(); ++i) {
30  inputs[i].Merge(psbt.inputs[i]);
31  }
32  for (unsigned int i = 0; i < outputs.size(); ++i) {
33  outputs[i].Merge(psbt.outputs[i]);
34  }
35  unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
36 
37  return true;
38 }
39 
41 {
42  if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
43  return false;
44  }
45  tx->vin.push_back(txin);
46  psbtin.partial_sigs.clear();
47  psbtin.final_script_sig.clear();
49  inputs.push_back(psbtin);
50  return true;
51 }
52 
53 bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout)
54 {
55  tx->vout.push_back(txout);
56  outputs.push_back(psbtout);
57  return true;
58 }
59 
60 bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
61 {
62  PSBTInput input = inputs[input_index];
63  uint32_t prevout_index = tx->vin[input_index].prevout.n;
64  if (input.non_witness_utxo) {
65  if (prevout_index >= input.non_witness_utxo->vout.size()) {
66  return false;
67  }
68  utxo = input.non_witness_utxo->vout[prevout_index];
69  } else if (!input.witness_utxo.IsNull()) {
70  utxo = input.witness_utxo;
71  } else {
72  return false;
73  }
74  return true;
75 }
76 
77 bool PSBTInput::IsNull() const
78 {
79  return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty();
80 }
81 
83 {
84  if (!final_script_sig.empty()) {
85  sigdata.scriptSig = final_script_sig;
86  sigdata.complete = true;
87  }
88  if (!final_script_witness.IsNull()) {
89  sigdata.scriptWitness = final_script_witness;
90  sigdata.complete = true;
91  }
92  if (sigdata.complete) {
93  return;
94  }
95 
96  sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
97  if (!redeem_script.empty()) {
98  sigdata.redeem_script = redeem_script;
99  }
100  if (!witness_script.empty()) {
101  sigdata.witness_script = witness_script;
102  }
103  for (const auto& key_pair : hd_keypaths) {
104  sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
105  }
106 }
107 
109 {
110  if (sigdata.complete) {
111  partial_sigs.clear();
112  hd_keypaths.clear();
113  redeem_script.clear();
114  witness_script.clear();
115 
116  if (!sigdata.scriptSig.empty()) {
117  final_script_sig = sigdata.scriptSig;
118  }
119  if (!sigdata.scriptWitness.IsNull()) {
120  final_script_witness = sigdata.scriptWitness;
121  }
122  return;
123  }
124 
125  partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
126  if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
127  redeem_script = sigdata.redeem_script;
128  }
129  if (witness_script.empty() && !sigdata.witness_script.empty()) {
130  witness_script = sigdata.witness_script;
131  }
132  for (const auto& entry : sigdata.misc_pubkeys) {
133  hd_keypaths.emplace(entry.second);
134  }
135 }
136 
137 void PSBTInput::Merge(const PSBTInput& input)
138 {
139  if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
140  if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
141  // TODO: For segwit v1, we will want to clear out the non-witness utxo when setting a witness one. For v0 and non-segwit, this is not safe
142  witness_utxo = input.witness_utxo;
143  }
144 
145  partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
146  hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
147  unknown.insert(input.unknown.begin(), input.unknown.end());
148 
149  if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
150  if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
151  if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
152  if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
153 }
154 
156 {
157  if (!redeem_script.empty()) {
158  sigdata.redeem_script = redeem_script;
159  }
160  if (!witness_script.empty()) {
161  sigdata.witness_script = witness_script;
162  }
163  for (const auto& key_pair : hd_keypaths) {
164  sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
165  }
166 }
167 
169 {
170  if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
171  redeem_script = sigdata.redeem_script;
172  }
173  if (witness_script.empty() && !sigdata.witness_script.empty()) {
174  witness_script = sigdata.witness_script;
175  }
176  for (const auto& entry : sigdata.misc_pubkeys) {
177  hd_keypaths.emplace(entry.second);
178  }
179 }
180 
181 bool PSBTOutput::IsNull() const
182 {
183  return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty();
184 }
185 
186 void PSBTOutput::Merge(const PSBTOutput& output)
187 {
188  hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
189  unknown.insert(output.unknown.begin(), output.unknown.end());
190 
191  if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
192  if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
193 }
194 bool PSBTInputSigned(const PSBTInput& input)
195 {
196  return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
197 }
198 
200  size_t count = 0;
201  for (const auto& input : psbt.inputs) {
202  if (!PSBTInputSigned(input)) {
203  count++;
204  }
205  }
206 
207  return count;
208 }
209 
210 void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index)
211 {
212  CMutableTransaction& tx = *Assert(psbt.tx);
213  const CTxOut& out = tx.vout.at(index);
214  PSBTOutput& psbt_out = psbt.outputs.at(index);
215 
216  // Fill a SignatureData with output info
217  SignatureData sigdata;
218  psbt_out.FillSignatureData(sigdata);
219 
220  // Construct a would-be spend of this output, to update sigdata with.
221  // Note that ProduceSignature is used to fill in metadata (not actual signatures),
222  // so provider does not need to provide any private keys (it can be a HidingSigningProvider).
223  MutableTransactionSignatureCreator creator(&tx, /* index */ 0, out.nValue, SIGHASH_ALL);
224  ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
225 
226  // Put redeem_script, witness_script, key paths, into PSBTOutput.
227  psbt_out.FromSignatureData(sigdata);
228 }
229 
230 bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, int sighash, SignatureData* out_sigdata, bool use_dummy)
231 {
232  PSBTInput& input = psbt.inputs.at(index);
233  const CMutableTransaction& tx = *psbt.tx;
234 
235  if (PSBTInputSigned(input)) {
236  return true;
237  }
238 
239  // Fill SignatureData with input info
240  SignatureData sigdata;
241  input.FillSignatureData(sigdata);
242 
243  // Get UTXO
244  bool require_witness_sig = false;
245  CTxOut utxo;
246 
247  if (input.non_witness_utxo) {
248  // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
249  COutPoint prevout = tx.vin[index].prevout;
250  if (prevout.n >= input.non_witness_utxo->vout.size()) {
251  return false;
252  }
253  if (input.non_witness_utxo->GetHash() != prevout.hash) {
254  return false;
255  }
256  utxo = input.non_witness_utxo->vout[prevout.n];
257  } else if (!input.witness_utxo.IsNull()) {
258  utxo = input.witness_utxo;
259  // When we're taking our information from a witness UTXO, we can't verify it is actually data from
260  // the output being spent. This is safe in case a witness signature is produced (which includes this
261  // information directly in the hash), but not for non-witness signatures. Remember that we require
262  // a witness signature in this situation.
263  require_witness_sig = true;
264  } else {
265  return false;
266  }
267 
268  sigdata.witness = false;
269  bool sig_complete;
270  if (use_dummy) {
271  sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
272  } else {
273  MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue, sighash);
274  sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
275  }
276  // Verify that a witness signature was produced in case one was required.
277  if (require_witness_sig && !sigdata.witness) return false;
278  input.FromSignatureData(sigdata);
279 
280  // If we have a witness signature, put a witness UTXO.
281  // TODO: For segwit v1, we should remove the non_witness_utxo
282  if (sigdata.witness) {
283  input.witness_utxo = utxo;
284  // input.non_witness_utxo = nullptr;
285  }
286 
287  // Fill in the missing info
288  if (out_sigdata) {
289  out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
290  out_sigdata->missing_sigs = sigdata.missing_sigs;
291  out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
292  out_sigdata->missing_witness_script = sigdata.missing_witness_script;
293  }
294 
295  return sig_complete;
296 }
297 
299 {
300  // Finalize input signatures -- in case we have partial signatures that add up to a complete
301  // signature, but have not combined them yet (e.g. because the combiner that created this
302  // PartiallySignedTransaction did not understand them), this will combine them into a final
303  // script.
304  bool complete = true;
305  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
306  complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, SIGHASH_ALL);
307  }
308 
309  return complete;
310 }
311 
313 {
314  // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check
315  // whether a PSBT is finalized without finalizing it, so we just do this.
316  if (!FinalizePSBT(psbtx)) {
317  return false;
318  }
319 
320  result = *psbtx.tx;
321  for (unsigned int i = 0; i < result.vin.size(); ++i) {
322  result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
323  result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
324  }
325  return true;
326 }
327 
328 TransactionError CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs)
329 {
330  out = psbtxs[0]; // Copy the first one
331 
332  // Merge
333  for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
334  if (!out.Merge(*it)) {
336  }
337  }
338  return TransactionError::OK;
339 }
340 
341 std::string PSBTRoleName(PSBTRole role) {
342  switch (role) {
343  case PSBTRole::CREATOR: return "creator";
344  case PSBTRole::UPDATER: return "updater";
345  case PSBTRole::SIGNER: return "signer";
346  case PSBTRole::FINALIZER: return "finalizer";
347  case PSBTRole::EXTRACTOR: return "extractor";
348  // no default case, so the compiler can warn about missing cases
349  }
350  assert(false);
351 }
352 
353 bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
354 {
355  bool invalid;
356  std::string tx_data = DecodeBase64(base64_tx, &invalid);
357  if (invalid) {
358  error = "invalid base64";
359  return false;
360  }
361  return DecodeRawPSBT(psbt, tx_data, error);
362 }
363 
364 bool DecodeRawPSBT(PartiallySignedTransaction& psbt, const std::string& tx_data, std::string& error)
365 {
366  CDataStream ss_data(tx_data.data(), tx_data.data() + tx_data.size(), SER_NETWORK, PROTOCOL_VERSION);
367  try {
368  ss_data >> psbt;
369  if (!ss_data.empty()) {
370  error = "extra data after PSBT";
371  return false;
372  }
373  } catch (const std::exception& e) {
374  error = e.what();
375  return false;
376  }
377  return true;
378 }
CAmount nValue
Definition: transaction.h:131
bool AddInput(const CTxIn &txin, PSBTInput &psbtin)
Definition: psbt.cpp:40
bool IsNull() const
Definition: psbt.cpp:181
std::deque< CInv >::iterator it
assert(!tx.IsCoinBase())
CScript scriptPubKey
Definition: transaction.h:132
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
Definition: sign.h:65
Optional< CMutableTransaction > tx
Definition: psbt.h:392
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format...
Definition: sign.h:63
std::vector< CTxIn > vin
Definition: transaction.h:346
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:70
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:298
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:230
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:69
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:434
void Merge(const PSBTOutput &output)
Definition: psbt.cpp:186
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:108
std::vector< unsigned char > DecodeBase64(const char *p, bool *pf_invalid)
A version of CTransaction with the PSBT format.
Definition: psbt.h:390
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:202
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:68
CTxOut witness_utxo
Definition: psbt.h:51
A signature creator for transactions.
Definition: sign.h:37
bool IsNull() const
Definition: script.h:565
bool AddOutput(const CTxOut &txout, const PSBTOutput &psbtout)
Definition: psbt.cpp:53
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:72
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:312
CScript redeem_script
Definition: psbt.h:52
void Merge(const PSBTInput &input)
Definition: psbt.cpp:137
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:168
bool IsNull() const
Definition: transaction.h:149
std::string PSBTRoleName(PSBTRole role)
Definition: psbt.cpp:341
PSBTRole
Definition: psbt.h:559
A structure for PSBTs which contains per output information.
Definition: psbt.h:275
std::vector< PSBTOutput > outputs
Definition: psbt.h:394
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:279
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:71
An input of a transaction.
Definition: transaction.h:65
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:353
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:58
const SigningProvider & DUMMY_SIGNING_PROVIDER
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:56
bool IsNull() const
Definition: psbt.cpp:17
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:57
uint32_t n
Definition: transaction.h:30
CScriptWitness final_script_witness
Definition: psbt.h:55
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:280
A structure for PSBTs which contain per-input information.
Definition: psbt.h:48
An output of a transaction.
Definition: transaction.h:128
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:210
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
void SetNull()
Definition: script.h:567
std::vector< CTxOut > vout
Definition: transaction.h:347
std::vector< PSBTInput > inputs
Definition: psbt.h:393
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
Definition: sign.h:66
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction &psbt)
Counts the unsigned inputs of a PSBT.
Definition: psbt.cpp:199
bool DecodeRawPSBT(PartiallySignedTransaction &psbt, const std::string &tx_data, std::string &error)
Decode a raw (binary blob) PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:364
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:155
bool Merge(const PartiallySignedTransaction &psbt)
Merge psbt into this.
Definition: psbt.cpp:22
An interface to be implemented by keystores that support signing.
CScript witness_script
Definition: psbt.h:278
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
CScript redeem_script
Definition: psbt.h:277
bool empty() const
Definition: prevector.h:286
CTransactionRef non_witness_utxo
Definition: psbt.h:50
TransactionError
Definition: error.h:22
static int count
Definition: tests.c:35
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:199
A mutable version of CTransaction.
Definition: transaction.h:344
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:194
CScript final_script_sig
Definition: psbt.h:54
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:82
if(it !=peer.m_getdata_requests.end() &&!pfrom.fPauseSend)
bool complete
Stores whether the scriptSig and scriptWitness are complete.
Definition: sign.h:61
CScript witness_script
Definition: psbt.h:53
bool GetInputUTXO(CTxOut &utxo, int input_index) const
Finds the UTXO for a given input index.
Definition: psbt.cpp:60
void clear()
Definition: script.h:548
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
CScript redeem_script
The redeemScript (if any) for the input.
Definition: sign.h:64
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:395
bool witness
Stores whether the input this SigData corresponds to is a witness input.
Definition: sign.h:62
#define Assert(val)
Identity function.
Definition: check.h:57
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:67
bool IsNull() const
Definition: psbt.cpp:77
uint256 hash
Definition: transaction.h:29
TransactionError 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:328