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