Bitcoin Core  27.99.0
P2P Digital Currency
external_signer_scriptpubkeyman.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-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 
5 #include <chainparams.h>
6 #include <common/args.h>
7 #include <common/system.h>
8 #include <external_signer.h>
10 
11 #include <iostream>
12 #include <key_io.h>
13 #include <memory>
14 #include <stdexcept>
15 #include <string>
16 #include <univalue.h>
17 #include <utility>
18 #include <vector>
19 
20 namespace wallet {
21 bool ExternalSignerScriptPubKeyMan::SetupDescriptor(WalletBatch& batch, std::unique_ptr<Descriptor> desc)
22 {
26 
27  int64_t creation_time = GetTime();
28 
29  // Make the descriptor
30  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
31  m_wallet_descriptor = w_desc;
32 
33  // Store the descriptor
34  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
35  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
36  }
37 
38  // TopUp
39  TopUpWithDB(batch);
40 
42  return true;
43 }
44 
46  const std::string command = gArgs.GetArg("-signer", "");
47  if (command == "") throw std::runtime_error(std::string(__func__) + ": restart bitcoind with -signer=<cmd>");
48  std::vector<ExternalSigner> signers;
49  ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
50  if (signers.empty()) throw std::runtime_error(std::string(__func__) + ": No external signers found");
51  // TODO: add fingerprint argument instead of failing in case of multiple signers.
52  if (signers.size() > 1) throw std::runtime_error(std::string(__func__) + ": More than one external signer found. Please connect only one at a time.");
53  return signers[0];
54 }
55 
57 {
58  // TODO: avoid the need to infer a descriptor from inside a descriptor wallet
59  const CScript& scriptPubKey = GetScriptForDestination(dest);
60  auto provider = GetSolvingProvider(scriptPubKey);
61  auto descriptor = InferDescriptor(scriptPubKey, *provider);
62 
63  const UniValue& result = signer.DisplayAddress(descriptor->ToString());
64 
65  const UniValue& error = result.find_value("error");
66  if (error.isStr()) return util::Error{strprintf(_("Signer returned error: %s"), error.getValStr())};
67 
68  const UniValue& ret_address = result.find_value("address");
69  if (!ret_address.isStr()) return util::Error{_("Signer did not echo address")};
70 
71  if (ret_address.getValStr() != EncodeDestination(dest)) {
72  return util::Error{strprintf(_("Signer echoed unexpected address %s"), ret_address.getValStr())};
73  }
74 
75  return util::Result<void>();
76 }
77 
78 // If sign is true, transaction must previously have been filled
79 TransactionError ExternalSignerScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbt, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
80 {
81  if (!sign) {
82  return DescriptorScriptPubKeyMan::FillPSBT(psbt, txdata, sighash_type, false, bip32derivs, n_signed, finalize);
83  }
84 
85  // Already complete if every input is now signed
86  bool complete = true;
87  for (const auto& input : psbt.inputs) {
88  // TODO: for multisig wallets, we should only care if all _our_ inputs are signed
89  complete &= PSBTInputSigned(input);
90  }
91  if (complete) return TransactionError::OK;
92 
93  std::string strFailReason;
94  if(!GetExternalSigner().SignTransaction(psbt, strFailReason)) {
95  tfm::format(std::cerr, "Failed to sign: %s\n", strFailReason);
97  }
98  if (finalize) FinalizePSBT(psbt); // This won't work in a multisig setup
99  return TransactionError::OK;
100 }
101 } // namespace wallet
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:131
ArgsManager gArgs
Definition: args.cpp:41
const auto command
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:455
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
Enables interaction with an external signing device or service, such as a hardware wallet.
UniValue DisplayAddress(const std::string &descriptor) const
Display address on the device.
static bool Enumerate(const std::string &command, std::vector< ExternalSigner > &signers, const std::string chain)
Obtain a list of signers.
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
const std::string & getValStr() const
Definition: univalue.h:68
bool isStr() const
Definition: univalue.h:83
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool TopUpWithDB(WalletBatch &batch, unsigned int size=0)
Same as 'TopUp' but designed for use within a batch transaction context.
TransactionError FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, int sighash_type=SIGHASH_DEFAULT, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
TransactionError FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, int sighash_type=1, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
bool SetupDescriptor(WalletBatch &batch, std::unique_ptr< Descriptor >desc)
Provide a descriptor at setup time Returns false if already setup or setup fails, true if setup is su...
util::Result< void > DisplayAddress(const CTxDestination &dest, const ExternalSigner &signer) const
Display address on the device and verify that the returned value matches.
WalletStorage & m_storage
Access to the wallet database.
Definition: walletdb.h:191
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:248
Descriptor with some wallet metadata.
Definition: walletutil.h:85
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
TransactionError
Definition: error.h:22
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:287
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1060
@ WALLET_FLAG_EXTERNAL_SIGNER
Indicates that the wallet needs an external signer.
Definition: walletutil.h:77
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
Definition: psbt.cpp:293
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:480
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
A version of CTransaction with the PSBT format.
Definition: psbt.h:947
std::vector< PSBTInput > inputs
Definition: psbt.h:952
#define LOCK(cs)
Definition: sync.h:257
int64_t GetTime()
Definition: time.cpp:48
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:74
assert(!tx.IsCoinBase())