Skip to content

Commit 4373414

Browse files
committed
Merge bitcoin/bitcoin#29130: wallet: Add createwalletdescriptor and gethdkeys RPCs for adding new automatically generated descriptors
746b6d8 test: Add test for createwalletdescriptor (Ava Chow) 2402b63 wallet: Test upgrade of pre-taproot wallet to have tr() descriptors (Ava Chow) 460ae1b wallet, rpc: Add createwalletdescriptor RPC (Ava Chow) 8e1a475 wallet: Be able to retrieve single key from descriptors (Ava Chow) 85b1fb1 wallet: Add GetActiveHDPubKeys to retrieve xpubs from active descriptors (Ava Chow) 73926f2 wallet, descspkm: Refactor wallet descriptor generation to standalone func (Andrew Chow) 54e74f4 wallet: Refactor function for single DescSPKM setup (Andrew Chow) 3b09d0e tests: Test for gethdkeys (Ava Chow) 5febe28 wallet, rpc: Add gethdkeys RPC (Ava Chow) 66632e5 wallet: Add IsActiveScriptPubKeyMan (Ava Chow) fa6a259 desc spkm: Add functions to retrieve specific private keys (Ava Chow) fe67841 descriptor: Be able to get the pubkeys involved in a descriptor (Ava Chow) ef67458 key: Add constructor for CExtKey that takes CExtPubKey and CKey (Ava Chow) Pull request description: This PR adds a `createwalletdescriptor` RPC which allows users to add new automatically generated descriptors to their wallet, e.g. to upgrade a 0.21.x wallet to contain a taproot descriptor. This RPC takes 3 arguments: the output type to create a descriptor for, whether the descriptor will be internal or external, and the HD key to use if the user wishes to use a specific key. The HD key is an optional parameter. If it is not specified, the wallet will use the key shared by the active descriptors, if they are all single key. For most users in the expected upgrade scenario, this should be sufficient. In more advanced cases, the user must specify the HD key to use. Currently, specified HD keys must already exist in the wallet. To make it easier for the user to know, `gethdkeys` is also added to list out the HD keys in use by all of the descriptors in the wallet. This will include all HD keys, whether we have the private key, for it, which descriptors use it and their activeness, and optionally the extended private key. In this way, users with more complex wallets will be still be able to get HD keys from their wallet for use in other scenarios, and if they want to use `createwalletdescriptor`, they can easily get the keys that they can specify to it. See also bitcoin/bitcoin#26728 (comment) ACKs for top commit: Sjors: re-utACK 746b6d8 furszy: ACK 746b6d8 ryanofsky: Code review ACK 746b6d8, and this looks ready to merge. There were various suggested changes since last review where main change seems to be switching `gethdkeys` output to use normalized descriptors (removing hardened path components). Tree-SHA512: f2849101e6fbf1f59cb031eaaaee97af5b1ae92aaab54c5716940d210f08ab4fc952df2725b636596cd5747b8f5beb1a7a533425bc10d09da02659473516fbda
2 parents d1e9a02 + 746b6d8 commit 4373414

16 files changed

+775
-63
lines changed

src/key.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,12 @@ struct CExtKey {
223223
a.key == b.key;
224224
}
225225

226+
CExtKey() = default;
227+
CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in)
228+
{
229+
std::copy(xpub.vchFingerprint, xpub.vchFingerprint + sizeof(xpub.vchFingerprint), vchFingerprint);
230+
}
231+
226232
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
227233
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
228234
[[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;

src/rpc/client.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,11 @@ static const CRPCConvertParam vRPCConvertParams[] =
277277
{ "logging", 1, "exclude" },
278278
{ "disconnectnode", 1, "nodeid" },
279279
{ "upgradewallet", 0, "version" },
280+
{ "gethdkeys", 0, "active_only" },
281+
{ "gethdkeys", 0, "options" },
282+
{ "gethdkeys", 0, "private" },
283+
{ "createwalletdescriptor", 1, "options" },
284+
{ "createwalletdescriptor", 1, "internal" },
280285
// Echo with conversion (For testing only)
281286
{ "echojson", 0, "arg0" },
282287
{ "echojson", 1, "arg1" },

src/script/descriptor.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,11 @@ struct PubkeyProvider
212212

213213
/** Derive a private key, if private data is available in arg. */
214214
virtual bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const = 0;
215+
216+
/** Return the non-extended public key for this PubkeyProvider, if it has one. */
217+
virtual std::optional<CPubKey> GetRootPubKey() const = 0;
218+
/** Return the extended public key for this PubkeyProvider, if it has one. */
219+
virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
215220
};
216221

217222
class OriginPubkeyProvider final : public PubkeyProvider
@@ -265,6 +270,14 @@ class OriginPubkeyProvider final : public PubkeyProvider
265270
{
266271
return m_provider->GetPrivKey(pos, arg, key);
267272
}
273+
std::optional<CPubKey> GetRootPubKey() const override
274+
{
275+
return m_provider->GetRootPubKey();
276+
}
277+
std::optional<CExtPubKey> GetRootExtPubKey() const override
278+
{
279+
return m_provider->GetRootExtPubKey();
280+
}
268281
};
269282

270283
/** An object representing a parsed constant public key in a descriptor. */
@@ -310,6 +323,14 @@ class ConstPubkeyProvider final : public PubkeyProvider
310323
{
311324
return arg.GetKey(m_pubkey.GetID(), key);
312325
}
326+
std::optional<CPubKey> GetRootPubKey() const override
327+
{
328+
return m_pubkey;
329+
}
330+
std::optional<CExtPubKey> GetRootExtPubKey() const override
331+
{
332+
return std::nullopt;
333+
}
313334
};
314335

315336
enum class DeriveType {
@@ -525,6 +546,14 @@ class BIP32PubkeyProvider final : public PubkeyProvider
525546
key = extkey.key;
526547
return true;
527548
}
549+
std::optional<CPubKey> GetRootPubKey() const override
550+
{
551+
return std::nullopt;
552+
}
553+
std::optional<CExtPubKey> GetRootExtPubKey() const override
554+
{
555+
return m_root_extkey;
556+
}
528557
};
529558

530559
/** Base class for all Descriptor implementations. */
@@ -720,6 +749,19 @@ class DescriptorImpl : public Descriptor
720749
std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
721750

722751
std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
752+
753+
void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
754+
{
755+
for (const auto& p : m_pubkey_args) {
756+
std::optional<CPubKey> pub = p->GetRootPubKey();
757+
if (pub) pubkeys.insert(*pub);
758+
std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
759+
if (ext_pub) ext_pubs.insert(*ext_pub);
760+
}
761+
for (const auto& arg : m_subdescriptor_args) {
762+
arg->GetPubKeys(pubkeys, ext_pubs);
763+
}
764+
}
723765
};
724766

725767
/** A parsed addr(A) descriptor. */

src/script/descriptor.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,13 @@ struct Descriptor {
158158

159159
/** Get the maximum size number of stack elements for satisfying this descriptor. */
160160
virtual std::optional<int64_t> MaxSatisfactionElems() const = 0;
161+
162+
/** Return all (extended) public keys for this descriptor, including any from subdescriptors.
163+
*
164+
* @param[out] pubkeys Any public keys
165+
* @param[out] ext_pubs Any extended public keys
166+
*/
167+
virtual void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const = 0;
161168
};
162169

163170
/** Parse a `descriptor` string. Included private keys are put in `out`.

src/wallet/rpc/wallet.cpp

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,217 @@ static RPCHelpMan migratewallet()
817817
};
818818
}
819819

820+
RPCHelpMan gethdkeys()
821+
{
822+
return RPCHelpMan{
823+
"gethdkeys",
824+
"\nList all BIP 32 HD keys in the wallet and which descriptors use them.\n",
825+
{
826+
{"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", {
827+
{"active_only", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show the keys for only active descriptors"},
828+
{"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private keys"}
829+
}},
830+
},
831+
RPCResult{RPCResult::Type::ARR, "", "", {
832+
{
833+
{RPCResult::Type::OBJ, "", "", {
834+
{RPCResult::Type::STR, "xpub", "The extended public key"},
835+
{RPCResult::Type::BOOL, "has_private", "Whether the wallet has the private key for this xpub"},
836+
{RPCResult::Type::STR, "xprv", /*optional=*/true, "The extended private key if \"private\" is true"},
837+
{RPCResult::Type::ARR, "descriptors", "Array of descriptor objects that use this HD key",
838+
{
839+
{RPCResult::Type::OBJ, "", "", {
840+
{RPCResult::Type::STR, "desc", "Descriptor string representation"},
841+
{RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"},
842+
}},
843+
}},
844+
}},
845+
}
846+
}},
847+
RPCExamples{
848+
HelpExampleCli("gethdkeys", "") + HelpExampleRpc("gethdkeys", "")
849+
+ HelpExampleCliNamed("gethdkeys", {{"active_only", "true"}, {"private", "true"}}) + HelpExampleRpcNamed("gethdkeys", {{"active_only", "true"}, {"private", "true"}})
850+
},
851+
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
852+
{
853+
const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);
854+
if (!wallet) return UniValue::VNULL;
855+
856+
if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
857+
throw JSONRPCError(RPC_WALLET_ERROR, "gethdkeys is not available for non-descriptor wallets");
858+
}
859+
860+
LOCK(wallet->cs_wallet);
861+
862+
UniValue options{request.params[0].isNull() ? UniValue::VOBJ : request.params[0]};
863+
const bool active_only{options.exists("active_only") ? options["active_only"].get_bool() : false};
864+
const bool priv{options.exists("private") ? options["private"].get_bool() : false};
865+
if (priv) {
866+
EnsureWalletIsUnlocked(*wallet);
867+
}
868+
869+
870+
std::set<ScriptPubKeyMan*> spkms;
871+
if (active_only) {
872+
spkms = wallet->GetActiveScriptPubKeyMans();
873+
} else {
874+
spkms = wallet->GetAllScriptPubKeyMans();
875+
}
876+
877+
std::map<CExtPubKey, std::set<std::tuple<std::string, bool, bool>>> wallet_xpubs;
878+
std::map<CExtPubKey, CExtKey> wallet_xprvs;
879+
for (auto* spkm : spkms) {
880+
auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};
881+
CHECK_NONFATAL(desc_spkm);
882+
LOCK(desc_spkm->cs_desc_man);
883+
WalletDescriptor w_desc = desc_spkm->GetWalletDescriptor();
884+
885+
// Retrieve the pubkeys from the descriptor
886+
std::set<CPubKey> desc_pubkeys;
887+
std::set<CExtPubKey> desc_xpubs;
888+
w_desc.descriptor->GetPubKeys(desc_pubkeys, desc_xpubs);
889+
for (const CExtPubKey& xpub : desc_xpubs) {
890+
std::string desc_str;
891+
bool ok = desc_spkm->GetDescriptorString(desc_str, false);
892+
CHECK_NONFATAL(ok);
893+
wallet_xpubs[xpub].emplace(desc_str, wallet->IsActiveScriptPubKeyMan(*spkm), desc_spkm->HasPrivKey(xpub.pubkey.GetID()));
894+
if (std::optional<CKey> key = priv ? desc_spkm->GetKey(xpub.pubkey.GetID()) : std::nullopt) {
895+
wallet_xprvs[xpub] = CExtKey(xpub, *key);
896+
}
897+
}
898+
}
899+
900+
UniValue response(UniValue::VARR);
901+
for (const auto& [xpub, descs] : wallet_xpubs) {
902+
bool has_xprv = false;
903+
UniValue descriptors(UniValue::VARR);
904+
for (const auto& [desc, active, has_priv] : descs) {
905+
UniValue d(UniValue::VOBJ);
906+
d.pushKV("desc", desc);
907+
d.pushKV("active", active);
908+
has_xprv |= has_priv;
909+
910+
descriptors.push_back(std::move(d));
911+
}
912+
UniValue xpub_info(UniValue::VOBJ);
913+
xpub_info.pushKV("xpub", EncodeExtPubKey(xpub));
914+
xpub_info.pushKV("has_private", has_xprv);
915+
if (priv) {
916+
xpub_info.pushKV("xprv", EncodeExtKey(wallet_xprvs.at(xpub)));
917+
}
918+
xpub_info.pushKV("descriptors", std::move(descriptors));
919+
920+
response.push_back(std::move(xpub_info));
921+
}
922+
923+
return response;
924+
},
925+
};
926+
}
927+
928+
static RPCHelpMan createwalletdescriptor()
929+
{
930+
return RPCHelpMan{"createwalletdescriptor",
931+
"Creates the wallet's descriptor for the given address type. "
932+
"The address type must be one that the wallet does not already have a descriptor for."
933+
+ HELP_REQUIRING_PASSPHRASE,
934+
{
935+
{"type", RPCArg::Type::STR, RPCArg::Optional::NO, "The address type the descriptor will produce. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
936+
{"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", {
937+
{"internal", RPCArg::Type::BOOL, RPCArg::DefaultHint{"Both external and internal will be generated unless this parameter is specified"}, "Whether to only make one descriptor that is internal (if parameter is true) or external (if parameter is false)"},
938+
{"hdkey", RPCArg::Type::STR, RPCArg::DefaultHint{"The HD key used by all other active descriptors"}, "The HD key that the wallet knows the private key of, listed using 'gethdkeys', to use for this descriptor's key"},
939+
}},
940+
},
941+
RPCResult{
942+
RPCResult::Type::OBJ, "", "",
943+
{
944+
{RPCResult::Type::ARR, "descs", "The public descriptors that were added to the wallet",
945+
{{RPCResult::Type::STR, "", ""}}
946+
}
947+
},
948+
},
949+
RPCExamples{
950+
HelpExampleCli("createwalletdescriptor", "bech32m")
951+
+ HelpExampleRpc("createwalletdescriptor", "bech32m")
952+
},
953+
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
954+
{
955+
std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
956+
if (!pwallet) return UniValue::VNULL;
957+
958+
// Make sure wallet is a descriptor wallet
959+
if (!pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
960+
throw JSONRPCError(RPC_WALLET_ERROR, "createwalletdescriptor is not available for non-descriptor wallets");
961+
}
962+
963+
std::optional<OutputType> output_type = ParseOutputType(request.params[0].get_str());
964+
if (!output_type) {
965+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str()));
966+
}
967+
968+
UniValue options{request.params[1].isNull() ? UniValue::VOBJ : request.params[1]};
969+
UniValue internal_only{options["internal"]};
970+
UniValue hdkey{options["hdkey"]};
971+
972+
std::vector<bool> internals;
973+
if (internal_only.isNull()) {
974+
internals.push_back(false);
975+
internals.push_back(true);
976+
} else {
977+
internals.push_back(internal_only.get_bool());
978+
}
979+
980+
LOCK(pwallet->cs_wallet);
981+
EnsureWalletIsUnlocked(*pwallet);
982+
983+
CExtPubKey xpub;
984+
if (hdkey.isNull()) {
985+
std::set<CExtPubKey> active_xpubs = pwallet->GetActiveHDPubKeys();
986+
if (active_xpubs.size() != 1) {
987+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to determine which HD key to use from active descriptors. Please specify with 'hdkey'");
988+
}
989+
xpub = *active_xpubs.begin();
990+
} else {
991+
xpub = DecodeExtPubKey(hdkey.get_str());
992+
if (!xpub.pubkey.IsValid()) {
993+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to parse HD key. Please provide a valid xpub");
994+
}
995+
}
996+
997+
std::optional<CKey> key = pwallet->GetKey(xpub.pubkey.GetID());
998+
if (!key) {
999+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Private key for %s is not known", EncodeExtPubKey(xpub)));
1000+
}
1001+
CExtKey active_hdkey(xpub, *key);
1002+
1003+
std::vector<std::reference_wrapper<DescriptorScriptPubKeyMan>> spkms;
1004+
WalletBatch batch{pwallet->GetDatabase()};
1005+
for (bool internal : internals) {
1006+
WalletDescriptor w_desc = GenerateWalletDescriptor(xpub, *output_type, internal);
1007+
uint256 w_id = DescriptorID(*w_desc.descriptor);
1008+
if (!pwallet->GetScriptPubKeyMan(w_id)) {
1009+
spkms.emplace_back(pwallet->SetupDescriptorScriptPubKeyMan(batch, active_hdkey, *output_type, internal));
1010+
}
1011+
}
1012+
if (spkms.empty()) {
1013+
throw JSONRPCError(RPC_WALLET_ERROR, "Descriptor already exists");
1014+
}
1015+
1016+
// Fetch each descspkm from the wallet in order to get the descriptor strings
1017+
UniValue descs{UniValue::VARR};
1018+
for (const auto& spkm : spkms) {
1019+
std::string desc_str;
1020+
bool ok = spkm.get().GetDescriptorString(desc_str, false);
1021+
CHECK_NONFATAL(ok);
1022+
descs.push_back(desc_str);
1023+
}
1024+
UniValue out{UniValue::VOBJ};
1025+
out.pushKV("descs", std::move(descs));
1026+
return out;
1027+
}
1028+
};
1029+
}
1030+
8201031
// addresses
8211032
RPCHelpMan getaddressinfo();
8221033
RPCHelpMan getnewaddress();
@@ -900,13 +1111,15 @@ Span<const CRPCCommand> GetWalletRPCCommands()
9001111
{"wallet", &bumpfee},
9011112
{"wallet", &psbtbumpfee},
9021113
{"wallet", &createwallet},
1114+
{"wallet", &createwalletdescriptor},
9031115
{"wallet", &restorewallet},
9041116
{"wallet", &dumpprivkey},
9051117
{"wallet", &dumpwallet},
9061118
{"wallet", &encryptwallet},
9071119
{"wallet", &getaddressesbylabel},
9081120
{"wallet", &getaddressinfo},
9091121
{"wallet", &getbalance},
1122+
{"wallet", &gethdkeys},
9101123
{"wallet", &getnewaddress},
9111124
{"wallet", &getrawchangeaddress},
9121125
{"wallet", &getreceivedbyaddress},

0 commit comments

Comments
 (0)