Bitcoin Core  24.99.0
P2P Digital Currency
psbtoperationsdialog.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2022 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 
6 
7 #include <core_io.h>
8 #include <fs.h>
9 #include <interfaces/node.h>
10 #include <key_io.h>
11 #include <node/psbt.h>
12 #include <policy/policy.h>
13 #include <qt/bitcoinunits.h>
14 #include <qt/forms/ui_psbtoperationsdialog.h>
15 #include <qt/guiutil.h>
16 #include <qt/optionsmodel.h>
17 #include <util/strencodings.h>
18 
19 #include <fstream>
20 #include <iostream>
21 #include <string>
22 
23 using node::AnalyzePSBT;
25 using node::PSBTAnalysis;
26 
28  QWidget* parent, WalletModel* wallet_model, ClientModel* client_model) : QDialog(parent, GUIUtil::dialog_flags),
29  m_ui(new Ui::PSBTOperationsDialog),
30  m_wallet_model(wallet_model),
31  m_client_model(client_model)
32 {
33  m_ui->setupUi(this);
34  setWindowTitle("PSBT Operations");
35 
36  connect(m_ui->signTransactionButton, &QPushButton::clicked, this, &PSBTOperationsDialog::signTransaction);
37  connect(m_ui->broadcastTransactionButton, &QPushButton::clicked, this, &PSBTOperationsDialog::broadcastTransaction);
38  connect(m_ui->copyToClipboardButton, &QPushButton::clicked, this, &PSBTOperationsDialog::copyToClipboard);
39  connect(m_ui->saveButton, &QPushButton::clicked, this, &PSBTOperationsDialog::saveTransaction);
40 
41  connect(m_ui->closeButton, &QPushButton::clicked, this, &PSBTOperationsDialog::close);
42 
43  m_ui->signTransactionButton->setEnabled(false);
44  m_ui->broadcastTransactionButton->setEnabled(false);
45 }
46 
48 {
49  delete m_ui;
50 }
51 
53 {
54  m_transaction_data = psbtx;
55 
56  bool complete = FinalizePSBT(psbtx); // Make sure all existing signatures are fully combined before checking for completeness.
57  if (m_wallet_model) {
58  size_t n_could_sign;
59  TransactionError err = m_wallet_model->wallet().fillPSBT(SIGHASH_ALL, /*sign=*/false, /*bip32derivs=*/true, &n_could_sign, m_transaction_data, complete);
60  if (err != TransactionError::OK) {
61  showStatus(tr("Failed to load transaction: %1")
62  .arg(QString::fromStdString(TransactionErrorString(err).translated)),
64  return;
65  }
66  m_ui->signTransactionButton->setEnabled(!complete && !m_wallet_model->wallet().privateKeysDisabled() && n_could_sign > 0);
67  } else {
68  m_ui->signTransactionButton->setEnabled(false);
69  }
70 
71  m_ui->broadcastTransactionButton->setEnabled(complete);
72 
74 }
75 
77 {
78  bool complete;
79  size_t n_signed;
80 
82 
83  TransactionError err = m_wallet_model->wallet().fillPSBT(SIGHASH_ALL, /*sign=*/true, /*bip32derivs=*/true, &n_signed, m_transaction_data, complete);
84 
85  if (err != TransactionError::OK) {
86  showStatus(tr("Failed to sign transaction: %1")
87  .arg(QString::fromStdString(TransactionErrorString(err).translated)), StatusLevel::ERR);
88  return;
89  }
90 
92 
93  if (!complete && !ctx.isValid()) {
94  showStatus(tr("Cannot sign inputs while wallet is locked."), StatusLevel::WARN);
95  } else if (!complete && n_signed < 1) {
96  showStatus(tr("Could not sign any more inputs."), StatusLevel::WARN);
97  } else if (!complete) {
98  showStatus(tr("Signed %1 inputs, but more signatures are still required.").arg(n_signed),
100  } else {
101  showStatus(tr("Signed transaction successfully. Transaction is ready to broadcast."),
103  m_ui->broadcastTransactionButton->setEnabled(true);
104  }
105 }
106 
108 {
111  // This is never expected to fail unless we were given a malformed PSBT
112  // (e.g. with an invalid signature.)
113  showStatus(tr("Unknown error processing transaction."), StatusLevel::ERR);
114  return;
115  }
116 
118  std::string err_string;
121 
122  if (error == TransactionError::OK) {
123  showStatus(tr("Transaction broadcast successfully! Transaction ID: %1")
124  .arg(QString::fromStdString(tx->GetHash().GetHex())), StatusLevel::INFO);
125  } else {
126  showStatus(tr("Transaction broadcast failed: %1")
127  .arg(QString::fromStdString(TransactionErrorString(error).translated)), StatusLevel::ERR);
128  }
129 }
130 
133  ssTx << m_transaction_data;
134  GUIUtil::setClipboard(EncodeBase64(ssTx.str()).c_str());
135  showStatus(tr("PSBT copied to clipboard."), StatusLevel::INFO);
136 }
137 
140  ssTx << m_transaction_data;
141 
142  QString selected_filter;
143  QString filename_suggestion = "";
144  bool first = true;
145  for (const CTxOut& out : m_transaction_data.tx->vout) {
146  if (!first) {
147  filename_suggestion.append("-");
148  }
149  CTxDestination address;
150  ExtractDestination(out.scriptPubKey, address);
152  QString address_str = QString::fromStdString(EncodeDestination(address));
153  filename_suggestion.append(address_str + "-" + amount);
154  first = false;
155  }
156  filename_suggestion.append(".psbt");
157  QString filename = GUIUtil::getSaveFileName(this,
158  tr("Save Transaction Data"), filename_suggestion,
159  //: Expanded name of the binary PSBT file format. See: BIP 174.
160  tr("Partially Signed Transaction (Binary)") + QLatin1String(" (*.psbt)"), &selected_filter);
161  if (filename.isEmpty()) {
162  return;
163  }
164  std::ofstream out{filename.toLocal8Bit().data(), std::ofstream::out | std::ofstream::binary};
165  out << ssTx.str();
166  out.close();
167  showStatus(tr("PSBT saved to disk."), StatusLevel::INFO);
168 }
169 
171  m_ui->transactionDescription->setText(QString::fromStdString(renderTransaction(m_transaction_data)));
173 }
174 
176 {
177  QString tx_description = "";
178  CAmount totalAmount = 0;
179  for (const CTxOut& out : psbtx.tx->vout) {
180  CTxDestination address;
181  ExtractDestination(out.scriptPubKey, address);
182  totalAmount += out.nValue;
183  tx_description.append(tr(" * Sends %1 to %2")
185  .arg(QString::fromStdString(EncodeDestination(address))));
186  tx_description.append("<br>");
187  }
188 
189  PSBTAnalysis analysis = AnalyzePSBT(psbtx);
190  tx_description.append(" * ");
191  if (!*analysis.fee) {
192  // This happens if the transaction is missing input UTXO information.
193  tx_description.append(tr("Unable to calculate transaction fee or total transaction amount."));
194  } else {
195  tx_description.append(tr("Pays transaction fee: "));
196  tx_description.append(BitcoinUnits::formatWithUnit(BitcoinUnit::BTC, *analysis.fee));
197 
198  // add total amount in all subdivision units
199  tx_description.append("<hr />");
200  QStringList alternativeUnits;
202  {
204  alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
205  }
206  }
207  tx_description.append(QString("<b>%1</b>: <b>%2</b>").arg(tr("Total Amount"))
209  tx_description.append(QString("<br /><span style='font-size:10pt; font-weight:normal;'>(=%1)</span>")
210  .arg(alternativeUnits.join(" " + tr("or") + " ")));
211  }
212 
213  size_t num_unsigned = CountPSBTUnsignedInputs(psbtx);
214  if (num_unsigned > 0) {
215  tx_description.append("<br><br>");
216  tx_description.append(tr("Transaction has %1 unsigned inputs.").arg(QString::number(num_unsigned)));
217  }
218 
219  return tx_description.toStdString();
220 }
221 
222 void PSBTOperationsDialog::showStatus(const QString &msg, StatusLevel level) {
223  m_ui->statusBar->setText(msg);
224  switch (level) {
225  case StatusLevel::INFO: {
226  m_ui->statusBar->setStyleSheet("QLabel { background-color : lightgreen }");
227  break;
228  }
229  case StatusLevel::WARN: {
230  m_ui->statusBar->setStyleSheet("QLabel { background-color : orange }");
231  break;
232  }
233  case StatusLevel::ERR: {
234  m_ui->statusBar->setStyleSheet("QLabel { background-color : red }");
235  break;
236  }
237  }
238  m_ui->statusBar->show();
239 }
240 
242  if (!m_wallet_model) {
243  return 0;
244  }
245 
246  size_t n_signed;
247  bool complete;
248  TransactionError err = m_wallet_model->wallet().fillPSBT(SIGHASH_ALL, /*sign=*/false, /*bip32derivs=*/false, &n_signed, m_transaction_data, complete);
249 
250  if (err != TransactionError::OK) {
251  return 0;
252  }
253  return n_signed;
254 }
255 
257  PSBTAnalysis analysis = AnalyzePSBT(psbtx);
258  size_t n_could_sign = couldSignInputs(psbtx);
259 
260  switch (analysis.next) {
261  case PSBTRole::UPDATER: {
262  showStatus(tr("Transaction is missing some information about inputs."), StatusLevel::WARN);
263  break;
264  }
265  case PSBTRole::SIGNER: {
266  QString need_sig_text = tr("Transaction still needs signature(s).");
268  if (!m_wallet_model) {
269  need_sig_text += " " + tr("(But no wallet is loaded.)");
270  level = StatusLevel::WARN;
271  } else if (m_wallet_model->wallet().privateKeysDisabled()) {
272  need_sig_text += " " + tr("(But this wallet cannot sign transactions.)");
273  level = StatusLevel::WARN;
274  } else if (n_could_sign < 1) {
275  need_sig_text += " " + tr("(But this wallet does not have the right keys.)"); // XXX wording
276  level = StatusLevel::WARN;
277  }
278  showStatus(need_sig_text, level);
279  break;
280  }
281  case PSBTRole::FINALIZER:
282  case PSBTRole::EXTRACTOR: {
283  showStatus(tr("Transaction is fully signed and ready for broadcast."), StatusLevel::INFO);
284  break;
285  }
286  default: {
287  showStatus(tr("Transaction status is unknown."), StatusLevel::ERR);
288  break;
289  }
290  }
291 }
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static QString format(Unit unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=SeparatorStyle::STANDARD, bool justify=false)
Format as string.
static QString formatHtmlWithUnit(Unit unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=SeparatorStyle::STANDARD)
Format as HTML string (with unit)
static QList< Unit > availableUnits()
Get list of units, for drop-down box.
static QString formatWithUnit(Unit unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=SeparatorStyle::STANDARD)
Format as string (with unit)
Unit
Bitcoin units.
Definition: bitcoinunits.h:42
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition: feerate.h:65
An output of a transaction.
Definition: transaction.h:158
CScript scriptPubKey
Definition: transaction.h:161
CAmount nValue
Definition: transaction.h:160
Model for Bitcoin network client.
Definition: clientmodel.h:54
interfaces::Node & node() const
Definition: clientmodel.h:61
OptionsModel * getOptionsModel()
std::string str() const
Definition: streams.h:207
BitcoinUnit getDisplayUnit() const
Definition: optionsmodel.h:94
Dialog showing transaction details.
PartiallySignedTransaction m_transaction_data
PSBTOperationsDialog(QWidget *parent, WalletModel *walletModel, ClientModel *clientModel)
Ui::PSBTOperationsDialog * m_ui
void openWithPSBT(PartiallySignedTransaction psbtx)
size_t couldSignInputs(const PartiallySignedTransaction &psbtx)
void showTransactionStatus(const PartiallySignedTransaction &psbtx)
void showStatus(const QString &msg, StatusLevel level)
std::string renderTransaction(const PartiallySignedTransaction &psbtx)
Interface to Bitcoin wallet from Qt view code.
Definition: walletmodel.h:53
interfaces::Wallet & wallet() const
Definition: walletmodel.h:143
UnlockContext requestUnlock()
virtual TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, std::string &err_string)=0
Broadcast transaction.
virtual TransactionError fillPSBT(int sighash_type, bool sign, bool bip32derivs, size_t *n_signed, PartiallySignedTransaction &psbtx, bool &complete)=0
Fill PSBT.
virtual bool privateKeysDisabled()=0
bilingual_str TransactionErrorString(const TransactionError err)
Definition: error.cpp:13
TransactionError
Definition: error.h:22
@ SIGHASH_ALL
Definition: interpreter.h:28
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:276
bool error(const char *fmt, const Args &... args)
Definition: logging.h:261
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:60
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut)
Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix when ...
Definition: guiutil.cpp:305
constexpr auto dialog_flags
Definition: guiutil.h:60
void setClipboard(const QString &str)
Definition: guiutil.cpp:653
PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
Provides helpful miscellaneous information about where a PSBT is in the signing workflow.
Definition: psbt.cpp:16
static const CFeeRate DEFAULT_MAX_RAW_TX_FEE_RATE
Maximum fee rate for sendrawtransaction and testmempoolaccept RPC calls.
Definition: transaction.h:26
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction &psbt)
Counts the unsigned inputs of a PSBT.
Definition: psbt.cpp:324
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:460
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:445
@ SER_NETWORK
Definition: serialize.h:131
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:237
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
A mutable version of CTransaction.
Definition: transaction.h:380
A version of CTransaction with the PSBT format.
Definition: psbt.h:947
std::optional< CMutableTransaction > tx
Definition: psbt.h:948
Holds the results of AnalyzePSBT (miscellaneous information about a PSBT)
Definition: psbt.h:30
std::optional< CAmount > fee
Amount of fee being paid by the transaction.
Definition: psbt.h:33
PSBTRole next
Which of the BIP 174 roles needs to handle the transaction next.
Definition: psbt.h:35
std::string EncodeBase64(Span< const unsigned char > input)
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12