Bitcoin Core  31.0.0
P2P Digital Currency
external_signer_scriptpubkeyman.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-present 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 == "") return util::Error{Untranslated("restart bitcoind with -signer=<cmd>")};
51  std::vector<ExternalSigner> signers;
52  ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
53  if (signers.empty()) return util::Error{Untranslated("No external signers found")};
54  // TODO: add fingerprint argument instead of failing in case of multiple signers.
55  if (signers.size() > 1) return util::Error{Untranslated("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, std::optional<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  auto signer{GetExternalSigner()};
97  if (!signer) {
98  LogWarning("%s", util::ErrorString(signer).original);
99  return PSBTError::EXTERNAL_SIGNER_NOT_FOUND;
100  }
101 
102  std::string failure_reason;
103  if(!signer->SignTransaction(psbt, failure_reason)) {
104  LogWarning("Failed to sign: %s\n", failure_reason);
105  return PSBTError::EXTERNAL_SIGNER_FAILED;
106  }
107  if (finalize) FinalizePSBT(psbt); // This won't work in a multisig setup
108  return {};
109 }
110 } // namespace wallet
PSBTError
Definition: types.h:17
Enables interaction with an external signing device or service, such as a hardware wallet...
virtual bool IsWalletFlagSet(uint64_t) const =0
assert(!tx.IsCoinBase())
#define LogWarning(...)
Definition: log.h:96
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
util::Result< void > DisplayAddress(const CTxDestination &dest, const ExternalSigner &signer) const
Display address on the device and verify that the returned value matches.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:81
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:551
bool isStr() const
Definition: univalue.h:85
A version of CTransaction with the PSBT format.
Definition: psbt.h:1138
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
Access to the wallet database.
Definition: walletdb.h:192
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
const std::string & getValStr() const
Definition: univalue.h:68
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:234
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
static util::Result< ExternalSigner > GetExternalSigner()
Indicates that the wallet needs an external signer.
Definition: walletutil.h:56
#define LOCK(cs)
Definition: sync.h:258
std::optional< common::PSBTError > FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, std::optional< int > sighash_type=std::nullopt, 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.
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
std::vector< PSBTInput > inputs
Definition: psbt.h:1144
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...
Descriptor with some wallet metadata.
Definition: walletutil.h:63
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
ArgsManager gArgs
Definition: args.cpp:40
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
Definition: musig.c:106
const auto command
auto result
Definition: common-types.h:74
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:461
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:294
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
Definition: psbt.cpp:320
is a home for public enum and struct type definitions that are used internally by node code...
static bool Enumerate(const std::string &command, std::vector< ExternalSigner > &signers, const std::string &chain)
Obtain a list of signers.
Definition: musig.c:31
bool TopUpWithDB(WalletBatch &batch, unsigned int size=0)
Same as &#39;TopUp&#39; but designed for use within a batch transaction context.
std::optional< common::PSBTError > FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, std::optional< int > sighash_type=std::nullopt, 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.
WalletStorage & m_storage