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