Coverage Report

Created: 2026-08-25 19:02

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