Coverage Report

Created: 2026-09-14 20:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/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
1.56k
    Secp256k1SelfTester() {
28
        /* Run libsecp256k1 self-test before using the secp256k1_context_static. */
29
1.56k
        secp256k1_selftest();
30
1.56k
    }
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
197k
int ecdsa_signature_parse_der_lax(secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) {
46
197k
    size_t rpos, rlen, spos, slen;
47
197k
    size_t pos = 0;
48
197k
    size_t lenbyte;
49
197k
    unsigned char tmpsig[64] = {0};
50
197k
    int overflow = 0;
51
52
    /* Hack to initialize sig with a correctly-parsed but invalid signature. */
53
197k
    secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
54
55
    /* Sequence tag byte */
56
197k
    if (pos == inputlen || input[pos] != 0x30) {
57
548
        return 0;
58
548
    }
59
196k
    pos++;
60
61
    /* Sequence length bytes */
62
196k
    if (pos == inputlen) {
63
0
        return 0;
64
0
    }
65
196k
    lenbyte = input[pos++];
66
196k
    if (lenbyte & 0x80) {
67
0
        lenbyte -= 0x80;
68
0
        if (lenbyte > inputlen - pos) {
69
0
            return 0;
70
0
        }
71
0
        pos += lenbyte;
72
0
    }
73
74
    /* Integer tag byte for R */
75
196k
    if (pos == inputlen || input[pos] != 0x02) {
76
0
        return 0;
77
0
    }
78
196k
    pos++;
79
80
    /* Integer length for R */
81
196k
    if (pos == inputlen) {
82
0
        return 0;
83
0
    }
84
196k
    lenbyte = input[pos++];
85
196k
    if (lenbyte & 0x80) {
86
0
        lenbyte -= 0x80;
87
0
        if (lenbyte > inputlen - pos) {
88
0
            return 0;
89
0
        }
90
0
        while (lenbyte > 0 && input[pos] == 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) {
96
0
            return 0;
97
0
        }
98
0
        rlen = 0;
99
0
        while (lenbyte > 0) {
100
0
            rlen = (rlen << 8) + input[pos];
101
0
            pos++;
102
0
            lenbyte--;
103
0
        }
104
196k
    } else {
105
196k
        rlen = lenbyte;
106
196k
    }
107
196k
    if (rlen > inputlen - pos) {
108
0
        return 0;
109
0
    }
110
196k
    rpos = pos;
111
196k
    pos += rlen;
112
113
    /* Integer tag byte for S */
114
196k
    if (pos == inputlen || input[pos] != 0x02) {
115
0
        return 0;
116
0
    }
117
196k
    pos++;
118
119
    /* Integer length for S */
120
196k
    if (pos == inputlen) {
121
0
        return 0;
122
0
    }
123
196k
    lenbyte = input[pos++];
124
196k
    if (lenbyte & 0x80) {
125
0
        lenbyte -= 0x80;
126
0
        if (lenbyte > inputlen - pos) {
127
0
            return 0;
128
0
        }
129
0
        while (lenbyte > 0 && input[pos] == 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) {
135
0
            return 0;
136
0
        }
137
0
        slen = 0;
138
0
        while (lenbyte > 0) {
139
0
            slen = (slen << 8) + input[pos];
140
0
            pos++;
141
0
            lenbyte--;
142
0
        }
143
196k
    } else {
144
196k
        slen = lenbyte;
145
196k
    }
146
196k
    if (slen > inputlen - pos) {
147
0
        return 0;
148
0
    }
149
196k
    spos = pos;
150
151
    /* Ignore leading zeroes in R */
152
228k
    while (rlen > 0 && input[rpos] == 0) {
153
31.4k
        rlen--;
154
31.4k
        rpos++;
155
31.4k
    }
156
    /* Copy R value */
157
196k
    if (rlen > 32) {
158
1
        overflow = 1;
159
196k
    } else {
160
196k
        memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
161
196k
    }
162
163
    /* Ignore leading zeroes in S */
164
199k
    while (slen > 0 && input[spos] == 0) {
165
3.07k
        slen--;
166
3.07k
        spos++;
167
3.07k
    }
168
    /* Copy S value */
169
196k
    if (slen > 32) {
170
0
        overflow = 1;
171
196k
    } else {
172
196k
        memcpy(tmpsig + 64 - slen, input + spos, slen);
173
196k
    }
174
175
196k
    if (!overflow) {
176
196k
        overflow = !secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
177
196k
    }
178
196k
    if (overflow) {
179
        /* Overwrite the result again with a correctly-parsed but invalid
180
           signature if parsing failed. */
181
1
        memset(tmpsig, 0, 64);
182
1
        secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
183
1
    }
184
196k
    return 1;
185
196k
}
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<CPubKey> XOnlyPubKey::GetCPubKeys() const
201
395k
{
202
395k
    std::vector<CPubKey> out;
203
395k
    unsigned char b[33] = {0x02};
204
395k
    std::copy(m_keydata.begin(), m_keydata.end(), b + 1);
205
395k
    CPubKey fullpubkey;
206
395k
    fullpubkey.Set(b, b + 33);
207
395k
    out.push_back(fullpubkey);
208
395k
    b[0] = 0x03;
209
395k
    fullpubkey.Set(b, b + 33);
210
395k
    out.push_back(fullpubkey);
211
395k
    return out;
212
395k
}
213
214
std::vector<CKeyID> XOnlyPubKey::GetKeyIDs() const
215
394k
{
216
394k
    std::vector<CKeyID> out;
217
788k
    for (const CPubKey& pk : GetCPubKeys()) {
218
788k
        out.push_back(pk.GetID());
219
788k
    }
220
394k
    return out;
221
394k
}
222
223
CPubKey XOnlyPubKey::GetEvenCorrespondingCPubKey() const
224
130k
{
225
130k
    unsigned char full_key[CPubKey::COMPRESSED_SIZE] = {0x02};
226
130k
    std::copy(begin(), end(), full_key + 1);
227
130k
    return CPubKey{full_key};
228
130k
}
229
230
bool XOnlyPubKey::IsFullyValid() const
231
167k
{
232
167k
    secp256k1_xonly_pubkey pubkey;
233
167k
    return secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data());
234
167k
}
235
236
bool XOnlyPubKey::VerifySchnorr(const uint256& msg, std::span<const unsigned char> sigbytes) const
237
27.4k
{
238
27.4k
    assert(sigbytes.size() == 64);
239
27.4k
    secp256k1_xonly_pubkey pubkey;
240
27.4k
    if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data())) return false;
241
27.4k
    return secp256k1_schnorrsig_verify(secp256k1_context_static, sigbytes.data(), msg.begin(), 32, &pubkey);
242
27.4k
}
243
244
static const HashWriter HASHER_TAPTWEAK{TaggedHash("TapTweak")};
245
246
uint256 XOnlyPubKey::ComputeTapTweakHash(const uint256* merkle_root) const
247
264k
{
248
264k
    if (merkle_root == nullptr) {
249
        // We have no scripts. The actual tweak does not matter, but follow BIP341 here to
250
        // allow for reproducible tweaking.
251
128k
        return (HashWriter{HASHER_TAPTWEAK} << m_keydata).GetSHA256();
252
135k
    } else {
253
135k
        return (HashWriter{HASHER_TAPTWEAK} << m_keydata << *merkle_root).GetSHA256();
254
135k
    }
255
264k
}
256
257
bool XOnlyPubKey::CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const
258
114k
{
259
114k
    secp256k1_xonly_pubkey internal_key;
260
114k
    if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &internal_key, internal.data())) return false;
261
114k
    uint256 tweak = internal.ComputeTapTweakHash(&merkle_root);
262
114k
    return secp256k1_xonly_pubkey_tweak_add_check(secp256k1_context_static, m_keydata.begin(), parity, &internal_key, tweak.begin());
263
114k
}
264
265
std::optional<std::pair<XOnlyPubKey, bool>> XOnlyPubKey::CreateTapTweak(const uint256* merkle_root) const
266
148k
{
267
148k
    secp256k1_xonly_pubkey base_point;
268
148k
    if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &base_point, data())) return std::nullopt;
269
148k
    secp256k1_pubkey out;
270
148k
    uint256 tweak = ComputeTapTweakHash(merkle_root);
271
148k
    if (!secp256k1_xonly_pubkey_tweak_add(secp256k1_context_static, &out, &base_point, tweak.data())) return std::nullopt;
272
148k
    int parity = -1;
273
148k
    std::pair<XOnlyPubKey, bool> ret;
274
148k
    secp256k1_xonly_pubkey out_xonly;
275
148k
    if (!secp256k1_xonly_pubkey_from_pubkey(secp256k1_context_static, &out_xonly, &parity, &out)) return std::nullopt;
276
148k
    secp256k1_xonly_pubkey_serialize(secp256k1_context_static, ret.first.begin(), &out_xonly);
277
148k
    assert(parity == 0 || parity == 1);
278
148k
    ret.second = parity;
279
148k
    return ret;
280
148k
}
281
282
283
131k
bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
284
131k
    if (!IsValid())
285
0
        return false;
286
131k
    secp256k1_pubkey pubkey;
287
131k
    secp256k1_ecdsa_signature sig;
288
131k
    if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
289
0
        return false;
290
0
    }
291
131k
    if (!ecdsa_signature_parse_der_lax(&sig, vchSig.data(), vchSig.size())) {
292
548
        return false;
293
548
    }
294
    /* libsecp256k1's ECDSA verification requires lower-S signatures, which have
295
     * not historically been enforced in Bitcoin, so normalize them first. */
296
131k
    secp256k1_ecdsa_signature_normalize(secp256k1_context_static, &sig, &sig);
297
131k
    return secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pubkey);
298
131k
}
299
300
77
bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
301
77
    if (vchSig.size() != COMPACT_SIGNATURE_SIZE)
302
0
        return false;
303
77
    int recid = (vchSig[0] - 27) & 3;
304
77
    bool fComp = ((vchSig[0] - 27) & 4) != 0;
305
77
    secp256k1_pubkey pubkey;
306
77
    secp256k1_ecdsa_recoverable_signature sig;
307
77
    if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp256k1_context_static, &sig, &vchSig[1], recid)) {
308
0
        return false;
309
0
    }
310
77
    if (!secp256k1_ecdsa_recover(secp256k1_context_static, &pubkey, &sig, hash.begin())) {
311
1
        return false;
312
1
    }
313
76
    unsigned char pub[SIZE];
314
76
    size_t publen = SIZE;
315
76
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
316
76
    Set(pub, pub + publen);
317
76
    return true;
318
77
}
319
320
65.3k
bool CPubKey::IsFullyValid() const {
321
65.3k
    if (!IsValid())
322
18.6k
        return false;
323
46.7k
    secp256k1_pubkey pubkey;
324
46.7k
    return secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size());
325
65.3k
}
326
327
152
bool CPubKey::Decompress() {
328
152
    if (!IsValid())
329
0
        return false;
330
152
    secp256k1_pubkey pubkey;
331
152
    if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
332
2
        return false;
333
2
    }
334
150
    unsigned char pub[SIZE];
335
150
    size_t publen = SIZE;
336
150
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
337
150
    Set(pub, pub + publen);
338
150
    return true;
339
152
}
340
341
730k
bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc, uint256* bip32_tweak_out) const {
342
730k
    assert(IsValid());
343
730k
    assert((nChild >> 31) == 0);
344
730k
    assert(size() == COMPRESSED_SIZE);
345
730k
    unsigned char out[64];
346
730k
    BIP32Hash(cc, nChild, *begin(), begin()+1, out);
347
730k
    memcpy(ccChild.begin(), out+32, 32);
348
730k
    if (bip32_tweak_out) {
349
5.62k
        memcpy(bip32_tweak_out->begin(), out, 32);
350
5.62k
    }
351
730k
    secp256k1_pubkey pubkey;
352
730k
    if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
353
0
        return false;
354
0
    }
355
730k
    if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_static, &pubkey, out)) {
356
0
        return false;
357
0
    }
358
730k
    unsigned char pub[COMPRESSED_SIZE];
359
730k
    size_t publen = COMPRESSED_SIZE;
360
730k
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, SECP256K1_EC_COMPRESSED);
361
730k
    pubkeyChild.Set(pub, pub + publen);
362
730k
    return true;
363
730k
}
364
365
EllSwiftPubKey::EllSwiftPubKey(std::span<const std::byte> ellswift) noexcept
366
718
{
367
718
    assert(ellswift.size() == SIZE);
368
718
    std::copy(ellswift.begin(), ellswift.end(), m_pubkey.begin());
369
718
}
370
371
CPubKey EllSwiftPubKey::Decode() const
372
4
{
373
4
    secp256k1_pubkey pubkey;
374
4
    secp256k1_ellswift_decode(secp256k1_context_static, &pubkey, UCharCast(m_pubkey.data()));
375
376
4
    size_t sz = CPubKey::COMPRESSED_SIZE;
377
4
    std::array<uint8_t, CPubKey::COMPRESSED_SIZE> vch_bytes;
378
379
4
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, vch_bytes.data(), &sz, &pubkey, SECP256K1_EC_COMPRESSED);
380
4
    assert(sz == vch_bytes.size());
381
382
4
    return CPubKey{vch_bytes.begin(), vch_bytes.end()};
383
4
}
384
385
167k
void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
386
167k
    code[0] = nDepth;
387
167k
    std::ranges::copy(fingerprint, code+1);
388
167k
    WriteBE32(code+5, nChild);
389
167k
    memcpy(code+9, chaincode.begin(), 32);
390
167k
    assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
391
167k
    memcpy(code+41, pubkey.begin(), CPubKey::COMPRESSED_SIZE);
392
167k
}
393
394
13.4k
void CExtPubKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
395
13.4k
    nDepth = code[0];
396
13.4k
    std::copy_n(code + 1, fingerprint.size(), fingerprint.begin());
397
13.4k
    nChild = ReadBE32(code+5);
398
13.4k
    memcpy(chaincode.begin(), code+9, 32);
399
13.4k
    pubkey.Set(code+41, code+BIP32_EXTKEY_SIZE);
400
13.4k
    if ((nDepth == 0 && (nChild != 0 || ReadLE32(fingerprint.data()) != 0)) || !pubkey.IsFullyValid()) pubkey = CPubKey();
401
13.4k
}
402
403
void CExtPubKey::EncodeWithVersion(unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE]) const
404
9
{
405
9
    memcpy(code, version, 4);
406
9
    Encode(&code[4]);
407
9
}
408
409
void CExtPubKey::DecodeWithVersion(const unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE])
410
11
{
411
11
    memcpy(version, code, 4);
412
11
    Decode(&code[4]);
413
11
}
414
415
730k
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild, uint256* bip32_tweak_out) const {
416
730k
    if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
417
730k
    out.nDepth = nDepth + 1;
418
730k
    out.fingerprint = id_key_fingerprint();
419
730k
    out.nChild = _nChild;
420
730k
    return pubkey.Derive(out.pubkey, out.chaincode, _nChild, chaincode, bip32_tweak_out);
421
730k
}
422
423
65.3k
/* static */ bool CPubKey::CheckLowS(const std::vector<unsigned char>& vchSig) {
424
65.3k
    secp256k1_ecdsa_signature sig;
425
65.3k
    if (!ecdsa_signature_parse_der_lax(&sig, vchSig.data(), vchSig.size())) {
426
0
        return false;
427
0
    }
428
65.3k
    return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &sig));
429
65.3k
}