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