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