Bitcoin ABC  0.26.3
P2P Digital Currency
psbt.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2018 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/strencodings.h>
8 
10  const CMutableTransaction &txIn)
11  : tx(txIn) {
12  inputs.resize(txIn.vin.size());
13  outputs.resize(txIn.vout.size());
14 }
15 
17  return !tx && inputs.empty() && outputs.empty() && unknown.empty();
18 }
19 
21  // Prohibited to merge two PSBTs over different transactions
22  if (tx->GetId() != psbt.tx->GetId()) {
23  return false;
24  }
25 
26  for (size_t i = 0; i < inputs.size(); ++i) {
27  inputs[i].Merge(psbt.inputs[i]);
28  }
29  for (size_t i = 0; i < outputs.size(); ++i) {
30  outputs[i].Merge(psbt.outputs[i]);
31  }
32  unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
33 
34  return true;
35 }
36 
38  PSBTInput &psbtin) {
39  if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
40  return false;
41  }
42  tx->vin.push_back(txin);
43  psbtin.partial_sigs.clear();
44  psbtin.final_script_sig.clear();
45  inputs.push_back(psbtin);
46  return true;
47 }
48 
50  const PSBTOutput &psbtout) {
51  tx->vout.push_back(txout);
52  outputs.push_back(psbtout);
53  return true;
54 }
55 
57  int input_index) const {
58  PSBTInput input = inputs[input_index];
59  if (!input.utxo.IsNull()) {
60  utxo = input.utxo;
61  } else {
62  return false;
63  }
64  return true;
65 }
66 
67 bool PSBTInput::IsNull() const {
68  return utxo.IsNull() && partial_sigs.empty() && unknown.empty() &&
69  hd_keypaths.empty() && redeem_script.empty();
70 }
71 
73  if (!final_script_sig.empty()) {
74  sigdata.scriptSig = final_script_sig;
75  sigdata.complete = true;
76  }
77  if (sigdata.complete) {
78  return;
79  }
80 
81  sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
82  if (!redeem_script.empty()) {
83  sigdata.redeem_script = redeem_script;
84  }
85  for (const auto &key_pair : hd_keypaths) {
86  sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
87  }
88 }
89 
91  if (sigdata.complete) {
92  partial_sigs.clear();
93  hd_keypaths.clear();
95 
96  if (!sigdata.scriptSig.empty()) {
97  final_script_sig = sigdata.scriptSig;
98  }
99  return;
100  }
101 
102  partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
103  if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
104  redeem_script = sigdata.redeem_script;
105  }
106  for (const auto &entry : sigdata.misc_pubkeys) {
107  hd_keypaths.emplace(entry.second);
108  }
109 }
110 
111 void PSBTInput::Merge(const PSBTInput &input) {
112  if (utxo.IsNull() && !input.utxo.IsNull()) {
113  utxo = input.utxo;
114  }
115 
116  partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
117  hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
118  unknown.insert(input.unknown.begin(), input.unknown.end());
119 
120  if (redeem_script.empty() && !input.redeem_script.empty()) {
122  }
123  if (final_script_sig.empty() && !input.final_script_sig.empty()) {
125  }
126 }
127 
129  if (!redeem_script.empty()) {
130  sigdata.redeem_script = redeem_script;
131  }
132  for (const auto &key_pair : hd_keypaths) {
133  sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
134  }
135 }
136 
138  if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
139  redeem_script = sigdata.redeem_script;
140  }
141  for (const auto &entry : sigdata.misc_pubkeys) {
142  hd_keypaths.emplace(entry.second);
143  }
144 }
145 
146 bool PSBTOutput::IsNull() const {
147  return redeem_script.empty() && hd_keypaths.empty() && unknown.empty();
148 }
149 
150 void PSBTOutput::Merge(const PSBTOutput &output) {
151  hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
152  unknown.insert(output.unknown.begin(), output.unknown.end());
153 
154  if (redeem_script.empty() && !output.redeem_script.empty()) {
155  redeem_script = output.redeem_script;
156  }
157 }
158 
159 bool PSBTInputSigned(const PSBTInput &input) {
160  return !input.final_script_sig.empty();
161 }
162 
163 void UpdatePSBTOutput(const SigningProvider &provider,
164  PartiallySignedTransaction &psbt, int index) {
165  const CTxOut &out = psbt.tx->vout.at(index);
166  PSBTOutput &psbt_out = psbt.outputs.at(index);
167 
168  // Fill a SignatureData with output info
169  SignatureData sigdata;
170  psbt_out.FillSignatureData(sigdata);
171 
172  // Construct a would-be spend of this output, to update sigdata with.
173  // Note that ProduceSignature is used to fill in metadata (not actual
174  // signatures), so provider does not need to provide any private keys (it
175  // can be a HidingSigningProvider).
177  psbt.tx ? &psbt.tx.value() : nullptr, /* index */ 0, out.nValue,
178  SigHashType().withForkId());
179  ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
180 
181  // Put redeem_script and key paths, into PSBTOutput.
182  psbt_out.FromSignatureData(sigdata);
183 }
184 
185 bool SignPSBTInput(const SigningProvider &provider,
186  PartiallySignedTransaction &psbt, int index,
187  SigHashType sighash, SignatureData *out_sigdata,
188  bool use_dummy) {
189  PSBTInput &input = psbt.inputs.at(index);
190  const CMutableTransaction &tx = *psbt.tx;
191 
192  if (PSBTInputSigned(input)) {
193  return true;
194  }
195 
196  // Fill SignatureData with input info
197  SignatureData sigdata;
198  input.FillSignatureData(sigdata);
199 
200  // Get UTXO
201  CTxOut utxo;
202 
203  if (input.utxo.IsNull()) {
204  return false;
205  }
206 
207  utxo = input.utxo;
208 
209  bool sig_complete{false};
210  if (use_dummy) {
211  sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR,
212  utxo.scriptPubKey, sigdata);
213  } else {
214  MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue,
215  sighash);
216  sig_complete =
217  ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
218  }
219  input.FromSignatureData(sigdata);
220 
221  // Fill in the missing info
222  if (out_sigdata != nullptr) {
223  out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
224  out_sigdata->missing_sigs = sigdata.missing_sigs;
225  out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
226  }
227 
228  return sig_complete;
229 }
230 
232  // Finalize input signatures -- in case we have partial signatures that add
233  // up to a complete
234  // signature, but have not combined them yet (e.g. because the combiner
235  // that created this PartiallySignedTransaction did not understand them),
236  // this will combine them into a final script.
237  bool complete = true;
238  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
239  complete &=
241  }
242 
243  return complete;
244 }
245 
247  CMutableTransaction &result) {
248  // It's not safe to extract a PSBT that isn't finalized, and there's no easy
249  // way to check
250  // whether a PSBT is finalized without finalizing it, so we just do this.
251  if (!FinalizePSBT(psbtx)) {
252  return false;
253  }
254 
255  result = *psbtx.tx;
256  for (size_t i = 0; i < result.vin.size(); ++i) {
257  result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
258  }
259  return true;
260 }
261 
264  const std::vector<PartiallySignedTransaction> &psbtxs) {
265  // Copy the first one
266  out = psbtxs[0];
267 
268  // Merge
269  for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
270  if (!out.Merge(*it)) {
272  }
273  }
274 
275  return TransactionError::OK;
276 }
277 
278 std::string PSBTRoleName(const PSBTRole role) {
279  switch (role) {
280  case PSBTRole::CREATOR:
281  return "creator";
282  case PSBTRole::UPDATER:
283  return "updater";
284  case PSBTRole::SIGNER:
285  return "signer";
286  case PSBTRole::FINALIZER:
287  return "finalizer";
288  case PSBTRole::EXTRACTOR:
289  return "extractor";
290  // no default case, so the compiler can warn about missing cases
291  }
292  assert(false);
293 }
294 
296  const std::string &base64_tx, std::string &error) {
297  bool invalid;
298  std::string tx_data = DecodeBase64(base64_tx, &invalid);
299  if (invalid) {
300  error = "invalid base64";
301  return false;
302  }
303  return DecodeRawPSBT(psbt, tx_data, error);
304 }
305 
306 bool DecodeRawPSBT(PartiallySignedTransaction &psbt, const std::string &tx_data,
307  std::string &error) {
308  CDataStream ss_data(tx_data.data(), tx_data.data() + tx_data.size(),
310  try {
311  ss_data >> psbt;
312  if (!ss_data.empty()) {
313  error = "extra data after PSBT";
314  return false;
315  }
316  } catch (const std::exception &e) {
317  error = e.what();
318  return false;
319  }
320  return true;
321 }
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:197
bool empty() const
Definition: streams.h:281
A mutable version of CTransaction.
Definition: transaction.h:280
std::vector< CTxOut > vout
Definition: transaction.h:283
std::vector< CTxIn > vin
Definition: transaction.h:282
void clear()
Definition: script.h:554
An input of a transaction.
Definition: transaction.h:61
An output of a transaction.
Definition: transaction.h:130
CScript scriptPubKey
Definition: transaction.h:133
Amount nValue
Definition: transaction.h:132
bool IsNull() const
Definition: transaction.h:147
A signature creator for transactions.
Definition: sign.h:38
Signature hash type wrapper class.
Definition: sighashtype.h:37
An interface to be implemented by keystores that support signing.
bool empty() const
Definition: prevector.h:388
TransactionError
Definition: error.h:22
bool DecodeRawPSBT(PartiallySignedTransaction &psbt, const std::string &tx_data, std::string &error)
Decode a raw (binary blob) PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:306
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:295
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:163
std::string PSBTRoleName(const PSBTRole role)
Definition: psbt.cpp:278
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:246
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:159
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:263
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, SigHashType sighash, SignatureData *out_sigdata, bool use_dummy)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:185
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:231
PSBTRole
Definition: psbt.h:506
@ SER_NETWORK
Definition: serialize.h:166
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
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:419
const SigningProvider & DUMMY_SIGNING_PROVIDER
std::vector< uint8_t > DecodeBase64(const char *p, bool *pf_invalid)
A structure for PSBTs which contain per-input information.
Definition: psbt.h:44
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:48
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:49
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:72
bool IsNull() const
Definition: psbt.cpp:67
void Merge(const PSBTInput &input)
Definition: psbt.cpp:111
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:50
CScript redeem_script
Definition: psbt.h:46
CScript final_script_sig
Definition: psbt.h:47
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:90
CTxOut utxo
Definition: psbt.h:45
A structure for PSBTs which contains per output information.
Definition: psbt.h:233
bool IsNull() const
Definition: psbt.cpp:146
void Merge(const PSBTOutput &output)
Definition: psbt.cpp:150
CScript redeem_script
Definition: psbt.h:234
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:235
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:236
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:128
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:137
A version of CTransaction with the PSBT format.
Definition: psbt.h:334
bool Merge(const PartiallySignedTransaction &psbt)
Merge psbt into this.
Definition: psbt.cpp:20
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:338
bool IsNull() const
Definition: psbt.cpp:16
bool GetInputUTXO(CTxOut &utxo, int input_index) const
Finds the UTXO for a given input index.
Definition: psbt.cpp:56
bool AddOutput(const CTxOut &txout, const PSBTOutput &psbtout)
Definition: psbt.cpp:49
std::vector< PSBTInput > inputs
Definition: psbt.h:336
std::optional< CMutableTransaction > tx
Definition: psbt.h:335
bool AddInput(const CTxIn &txin, PSBTInput &psbtin)
Definition: psbt.cpp:37
std::vector< PSBTOutput > outputs
Definition: psbt.h:337
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:83
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:81
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input.
Definition: sign.h:76
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:77
CScript scriptSig
The scriptSig of an input.
Definition: sign.h:71
CScript redeem_script
The redeemScript (if any) for the input.
Definition: sign.h:73
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:79
bool complete
Stores whether the scriptSig are complete.
Definition: sign.h:68
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11