Coverage Report

Created: 2026-09-14 20:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/rpc/output_script.cpp
Line
Count
Source
1
// Copyright (c) 2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present 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
6
#include <rpc/register.h> // IWYU pragma: associated
7
8
#include <addresstype.h>
9
#include <crypto/hex_base.h>
10
#include <key.h>
11
#include <key_io.h>
12
#include <outputtype.h>
13
#include <pubkey.h>
14
#include <rpc/protocol.h>
15
#include <rpc/request.h>
16
#include <rpc/server.h>
17
#include <rpc/util.h>
18
#include <script/descriptor.h>
19
#include <script/script.h>
20
#include <script/signingprovider.h>
21
#include <tinyformat.h>
22
#include <univalue.h>
23
#include <util/check.h>
24
25
#include <cstddef>
26
#include <cstdint>
27
#include <map>
28
#include <memory>
29
#include <optional>
30
#include <span>
31
#include <string>
32
#include <string_view>
33
#include <tuple>
34
#include <utility>
35
#include <variant>
36
#include <vector>
37
38
static RPCMethod validateaddress()
39
2.61k
{
40
2.61k
    return RPCMethod{
41
2.61k
        "validateaddress",
42
2.61k
        "Return information about the given bitcoin address.\n",
43
2.61k
        {
44
2.61k
            {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"},
45
2.61k
        },
46
2.61k
        RPCResult{
47
2.61k
            RPCResult::Type::OBJ, "", "",
48
2.61k
            {
49
2.61k
                {RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
50
2.61k
                {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address validated"},
51
2.61k
                {RPCResult::Type::STR_HEX, "scriptPubKey", /*optional=*/true, "The hex-encoded output script generated by the address"},
52
2.61k
                {RPCResult::Type::BOOL, "isscript", /*optional=*/true, "If the key is a script"},
53
2.61k
                {RPCResult::Type::BOOL, "iswitness", /*optional=*/true, "If the address is a witness address"},
54
2.61k
                {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program"},
55
2.61k
                {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program"},
56
2.61k
                {RPCResult::Type::STR, "error", /*optional=*/true, "Error message, if any"},
57
2.61k
                {RPCResult::Type::ARR, "error_locations", /*optional=*/true, "Indices of likely error locations in address, if known (e.g. Bech32 errors)",
58
2.61k
                    {
59
2.61k
                        {RPCResult::Type::NUM, "index", "index of a potential error"},
60
2.61k
                    }},
61
2.61k
            }
62
2.61k
        },
63
2.61k
        RPCExamples{
64
2.61k
            HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
65
2.61k
            HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
66
2.61k
        },
67
2.61k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
68
2.61k
        {
69
148
            std::string error_msg;
70
148
            std::vector<int> error_locations;
71
148
            CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
72
148
            const bool isValid = IsValidDestination(dest);
73
148
            CHECK_NONFATAL(isValid == error_msg.empty());
74
75
148
            UniValue ret(UniValue::VOBJ);
76
148
            ret.pushKV("isvalid", isValid);
77
148
            if (isValid) {
78
102
                std::string currentAddress = EncodeDestination(dest);
79
102
                ret.pushKV("address", currentAddress);
80
81
102
                CScript scriptPubKey = GetScriptForDestination(dest);
82
102
                ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
83
84
102
                UniValue detail = DescribeAddress(dest);
85
102
                ret.pushKVs(std::move(detail));
86
102
            } else {
87
46
                UniValue error_indices(UniValue::VARR);
88
46
                for (int i : error_locations) error_indices.push_back(i);
89
46
                ret.pushKV("error_locations", std::move(error_indices));
90
46
                ret.pushKV("error", error_msg);
91
46
            }
92
93
148
            return ret;
94
148
        },
95
2.61k
    };
96
2.61k
}
97
98
static RPCMethod createmultisig()
99
2.55k
{
100
2.55k
    return RPCMethod{
101
2.55k
        "createmultisig",
102
2.55k
        "Creates a multi-signature address with n signatures of m keys required.\n"
103
2.55k
        "It returns a json object with the address and redeemScript.\n",
104
2.55k
        {
105
2.55k
            {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the m keys."},
106
2.55k
            {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
107
2.55k
                {
108
2.55k
                    {"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
109
2.55k
                }},
110
2.55k
            {"address_type", RPCArg::Type::STR, RPCArg::Default{"legacy"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
111
2.55k
        },
112
2.55k
        RPCResult{
113
2.55k
            RPCResult::Type::OBJ, "", "",
114
2.55k
            {
115
2.55k
                {RPCResult::Type::STR, "address", "The value of the new multisig address."},
116
2.55k
                {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."},
117
2.55k
                {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"},
118
2.55k
                {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Any warnings resulting from the creation of this multisig",
119
2.55k
                {
120
2.55k
                    {RPCResult::Type::STR, "", ""},
121
2.55k
                }},
122
2.55k
            }
123
2.55k
        },
124
2.55k
        RPCExamples{
125
2.55k
            "\nCreate a multisig address from 2 public keys\n"
126
2.55k
            + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
127
2.55k
            "\nAs a JSON-RPC call\n"
128
2.55k
            + HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
129
2.55k
                },
130
2.55k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
131
2.55k
        {
132
85
            int required = request.params[0].getInt<int>();
133
134
            // Get the public keys
135
85
            const UniValue& keys = request.params[1].get_array();
136
85
            std::vector<CPubKey> pubkeys;
137
85
            pubkeys.reserve(keys.size());
138
648
            for (unsigned int i = 0; i < keys.size(); ++i) {
139
563
                pubkeys.push_back(HexToPubKey(keys[i].get_str()));
140
563
            }
141
142
            // Get the output type
143
85
            auto address_type{self.Arg<std::string_view>("address_type")};
144
85
            auto output_type{ParseOutputType(address_type)};
145
85
            if (!output_type) {
146
1
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, tfm::format("Unknown address type '%s'", address_type));
147
84
            } else if (output_type.value() == OutputType::BECH32M) {
148
1
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
149
1
            }
150
151
83
            FlatSigningProvider keystore;
152
83
            CScript inner;
153
83
            const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type.value(), keystore, inner);
154
155
            // Make the descriptor
156
83
            std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
157
158
83
            UniValue result(UniValue::VOBJ);
159
83
            result.pushKV("address", EncodeDestination(dest));
160
83
            result.pushKV("redeemScript", HexStr(inner));
161
83
            result.pushKV("descriptor", descriptor->ToString());
162
163
83
            UniValue warnings(UniValue::VARR);
164
83
            if (descriptor->GetOutputType() != output_type.value()) {
165
                // Only warns if the user has explicitly chosen an address type we cannot generate
166
12
                warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
167
12
            }
168
83
            PushWarnings(warnings, result);
169
170
83
            return result;
171
85
        },
172
2.55k
    };
173
2.55k
}
174
175
static RPCMethod getdescriptorinfo()
176
2.72k
{
177
2.72k
    const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
178
179
2.72k
    return RPCMethod{
180
2.72k
        "getdescriptorinfo",
181
2.72k
        "Analyses a descriptor.\n",
182
2.72k
        {
183
2.72k
            {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
184
2.72k
        },
185
2.72k
        RPCResult{
186
2.72k
            RPCResult::Type::OBJ, "", "",
187
2.72k
            {
188
2.72k
                {RPCResult::Type::STR, "descriptor", "The descriptor, without private keys. For a multipath descriptor, only the first will be returned."},
189
2.72k
                {RPCResult::Type::ARR, "multipath_expansion", /*optional=*/true, "All descriptors produced by expanding multipath derivation elements. Only if the provided descriptor specifies multipath derivation elements.",
190
2.72k
                {
191
2.72k
                    {RPCResult::Type::STR, "", ""},
192
2.72k
                }},
193
2.72k
                {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
194
2.72k
                {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
195
2.72k
                {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
196
2.72k
                {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
197
2.72k
            }
198
2.72k
        },
199
2.72k
        RPCExamples{
200
2.72k
            "Analyse a descriptor\n" +
201
2.72k
            HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
202
2.72k
            HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
203
2.72k
        },
204
2.72k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
205
2.72k
        {
206
254
            FlatSigningProvider provider;
207
254
            std::string error;
208
254
            auto descs = Parse(self.Arg<std::string_view>("descriptor"), provider, error);
209
254
            if (descs.empty()) {
210
6
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
211
6
            }
212
213
248
            UniValue result(UniValue::VOBJ);
214
248
            result.pushKV("descriptor", descs.at(0)->ToString());
215
216
248
            if (descs.size() > 1) {
217
5
                UniValue multipath_descs(UniValue::VARR);
218
10
                for (const auto& d : descs) {
219
10
                    multipath_descs.push_back(d->ToString());
220
10
                }
221
5
                result.pushKV("multipath_expansion", multipath_descs);
222
5
            }
223
224
248
            result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
225
248
            result.pushKV("isrange", descs.at(0)->IsRange());
226
248
            result.pushKV("issolvable", descs.at(0)->IsSolvable());
227
248
            result.pushKV("hasprivatekeys", provider.keys.size() > 0);
228
248
            return result;
229
254
        },
230
2.72k
    };
231
2.72k
}
232
233
static UniValue DeriveAddresses(const Descriptor* desc, int64_t range_begin, int64_t range_end, FlatSigningProvider& key_provider)
234
197
{
235
197
    UniValue addresses(UniValue::VARR);
236
237
406
    for (int64_t i = range_begin; i <= range_end; ++i) {
238
215
        FlatSigningProvider provider;
239
215
        std::vector<CScript> scripts;
240
215
        if (!desc->Expand(i, key_provider, scripts, provider)) {
241
2
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
242
2
        }
243
244
219
        for (const CScript& script : scripts) {
245
219
            CTxDestination dest;
246
219
            if (!ExtractDestination(script, dest)) {
247
                // ExtractDestination no longer returns true for P2PK since it doesn't have a corresponding address
248
                // However combo will output P2PK and should just ignore that script
249
6
                if (scripts.size() > 1 && std::get_if<PubKeyDestination>(&dest)) {
250
2
                    continue;
251
2
                }
252
4
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
253
6
            }
254
255
213
            addresses.push_back(EncodeDestination(dest));
256
213
        }
257
213
    }
258
259
    // This should not be possible, but an assert seems overkill:
260
191
    if (addresses.empty()) {
261
0
        throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
262
0
    }
263
264
191
    return addresses;
265
191
}
266
267
static RPCMethod deriveaddresses()
268
2.67k
{
269
2.67k
    const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
270
271
2.67k
    return RPCMethod{
272
2.67k
        "deriveaddresses",
273
2.67k
        "Derives one or more addresses corresponding to an output descriptor.\n"
274
2.67k
         "Examples of output descriptors are:\n"
275
2.67k
         "    pkh(<pubkey>)                                     P2PKH outputs for the given pubkey\n"
276
2.67k
         "    wpkh(<pubkey>)                                    Native segwit P2PKH outputs for the given pubkey\n"
277
2.67k
         "    sh(multi(<n>,<pubkey>,<pubkey>,...))              P2SH-multisig outputs for the given threshold and pubkeys\n"
278
2.67k
         "    raw(<hex script>)                                 Outputs whose output script equals the specified hex-encoded bytes\n"
279
2.67k
         "    tr(<pubkey>,multi_a(<n>,<pubkey>,<pubkey>,...))   P2TR-multisig outputs for the given threshold and pubkeys\n"
280
2.67k
         "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
281
2.67k
         "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
282
2.67k
        "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
283
2.67k
        {
284
2.67k
            {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
285
2.67k
            {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."},
286
2.67k
        },
287
2.67k
        {
288
2.67k
            RPCResult{"for single derivation descriptors",
289
2.67k
                RPCResult::Type::ARR, "", "",
290
2.67k
                {
291
2.67k
                    {RPCResult::Type::STR, "address", "the derived addresses"},
292
2.67k
                }
293
2.67k
            },
294
2.67k
            RPCResult{"for multipath descriptors",
295
2.67k
                RPCResult::Type::ARR, "", "The derived addresses for each of the multipath expansions of the descriptor, in multipath specifier order",
296
2.67k
                {
297
2.67k
                    {
298
2.67k
                        RPCResult::Type::ARR, "", "The derived addresses for a multipath descriptor expansion",
299
2.67k
                        {
300
2.67k
                            {RPCResult::Type::STR, "address", "the derived address"},
301
2.67k
                        },
302
2.67k
                    },
303
2.67k
                },
304
2.67k
            },
305
2.67k
        },
306
2.67k
        RPCExamples{
307
2.67k
            "First three native segwit receive addresses\n" +
308
2.67k
            HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
309
2.67k
            HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
310
2.67k
        },
311
2.67k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
312
2.67k
        {
313
213
            auto desc_str{self.Arg<std::string_view>("descriptor")};
314
315
213
            int64_t range_begin = 0;
316
213
            int64_t range_end = 0;
317
318
213
            const UniValue* range = self.MaybeArg<UniValue>("range");
319
213
            if (range) {
320
80
                std::tie(range_begin, range_end) = ParseDescriptorRange(*range);
321
80
            }
322
323
213
            FlatSigningProvider key_provider;
324
213
            std::string error;
325
213
            auto descs = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
326
213
            if (descs.empty()) {
327
4
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
328
4
            }
329
209
            auto& desc = descs.at(0);
330
209
            if (!desc->IsRange() && range) {
331
2
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
332
2
            }
333
334
207
            if (desc->IsRange() && !range) {
335
4
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
336
4
            }
337
338
203
            UniValue addresses = DeriveAddresses(desc.get(), range_begin, range_end, key_provider);
339
340
203
            if (descs.size() == 1) {
341
187
                return addresses;
342
187
            }
343
344
16
            UniValue ret(UniValue::VARR);
345
16
            ret.push_back(addresses);
346
18
            for (size_t i = 1; i < descs.size(); ++i) {
347
2
                ret.push_back(DeriveAddresses(descs.at(i).get(), range_begin, range_end, key_provider));
348
2
            }
349
16
            return ret;
350
203
        },
351
2.67k
    };
352
2.67k
}
353
354
void RegisterOutputScriptRPCCommands(CRPCTable& t)
355
1.36k
{
356
1.36k
    static const CRPCCommand commands[]{
357
1.36k
        {"util", &validateaddress},
358
1.36k
        {"util", &createmultisig},
359
1.36k
        {"util", &deriveaddresses},
360
1.36k
        {"util", &getdescriptorinfo},
361
1.36k
    };
362
5.44k
    for (const auto& c : commands) {
363
5.44k
        t.appendCommand(c.name, &c);
364
5.44k
    }
365
1.36k
}