Coverage Report

Created: 2025-06-10 13:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/pubkey.cpp
Line
Count
Source
1
// Copyright (c) 2009-present The Bitcoin Core developers
2
// Copyright (c) 2017 The Zcash 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 <pubkey.h>
7
8
#include <hash.h>
9
#include <secp256k1.h>
10
#include <secp256k1_ellswift.h>
11
#include <secp256k1_extrakeys.h>
12
#include <secp256k1_recovery.h>
13
#include <secp256k1_schnorrsig.h>
14
#include <span.h>
15
#include <uint256.h>
16
#include <util/strencodings.h>
17
18
#include <algorithm>
19
#include <cassert>
20
21
using namespace util::hex_literals;
22
23
namespace {
24
25
struct Secp256k1SelfTester
26
{
27
11.0k
    Secp256k1SelfTester() {
28
        /* Run libsecp256k1 self-test before using the secp256k1_context_static. */
29
11.0k
        secp256k1_selftest();
30
11.0k
    }
31
} SECP256K1_SELFTESTER;
32
33
} // namespace
34
35
/** This function is taken from the libsecp256k1 distribution and implements
36
 *  DER parsing for ECDSA signatures, while supporting an arbitrary subset of
37
 *  format violations.
38
 *
39
 *  Supported violations include negative integers, excessive padding, garbage
40
 *  at the end, and overly long length descriptors. This is safe to use in
41
 *  Bitcoin because since the activation of BIP66, signatures are verified to be
42
 *  strict DER before being passed to this module, and we know it supports all
43
 *  violations present in the blockchain before that point.
44
 */
45
22.1k
int ecdsa_signature_parse_der_lax(secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) {
46
22.1k
    size_t rpos, rlen, spos, slen;
47
22.1k
    size_t pos = 0;
48
22.1k
    size_t lenbyte;
49
22.1k
    unsigned char tmpsig[64] = {0};
50
22.1k
    int overflow = 0;
51
52
    /* Hack to initialize sig with a correctly-parsed but invalid signature. */
53
22.1k
    secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
54
55
    /* Sequence tag byte */
56
22.1k
    if (pos == inputlen || input[pos] != 0x30) {
  Branch (56:9): [True: 0, False: 22.1k]
  Branch (56:28): [True: 0, False: 22.1k]
57
0
        return 0;
58
0
    }
59
22.1k
    pos++;
60
61
    /* Sequence length bytes */
62
22.1k
    if (pos == inputlen) {
  Branch (62:9): [True: 0, False: 22.1k]
63
0
        return 0;
64
0
    }
65
22.1k
    lenbyte = input[pos++];
66
22.1k
    if (lenbyte & 0x80) {
  Branch (66:9): [True: 0, False: 22.1k]
67
0
        lenbyte -= 0x80;
68
0
        if (lenbyte > inputlen - pos) {
  Branch (68:13): [True: 0, False: 0]
69
0
            return 0;
70
0
        }
71
0
        pos += lenbyte;
72
0
    }
73
74
    /* Integer tag byte for R */
75
22.1k
    if (pos == inputlen || input[pos] != 0x02) {
  Branch (75:9): [True: 0, False: 22.1k]
  Branch (75:28): [True: 0, False: 22.1k]
76
0
        return 0;
77
0
    }
78
22.1k
    pos++;
79
80
    /* Integer length for R */
81
22.1k
    if (pos == inputlen) {
  Branch (81:9): [True: 0, False: 22.1k]
82
0
        return 0;
83
0
    }
84
22.1k
    lenbyte = input[pos++];
85
22.1k
    if (lenbyte & 0x80) {
  Branch (85:9): [True: 0, False: 22.1k]
86
0
        lenbyte -= 0x80;
87
0
        if (lenbyte > inputlen - pos) {
  Branch (87:13): [True: 0, False: 0]
88
0
            return 0;
89
0
        }
90
0
        while (lenbyte > 0 && input[pos] == 0) {
  Branch (90:16): [True: 0, False: 0]
  Branch (90:31): [True: 0, False: 0]
91
0
            pos++;
92
0
            lenbyte--;
93
0
        }
94
0
        static_assert(sizeof(size_t) >= 4, "size_t too small");
95
0
        if (lenbyte >= 4) {
  Branch (95:13): [True: 0, False: 0]
96
0
            return 0;
97
0
        }
98
0
        rlen = 0;
99
0
        while (lenbyte > 0) {
  Branch (99:16): [True: 0, False: 0]
100
0
            rlen = (rlen << 8) + input[pos];
101
0
            pos++;
102
0
            lenbyte--;
103
0
        }
104
22.1k
    } else {
105
22.1k
        rlen = lenbyte;
106
22.1k
    }
107
22.1k
    if (rlen > inputlen - pos) {
  Branch (107:9): [True: 0, False: 22.1k]
108
0
        return 0;
109
0
    }
110
22.1k
    rpos = pos;
111
22.1k
    pos += rlen;
112
113
    /* Integer tag byte for S */
114
22.1k
    if (pos == inputlen || input[pos] != 0x02) {
  Branch (114:9): [True: 0, False: 22.1k]
  Branch (114:28): [True: 0, False: 22.1k]
115
0
        return 0;
116
0
    }
117
22.1k
    pos++;
118
119
    /* Integer length for S */
120
22.1k
    if (pos == inputlen) {
  Branch (120:9): [True: 0, False: 22.1k]
121
0
        return 0;
122
0
    }
123
22.1k
    lenbyte = input[pos++];
124
22.1k
    if (lenbyte & 0x80) {
  Branch (124:9): [True: 0, False: 22.1k]
125
0
        lenbyte -= 0x80;
126
0
        if (lenbyte > inputlen - pos) {
  Branch (126:13): [True: 0, False: 0]
127
0
            return 0;
128
0
        }
129
0
        while (lenbyte > 0 && input[pos] == 0) {
  Branch (129:16): [True: 0, False: 0]
  Branch (129:31): [True: 0, False: 0]
130
0
            pos++;
131
0
            lenbyte--;
132
0
        }
133
0
        static_assert(sizeof(size_t) >= 4, "size_t too small");
134
0
        if (lenbyte >= 4) {
  Branch (134:13): [True: 0, False: 0]
135
0
            return 0;
136
0
        }
137
0
        slen = 0;
138
0
        while (lenbyte > 0) {
  Branch (138:16): [True: 0, False: 0]
139
0
            slen = (slen << 8) + input[pos];
140
0
            pos++;
141
0
            lenbyte--;
142
0
        }
143
22.1k
    } else {
144
22.1k
        slen = lenbyte;
145
22.1k
    }
146
22.1k
    if (slen > inputlen - pos) {
  Branch (146:9): [True: 0, False: 22.1k]
147
0
        return 0;
148
0
    }
149
22.1k
    spos = pos;
150
151
    /* Ignore leading zeroes in R */
152
22.2k
    while (rlen > 0 && input[rpos] == 0) {
  Branch (152:12): [True: 22.2k, False: 0]
  Branch (152:24): [True: 74, False: 22.1k]
153
74
        rlen--;
154
74
        rpos++;
155
74
    }
156
    /* Copy R value */
157
22.1k
    if (rlen > 32) {
  Branch (157:9): [True: 0, False: 22.1k]
158
0
        overflow = 1;
159
22.1k
    } else {
160
22.1k
        memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
161
22.1k
    }
162
163
    /* Ignore leading zeroes in S */
164
22.2k
    while (slen > 0 && input[spos] == 0) {
  Branch (164:12): [True: 22.2k, False: 0]
  Branch (164:24): [True: 90, False: 22.1k]
165
90
        slen--;
166
90
        spos++;
167
90
    }
168
    /* Copy S value */
169
22.1k
    if (slen > 32) {
  Branch (169:9): [True: 0, False: 22.1k]
170
0
        overflow = 1;
171
22.1k
    } else {
172
22.1k
        memcpy(tmpsig + 64 - slen, input + spos, slen);
173
22.1k
    }
174
175
22.1k
    if (!overflow) {
  Branch (175:9): [True: 22.1k, False: 0]
176
22.1k
        overflow = !secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
177
22.1k
    }
178
22.1k
    if (overflow) {
  Branch (178:9): [True: 0, False: 22.1k]
179
        /* Overwrite the result again with a correctly-parsed but invalid
180
           signature if parsing failed. */
181
0
        memset(tmpsig, 0, 64);
182
0
        secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
183
0
    }
184
22.1k
    return 1;
185
22.1k
}
186
187
/** Nothing Up My Sleeve (NUMS) point
188
 *
189
 *  NUMS_H is a point with an unknown discrete logarithm, constructed by taking the sha256 of 'g'
190
 *  (uncompressed encoding), which happens to be a point on the curve.
191
 *
192
 *  For an example script for calculating H, refer to the unit tests in
193
 *  ./test/functional/test_framework/crypto/secp256k1.py
194
 */
195
constexpr XOnlyPubKey XOnlyPubKey::NUMS_H{
196
    // Use immediate lambda to work around GCC-14 bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117966
197
    []() consteval { return XOnlyPubKey{"50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"_hex_u8}; }(),
198
};
199
200
std::vector<CKeyID> XOnlyPubKey::GetKeyIDs() const
201
0
{
202
0
    std::vector<CKeyID> out;
203
    // For now, use the old full pubkey-based key derivation logic. As it is indexed by
204
    // Hash160(full pubkey), we need to return both a version prefixed with 0x02, and one
205
    // with 0x03.
206
0
    unsigned char b[33] = {0x02};
207
0
    std::copy(m_keydata.begin(), m_keydata.end(), b + 1);
208
0
    CPubKey fullpubkey;
209
0
    fullpubkey.Set(b, b + 33);
210
0
    out.push_back(fullpubkey.GetID());
211
0
    b[0] = 0x03;
212
0
    fullpubkey.Set(b, b + 33);
213
0
    out.push_back(fullpubkey.GetID());
214
0
    return out;
215
0
}
216
217
CPubKey XOnlyPubKey::GetEvenCorrespondingCPubKey() const
218
0
{
219
0
    unsigned char full_key[CPubKey::COMPRESSED_SIZE] = {0x02};
220
0
    std::copy(begin(), end(), full_key + 1);
221
0
    return CPubKey{full_key};
222
0
}
223
224
bool XOnlyPubKey::IsFullyValid() const
225
221k
{
226
221k
    secp256k1_xonly_pubkey pubkey;
227
221k
    return secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data());
228
221k
}
229
230
bool XOnlyPubKey::VerifySchnorr(const uint256& msg, std::span<const unsigned char> sigbytes) const
231
0
{
232
0
    assert(sigbytes.size() == 64);
  Branch (232:5): [True: 0, False: 0]
233
0
    secp256k1_xonly_pubkey pubkey;
234
0
    if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data())) return false;
  Branch (234:9): [True: 0, False: 0]
235
0
    return secp256k1_schnorrsig_verify(secp256k1_context_static, sigbytes.data(), msg.begin(), 32, &pubkey);
236
0
}
237
238
static const HashWriter HASHER_TAPTWEAK{TaggedHash("TapTweak")};
239
240
uint256 XOnlyPubKey::ComputeTapTweakHash(const uint256* merkle_root) const
241
221k
{
242
221k
    if (merkle_root == nullptr) {
  Branch (242:9): [True: 221k, False: 0]
243
        // We have no scripts. The actual tweak does not matter, but follow BIP341 here to
244
        // allow for reproducible tweaking.
245
221k
        return (HashWriter{HASHER_TAPTWEAK} << m_keydata).GetSHA256();
246
221k
    } else {
247
0
        return (HashWriter{HASHER_TAPTWEAK} << m_keydata << *merkle_root).GetSHA256();
248
0
    }
249
221k
}
250
251
bool XOnlyPubKey::CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const
252
0
{
253
0
    secp256k1_xonly_pubkey internal_key;
254
0
    if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &internal_key, internal.data())) return false;
  Branch (254:9): [True: 0, False: 0]
255
0
    uint256 tweak = internal.ComputeTapTweakHash(&merkle_root);
256
0
    return secp256k1_xonly_pubkey_tweak_add_check(secp256k1_context_static, m_keydata.begin(), parity, &internal_key, tweak.begin());
257
0
}
258
259
std::optional<std::pair<XOnlyPubKey, bool>> XOnlyPubKey::CreateTapTweak(const uint256* merkle_root) const
260
221k
{
261
221k
    secp256k1_xonly_pubkey base_point;
262
221k
    if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &base_point, data())) return std::nullopt;
  Branch (262:9): [True: 0, False: 221k]
263
221k
    secp256k1_pubkey out;
264
221k
    uint256 tweak = ComputeTapTweakHash(merkle_root);
265
221k
    if (!secp256k1_xonly_pubkey_tweak_add(secp256k1_context_static, &out, &base_point, tweak.data())) return std::nullopt;
  Branch (265:9): [True: 0, False: 221k]
266
221k
    int parity = -1;
267
221k
    std::pair<XOnlyPubKey, bool> ret;
268
221k
    secp256k1_xonly_pubkey out_xonly;
269
221k
    if (!secp256k1_xonly_pubkey_from_pubkey(secp256k1_context_static, &out_xonly, &parity, &out)) return std::nullopt;
  Branch (269:9): [True: 0, False: 221k]
270
221k
    secp256k1_xonly_pubkey_serialize(secp256k1_context_static, ret.first.begin(), &out_xonly);
271
221k
    assert(parity == 0 || parity == 1);
  Branch (271:5): [True: 111k, False: 110k]
  Branch (271:5): [True: 110k, False: 0]
  Branch (271:5): [True: 221k, False: 0]
272
221k
    ret.second = parity;
273
221k
    return ret;
274
221k
}
275
276
277
22.1k
bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
278
22.1k
    if (!IsValid())
  Branch (278:9): [True: 0, False: 22.1k]
279
0
        return false;
280
22.1k
    secp256k1_pubkey pubkey;
281
22.1k
    secp256k1_ecdsa_signature sig;
282
22.1k
    if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
  Branch (282:9): [True: 0, False: 22.1k]
283
0
        return false;
284
0
    }
285
22.1k
    if (!ecdsa_signature_parse_der_lax(&sig, vchSig.data(), vchSig.size())) {
  Branch (285:9): [True: 0, False: 22.1k]
286
0
        return false;
287
0
    }
288
    /* libsecp256k1's ECDSA verification requires lower-S signatures, which have
289
     * not historically been enforced in Bitcoin, so normalize them first. */
290
22.1k
    secp256k1_ecdsa_signature_normalize(secp256k1_context_static, &sig, &sig);
291
22.1k
    return secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pubkey);
292
22.1k
}
293
294
0
bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
295
0
    if (vchSig.size() != COMPACT_SIGNATURE_SIZE)
  Branch (295:9): [True: 0, False: 0]
296
0
        return false;
297
0
    int recid = (vchSig[0] - 27) & 3;
298
0
    bool fComp = ((vchSig[0] - 27) & 4) != 0;
299
0
    secp256k1_pubkey pubkey;
300
0
    secp256k1_ecdsa_recoverable_signature sig;
301
0
    if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp256k1_context_static, &sig, &vchSig[1], recid)) {
  Branch (301:9): [True: 0, False: 0]
302
0
        return false;
303
0
    }
304
0
    if (!secp256k1_ecdsa_recover(secp256k1_context_static, &pubkey, &sig, hash.begin())) {
  Branch (304:9): [True: 0, False: 0]
305
0
        return false;
306
0
    }
307
0
    unsigned char pub[SIZE];
308
0
    size_t publen = SIZE;
309
0
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
  Branch (309:84): [True: 0, False: 0]
310
0
    Set(pub, pub + publen);
311
0
    return true;
312
0
}
313
314
88.7k
bool CPubKey::IsFullyValid() const {
315
88.7k
    if (!IsValid())
  Branch (315:9): [True: 0, False: 88.7k]
316
0
        return false;
317
88.7k
    secp256k1_pubkey pubkey;
318
88.7k
    return secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size());
319
88.7k
}
320
321
0
bool CPubKey::Decompress() {
322
0
    if (!IsValid())
  Branch (322:9): [True: 0, False: 0]
323
0
        return false;
324
0
    secp256k1_pubkey pubkey;
325
0
    if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
  Branch (325:9): [True: 0, False: 0]
326
0
        return false;
327
0
    }
328
0
    unsigned char pub[SIZE];
329
0
    size_t publen = SIZE;
330
0
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
331
0
    Set(pub, pub + publen);
332
0
    return true;
333
0
}
334
335
798k
bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
336
798k
    assert(IsValid());
  Branch (336:5): [True: 798k, False: 0]
337
798k
    assert((nChild >> 31) == 0);
  Branch (337:5): [True: 798k, False: 0]
338
798k
    assert(size() == COMPRESSED_SIZE);
  Branch (338:5): [True: 798k, False: 0]
339
798k
    unsigned char out[64];
340
798k
    BIP32Hash(cc, nChild, *begin(), begin()+1, out);
341
798k
    memcpy(ccChild.begin(), out+32, 32);
342
798k
    secp256k1_pubkey pubkey;
343
798k
    if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
  Branch (343:9): [True: 0, False: 798k]
344
0
        return false;
345
0
    }
346
798k
    if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_static, &pubkey, out)) {
  Branch (346:9): [True: 0, False: 798k]
347
0
        return false;
348
0
    }
349
798k
    unsigned char pub[COMPRESSED_SIZE];
350
798k
    size_t publen = COMPRESSED_SIZE;
351
798k
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, SECP256K1_EC_COMPRESSED);
352
798k
    pubkeyChild.Set(pub, pub + publen);
353
798k
    return true;
354
798k
}
355
356
EllSwiftPubKey::EllSwiftPubKey(std::span<const std::byte> ellswift) noexcept
357
44.3k
{
358
44.3k
    assert(ellswift.size() == SIZE);
  Branch (358:5): [True: 44.3k, False: 0]
359
44.3k
    std::copy(ellswift.begin(), ellswift.end(), m_pubkey.begin());
360
44.3k
}
361
362
CPubKey EllSwiftPubKey::Decode() const
363
0
{
364
0
    secp256k1_pubkey pubkey;
365
0
    secp256k1_ellswift_decode(secp256k1_context_static, &pubkey, UCharCast(m_pubkey.data()));
366
367
0
    size_t sz = CPubKey::COMPRESSED_SIZE;
368
0
    std::array<uint8_t, CPubKey::COMPRESSED_SIZE> vch_bytes;
369
370
0
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, vch_bytes.data(), &sz, &pubkey, SECP256K1_EC_COMPRESSED);
371
0
    assert(sz == vch_bytes.size());
  Branch (371:5): [True: 0, False: 0]
372
373
0
    return CPubKey{vch_bytes.begin(), vch_bytes.end()};
374
0
}
375
376
621k
void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
377
621k
    code[0] = nDepth;
378
621k
    memcpy(code+1, vchFingerprint, 4);
379
621k
    WriteBE32(code+5, nChild);
380
621k
    memcpy(code+9, chaincode.begin(), 32);
381
621k
    assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
  Branch (381:5): [True: 621k, False: 0]
382
621k
    memcpy(code+41, pubkey.begin(), CPubKey::COMPRESSED_SIZE);
383
621k
}
384
385
88.7k
void CExtPubKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
386
88.7k
    nDepth = code[0];
387
88.7k
    memcpy(vchFingerprint, code+1, 4);
388
88.7k
    nChild = ReadBE32(code+5);
389
88.7k
    memcpy(chaincode.begin(), code+9, 32);
390
88.7k
    pubkey.Set(code+41, code+BIP32_EXTKEY_SIZE);
391
88.7k
    if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || !pubkey.IsFullyValid()) pubkey = CPubKey();
  Branch (391:10): [True: 88.7k, False: 0]
  Branch (391:26): [True: 0, False: 88.7k]
  Branch (391:41): [True: 0, False: 88.7k]
  Branch (391:76): [True: 0, False: 88.7k]
392
88.7k
}
393
394
void CExtPubKey::EncodeWithVersion(unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE]) const
395
0
{
396
0
    memcpy(code, version, 4);
397
0
    Encode(&code[4]);
398
0
}
399
400
void CExtPubKey::DecodeWithVersion(const unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE])
401
0
{
402
0
    memcpy(version, code, 4);
403
0
    Decode(&code[4]);
404
0
}
405
406
798k
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const {
407
798k
    if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
  Branch (407:9): [True: 0, False: 798k]
408
798k
    out.nDepth = nDepth + 1;
409
798k
    CKeyID id = pubkey.GetID();
410
798k
    memcpy(out.vchFingerprint, &id, 4);
411
798k
    out.nChild = _nChild;
412
798k
    return pubkey.Derive(out.pubkey, out.chaincode, _nChild, chaincode);
413
798k
}
414
415
0
/* static */ bool CPubKey::CheckLowS(const std::vector<unsigned char>& vchSig) {
416
0
    secp256k1_ecdsa_signature sig;
417
0
    if (!ecdsa_signature_parse_der_lax(&sig, vchSig.data(), vchSig.size())) {
  Branch (417:9): [True: 0, False: 0]
418
0
        return false;
419
0
    }
420
0
    return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &sig));
421
0
}