Skip to content

Commit 5952838

Browse files
committed
[rpc] util: add deriveaddresses method
1 parent 7275365 commit 5952838

File tree

5 files changed

+149
-0
lines changed

5 files changed

+149
-0
lines changed

doc/release-notes-14667.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
New RPC methods
2+
------------
3+
4+
- `deriveaddresses` returns one or more addresses corresponding to an [output descriptor](/doc/descriptors.md).

src/rpc/client.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ static const CRPCConvertParam vRPCConvertParams[] =
6868
{ "sendmany", 4, "subtractfeefrom" },
6969
{ "sendmany", 5 , "replaceable" },
7070
{ "sendmany", 6 , "conf_target" },
71+
{ "deriveaddresses", 1, "begin" },
72+
{ "deriveaddresses", 2, "end" },
7173
{ "scantxoutset", 1, "scanobjects" },
7274
{ "addmultisigaddress", 0, "nrequired" },
7375
{ "addmultisigaddress", 1, "keys" },

src/rpc/misc.cpp

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#include <rpc/blockchain.h>
1717
#include <rpc/server.h>
1818
#include <rpc/util.h>
19+
#include <script/descriptor.h>
1920
#include <timedata.h>
2021
#include <util/system.h>
2122
#include <util/strencodings.h>
@@ -142,6 +143,95 @@ static UniValue createmultisig(const JSONRPCRequest& request)
142143
return result;
143144
}
144145

146+
UniValue deriveaddresses(const JSONRPCRequest& request)
147+
{
148+
if (request.fHelp || request.params.empty() || request.params.size() > 3) {
149+
throw std::runtime_error(
150+
RPCHelpMan{"deriveaddresses",
151+
{"\nDerives one or more addresses corresponding to an output descriptor.\n"
152+
"Examples of output descriptors are:\n"
153+
" pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
154+
" wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
155+
" sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
156+
" raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
157+
"\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
158+
"or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
159+
"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
160+
{
161+
{"descriptor", RPCArg::Type::STR, /* opt */ false, /* default_val */ "", "The descriptor."},
162+
{"begin", RPCArg::Type::NUM, /* opt */ true, /* default_val */ "", "If a ranged descriptor is used, this specifies the beginning of the range to import."},
163+
{"end", RPCArg::Type::NUM, /* opt */ true, /* default_val */ "", "If a ranged descriptor is used, this specifies the end of the range to import."}
164+
},
165+
RPCResult{
166+
"[ address ] (array) the derived addresses\n"
167+
},
168+
RPCExamples{
169+
"First three native segwit receive addresses\n" +
170+
HelpExampleCli("deriveaddresses", "\"wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)\" 0 2")
171+
}}.ToString()
172+
);
173+
}
174+
175+
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VNUM, UniValue::VNUM});
176+
const std::string desc_str = request.params[0].get_str();
177+
178+
int range_begin = 0;
179+
int range_end = 0;
180+
181+
if (request.params.size() >= 2) {
182+
if (request.params.size() == 2) {
183+
throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing range end parameter");
184+
}
185+
range_begin = request.params[1].get_int();
186+
range_end = request.params[2].get_int();
187+
if (range_begin < 0) {
188+
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
189+
}
190+
if (range_begin > range_end) {
191+
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range end should be equal to or greater than begin");
192+
}
193+
}
194+
195+
FlatSigningProvider provider;
196+
auto desc = Parse(desc_str, provider);
197+
if (!desc) {
198+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid descriptor"));
199+
}
200+
201+
if (!desc->IsRange() && request.params.size() > 1) {
202+
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
203+
}
204+
205+
if (desc->IsRange() && request.params.size() == 1) {
206+
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
207+
}
208+
209+
UniValue addresses(UniValue::VARR);
210+
211+
for (int i = range_begin; i <= range_end; ++i) {
212+
std::vector<CScript> scripts;
213+
if (!desc->Expand(i, provider, scripts, provider)) {
214+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys"));
215+
}
216+
217+
for (const CScript &script : scripts) {
218+
CTxDestination dest;
219+
if (!ExtractDestination(script, dest)) {
220+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Descriptor does not have a corresponding address"));
221+
}
222+
223+
addresses.push_back(EncodeDestination(dest));
224+
}
225+
}
226+
227+
// This should not be possible, but an assert seems overkill:
228+
if (addresses.empty()) {
229+
throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
230+
}
231+
232+
return addresses;
233+
}
234+
145235
static UniValue verifymessage(const JSONRPCRequest& request)
146236
{
147237
if (request.fHelp || request.params.size() != 3)
@@ -473,6 +563,7 @@ static const CRPCCommand commands[] =
473563
{ "control", "logging", &logging, {"include", "exclude"}},
474564
{ "util", "validateaddress", &validateaddress, {"address"} },
475565
{ "util", "createmultisig", &createmultisig, {"nrequired","keys","address_type"} },
566+
{ "util", "deriveaddresses", &deriveaddresses, {"descriptor", "begin", "end"} },
476567
{ "util", "verifymessage", &verifymessage, {"address","signature","message"} },
477568
{ "util", "signmessagewithprivkey", &signmessagewithprivkey, {"privkey","message"} },
478569

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2018 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
"""Test the deriveaddresses rpc call."""
6+
from test_framework.test_framework import BitcoinTestFramework
7+
from test_framework.util import assert_equal, assert_raises_rpc_error
8+
9+
class DeriveaddressesTest(BitcoinTestFramework):
10+
def set_test_params(self):
11+
self.num_nodes = 1
12+
self.supports_cli = 1
13+
14+
def run_test(self):
15+
assert_raises_rpc_error(-5, "Invalid descriptor", self.nodes[0].deriveaddresses, "a")
16+
17+
descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
18+
address = "bcrt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferr34acd5"
19+
20+
assert_equal(self.nodes[0].deriveaddresses(descriptor), [address])
21+
22+
descriptor_pubkey = "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0)"
23+
address = "bcrt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferr34acd5"
24+
25+
assert_equal(self.nodes[0].deriveaddresses(descriptor_pubkey), [address])
26+
27+
ranged_descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
28+
assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, 0, 2), [address, "bcrt1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rq4442dy", "bcrt1qpgptk2gvshyl0s9lqshsmx932l9ccsv265tvaq"])
29+
30+
assert_raises_rpc_error(-8, "Range should not be specified for an un-ranged descriptor", self.nodes[0].deriveaddresses, "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)", 0, 2)
31+
32+
assert_raises_rpc_error(-8, "Range must be specified for a ranged descriptor", self.nodes[0].deriveaddresses, "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)")
33+
34+
assert_raises_rpc_error(-8, "Missing range end parameter", self.nodes[0].deriveaddresses, "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)", 0)
35+
36+
assert_raises_rpc_error(-8, "Range end should be equal to or greater than begin", self.nodes[0].deriveaddresses, "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)", 2, 0)
37+
38+
assert_raises_rpc_error(-8, "Range should be greater or equal than 0", self.nodes[0].deriveaddresses, "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)", -1, 0)
39+
40+
combo_descriptor = "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
41+
assert_equal(self.nodes[0].deriveaddresses(combo_descriptor), ["mtfUoUax9L4tzXARpw1oTGxWyoogp52KhJ", "mtfUoUax9L4tzXARpw1oTGxWyoogp52KhJ", address, "2NDvEwGfpEqJWfybzpKPHF2XH3jwoQV3D7x"])
42+
43+
hardened_without_privkey_descriptor = "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1'/1/0)"
44+
assert_raises_rpc_error(-5, "Cannot derive script without private keys", self.nodes[0].deriveaddresses, hardened_without_privkey_descriptor)
45+
46+
bare_multisig_descriptor = "multi(1, tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0, tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/1)"
47+
assert_raises_rpc_error(-5, "Descriptor does not have a corresponding address", self.nodes[0].deriveaddresses, bare_multisig_descriptor)
48+
49+
if __name__ == '__main__':
50+
DeriveaddressesTest().main()

test/functional/test_runner.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,8 @@
181181
'feature_filelock.py',
182182
'p2p_unrequested_blocks.py',
183183
'feature_includeconf.py',
184+
'rpc_deriveaddresses.py',
185+
'rpc_deriveaddresses.py --usecli',
184186
'rpc_scantxoutset.py',
185187
'feature_logging.py',
186188
'p2p_node_network_limited.py',

0 commit comments

Comments
 (0)