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>
9 #include <node/types.h>
11 
12 #include <iostream>
13 #include <key_io.h>
14 #include <memory>
15 #include <stdexcept>
16 #include <string>
17 #include <univalue.h>
18 #include <utility>
19 #include <vector>
20 
21 using common::PSBTError;
22 
23 namespace wallet {
24 bool ExternalSignerScriptPubKeyMan::SetupDescriptor(WalletBatch& batch, std::unique_ptr<Descriptor> desc)
25 {
29 
30  int64_t creation_time = GetTime();
31 
32  // Make the descriptor
33  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
34  m_wallet_descriptor = w_desc;
35 
36  // Store the descriptor
37  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
38  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
39  }
40 
41  // TopUp
42  TopUpWithDB(batch);
43 
45  return true;
46 }
47 
49  const std::string command = gArgs.GetArg("-signer", "");
50  if (command == "") throw std::runtime_error(std::string(__func__) + ": restart bitcoind with -signer=<cmd>");
51  std::vector<ExternalSigner> signers;
52  ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
53  if (signers.empty()) throw std::runtime_error(std::string(__func__) + ": No external signers found");
54  // TODO: add fingerprint argument instead of failing in case of multiple signers.
55  if (signers.size() > 1) throw std::runtime_error(std::string(__func__) + ": More than one external signer found. Please connect only one at a time.");
56  return signers[0];
57 }
58 
60 {
61  // TODO: avoid the need to infer a descriptor from inside a descriptor wallet
62  const CScript& scriptPubKey = GetScriptForDestination(dest);
63  auto provider = GetSolvingProvider(scriptPubKey);
64  auto descriptor = InferDescriptor(scriptPubKey, *provider);
65 
66  const UniValue& result = signer.DisplayAddress(descriptor->ToString());
67 
68  const UniValue& error = result.find_value("error");
69  if (error.isStr()) return util::Error{strprintf(_("Signer returned error: %s"), error.getValStr())};
70 
71  const UniValue& ret_address = result.find_value("address");
72  if (!ret_address.isStr()) return util::Error{_("Signer did not echo address")};
73 
74  if (ret_address.getValStr() != EncodeDestination(dest)) {
75  return util::Error{strprintf(_("Signer echoed unexpected address %s"), ret_address.getValStr())};
76  }
77 
78  return util::Result<void>();
79 }
80 
81 // If sign is true, transaction must previously have been filled
82 std::optional<PSBTError> ExternalSignerScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbt, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
83 {
84  if (!sign) {
85  return DescriptorScriptPubKeyMan::FillPSBT(psbt, txdata, sighash_type, false, bip32derivs, n_signed, finalize);
86  }
87 
88  // Already complete if every input is now signed
89  bool complete = true;
90  for (const auto& input : psbt.inputs) {
91  // TODO: for multisig wallets, we should only care if all _our_ inputs are signed
92  complete &= PSBTInputSigned(input);
93  }
94  if (complete) return {};
95 
96  std::string strFailReason;
97  if(!GetExternalSigner().SignTransaction(psbt, strFailReason)) {
98  tfm::format(std::cerr, "Failed to sign: %s\n", strFailReason);
99  return PSBTError::EXTERNAL_SIGNER_FAILED;
100  }
101  if (finalize) FinalizePSBT(psbt); // This won't work in a multisig setup
102  return {};
103 }
104 } // 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
std::optional< common::PSBTError > 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.
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.
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...
std::optional< common::PSBTError > 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.
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:247
Descriptor with some wallet metadata.
Definition: walletutil.h:85
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:287
PSBTError
Definition: types.h:17
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
is a home for public enum and struct type definitions that are used by internally by node code,...
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:951
std::vector< PSBTInput > inputs
Definition: psbt.h:956
#define LOCK(cs)
Definition: sync.h:257
int64_t GetTime()
Definition: time.cpp:44
#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())