Coverage Report

Created: 2026-09-14 20:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/key.h
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Copyright (c) 2017 The Zcash developers
4
// Distributed under the MIT software license, see the accompanying
5
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7
#ifndef BITCOIN_KEY_H
8
#define BITCOIN_KEY_H
9
10
#include <pubkey.h>
11
#include <script/keyorigin.h>
12
#include <serialize.h>
13
#include <support/allocators/secure.h>
14
#include <uint256.h>
15
16
#include <optional>
17
#include <stdexcept>
18
#include <utility>
19
#include <vector>
20
21
struct secp256k1_context_struct;
22
typedef struct secp256k1_context_struct secp256k1_context;
23
24
/**
25
 * CPrivKey is a serialized private key, with all parameters included
26
 * (SIZE bytes)
27
 */
28
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
29
30
/** Size of ECDH shared secrets. */
31
inline constexpr size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
32
33
// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
34
using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
35
36
class KeyPair;
37
38
/** An encapsulated private key. */
39
class CKey
40
{
41
public:
42
    /**
43
     * secp256k1:
44
     */
45
    static constexpr unsigned int SIZE{279};
46
    static constexpr unsigned int COMPRESSED_SIZE{214};
47
    /**
48
     * see www.keylength.com
49
     * script supports up to 75 for single byte push
50
     */
51
    static_assert(
52
        SIZE >= COMPRESSED_SIZE,
53
        "COMPRESSED_SIZE is larger than SIZE");
54
55
private:
56
    /** Internal data container for private key material. */
57
    using KeyType = std::array<unsigned char, 32>;
58
59
    //! Whether the public key corresponding to this private key is (to be) compressed.
60
    bool fCompressed{false};
61
62
    //! The actual byte data. nullptr for invalid keys.
63
    secure_unique_ptr<KeyType> keydata;
64
65
    //! Check whether the 32-byte array pointed to by vch is valid keydata.
66
    bool static Check(const unsigned char* vch);
67
68
    void MakeKeyData()
69
493k
    {
70
493k
        if (!keydata) keydata = make_secure_unique<KeyType>();
71
493k
    }
72
73
    void ClearKeyData()
74
2
    {
75
2
        keydata.reset();
76
2
    }
77
78
public:
79
430k
    CKey() noexcept = default;
80
7.90k
    CKey(CKey&&) noexcept = default;
81
1.39k
    CKey& operator=(CKey&&) noexcept = default;
82
83
    CKey& operator=(const CKey& other)
84
339k
    {
85
339k
        if (this != &other) {
86
339k
            if (other.keydata) {
87
339k
                MakeKeyData();
88
339k
                *keydata = *other.keydata;
89
339k
            } else {
90
0
                ClearKeyData();
91
0
            }
92
339k
            fCompressed = other.fCompressed;
93
339k
        }
94
339k
        return *this;
95
339k
    }
96
97
116k
    CKey(const CKey& other) { *this = other; }
98
99
    friend bool operator==(const CKey& a, const CKey& b)
100
255
    {
101
255
        return a.fCompressed == b.fCompressed &&
102
255
            a.size() == b.size() &&
103
255
            memcmp(a.data(), b.data(), a.size()) == 0;
104
255
    }
105
106
    //! Initialize using begin and end iterators to byte data.
107
    template <typename T>
108
    void Set(const T pbegin, const T pend, bool fCompressedIn)
109
148k
    {
110
148k
        if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111
0
            ClearKeyData();
112
148k
        } else if (Check(UCharCast(&pbegin[0]))) {
113
148k
            MakeKeyData();
114
148k
            memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115
148k
            fCompressed = fCompressedIn;
116
148k
        } else {
117
2
            ClearKeyData();
118
2
        }
119
148k
    }
void CKey::Set<__gnu_cxx::__normal_iterator<unsigned char const*, std::vector<unsigned char, std::allocator<unsigned char>>>>(__gnu_cxx::__normal_iterator<unsigned char const*, std::vector<unsigned char, std::allocator<unsigned char>>>, __gnu_cxx::__normal_iterator<unsigned char const*, std::vector<unsigned char, std::allocator<unsigned char>>>, bool)
Line
Count
Source
109
7
    {
110
7
        if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111
0
            ClearKeyData();
112
7
        } else if (Check(UCharCast(&pbegin[0]))) {
113
7
            MakeKeyData();
114
7
            memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115
7
            fCompressed = fCompressedIn;
116
7
        } else {
117
0
            ClearKeyData();
118
0
        }
119
7
    }
void CKey::Set<__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>>(__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>, __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>, bool)
Line
Count
Source
109
1.52k
    {
110
1.52k
        if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111
0
            ClearKeyData();
112
1.52k
        } else if (Check(UCharCast(&pbegin[0]))) {
113
1.52k
            MakeKeyData();
114
1.52k
            memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115
1.52k
            fCompressed = fCompressedIn;
116
1.52k
        } else {
117
0
            ClearKeyData();
118
0
        }
119
1.52k
    }
void CKey::Set<unsigned char*>(unsigned char*, unsigned char*, bool)
Line
Count
Source
109
1.04k
    {
110
1.04k
        if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111
0
            ClearKeyData();
112
1.04k
        } else if (Check(UCharCast(&pbegin[0]))) {
113
1.04k
            MakeKeyData();
114
1.04k
            memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115
1.04k
            fCompressed = fCompressedIn;
116
1.04k
        } else {
117
0
            ClearKeyData();
118
0
        }
119
1.04k
    }
void CKey::Set<unsigned char const*>(unsigned char const*, unsigned char const*, bool)
Line
Count
Source
109
1.02k
    {
110
1.02k
        if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111
0
            ClearKeyData();
112
1.02k
        } else if (Check(UCharCast(&pbegin[0]))) {
113
1.02k
            MakeKeyData();
114
1.02k
            memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115
1.02k
            fCompressed = fCompressedIn;
116
1.02k
        } else {
117
2
            ClearKeyData();
118
2
        }
119
1.02k
    }
void CKey::Set<__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, secure_allocator<unsigned char>>>>(__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, secure_allocator<unsigned char>>>, __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, secure_allocator<unsigned char>>>, bool)
Line
Count
Source
109
3.44k
    {
110
3.44k
        if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111
0
            ClearKeyData();
112
3.44k
        } else if (Check(UCharCast(&pbegin[0]))) {
113
3.44k
            MakeKeyData();
114
3.44k
            memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115
3.44k
            fCompressed = fCompressedIn;
116
3.44k
        } else {
117
0
            ClearKeyData();
118
0
        }
119
3.44k
    }
void CKey::Set<std::byte const*>(std::byte const*, std::byte const*, bool)
Line
Count
Source
109
141k
    {
110
141k
        if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111
0
            ClearKeyData();
112
141k
        } else if (Check(UCharCast(&pbegin[0]))) {
113
141k
            MakeKeyData();
114
141k
            memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115
141k
            fCompressed = fCompressedIn;
116
141k
        } else {
117
0
            ClearKeyData();
118
0
        }
119
141k
    }
120
121
    //! Simple read-only vector-like interface.
122
109k
    unsigned int size() const { return keydata ? keydata->size() : 0; }
123
951k
    const std::byte* data() const { return keydata ? reinterpret_cast<const std::byte*>(keydata->data()) : nullptr; }
124
947k
    const std::byte* begin() const { return data(); }
125
637
    const std::byte* end() const { return data() + size(); }
126
127
    //! Check whether this private key is valid.
128
201k
    bool IsValid() const { return !!keydata; }
129
130
    //! Check whether the public key corresponding to this private key is (to be) compressed.
131
152k
    bool IsCompressed() const { return fCompressed; }
132
133
    //! Generate a new private key using a cryptographic PRNG.
134
    void MakeNewKey(bool fCompressed);
135
136
    /**
137
     * Convert the private key to a CPrivKey (serialized OpenSSL private key data).
138
     * This is expensive.
139
     */
140
    CPrivKey GetPrivKey() const;
141
142
    /**
143
     * Compute the public key from a private key.
144
     * This is expensive.
145
     */
146
    CPubKey GetPubKey() const;
147
148
    /**
149
     * Create a DER-serialized signature.
150
     * The test_case parameter tweaks the deterministic nonce.
151
     */
152
    bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const;
153
154
    /**
155
     * Create a compact signature (65 bytes), which allows reconstructing the used public key.
156
     * The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
157
     * The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
158
     *                  0x1D = second key with even y, 0x1E = second key with odd y,
159
     *                  add 0x04 for compressed keys.
160
     */
161
    bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
162
163
    /**
164
     * Create a BIP-340 Schnorr signature, for the xonly-pubkey corresponding to *this,
165
     * optionally tweaked by *merkle_root. Additional nonce entropy is provided through
166
     * aux.
167
     *
168
     * merkle_root is used to optionally perform tweaking of the private key, as specified
169
     * in BIP341:
170
     * - If merkle_root == nullptr: no tweaking is done, sign with key directly (this is
171
     *                              used for signatures in BIP342 script).
172
     * - If merkle_root->IsNull():  sign with key + H_TapTweak(pubkey) (this is used for
173
     *                              key path spending when no scripts are present).
174
     * - Otherwise:                 sign with key + H_TapTweak(pubkey || *merkle_root)
175
     *                              (this is used for key path spending, with specific
176
     *                              Merkle root of the script tree).
177
     */
178
    bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;
179
180
    //! Derive BIP32 child key.
181
    [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
182
183
    /**
184
     * Verify thoroughly whether a private key and a public key match.
185
     * This is done using a different mechanism than just regenerating it.
186
     */
187
    bool VerifyPubKey(const CPubKey& vchPubKey) const;
188
189
    //! Load private key and check that public key matches.
190
    bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
191
192
    /** Create an ellswift-encoded public key for this key, with specified entropy.
193
     *
194
     *  entropy must be a 32-byte span with additional entropy to use in the encoding. Every
195
     *  public key has ~2^256 different encodings, and this function will deterministically pick
196
     *  one of them, based on entropy. Note that even without truly random entropy, the
197
     *  resulting encoding will be indistinguishable from uniform to any adversary who does not
198
     *  know the private key (because the private key itself is always used as entropy as well).
199
     */
200
    EllSwiftPubKey EllSwiftCreate(std::span<const std::byte> entropy) const;
201
202
    /** Compute a BIP324-style ECDH shared secret.
203
     *
204
     *  - their_ellswift: EllSwiftPubKey that was received from the other side.
205
     *  - our_ellswift: EllSwiftPubKey that was sent to the other side (must have been generated
206
     *                  from *this using EllSwiftCreate()).
207
     *  - initiating: whether we are the initiating party (true) or responding party (false).
208
     */
209
    ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
210
                                       const EllSwiftPubKey& our_ellswift,
211
                                       bool initiating) const;
212
    /** Compute a KeyPair
213
     *
214
     *  Wraps a `secp256k1_keypair` type.
215
     *
216
     *  `merkle_root` is used to optionally perform tweaking of
217
     *  the internal key, as specified in BIP341:
218
     *
219
     *  - If merkle_root == nullptr: no tweaking is done, use the internal key directly (this is
220
     *                               used for signatures in BIP342 script).
221
     *  - If merkle_root->IsNull():  tweak the internal key with H_TapTweak(pubkey) (this is used for
222
     *                               key path spending when no scripts are present).
223
     *  - Otherwise:                 tweak the internal key with H_TapTweak(pubkey || *merkle_root)
224
     *                               (this is used for key path spending with the
225
     *                               Merkle root of the script tree).
226
     */
227
    KeyPair ComputeKeyPair(const uint256* merkle_root) const;
228
};
229
230
CKey GenerateRandomKey(bool compressed = true) noexcept;
231
232
struct CExtKey {
233
    unsigned char nDepth;
234
    KeyFingerprint fingerprint;
235
    unsigned int nChild;
236
    ChainCode chaincode;
237
    CKey key;
238
239
    friend bool operator==(const CExtKey& a, const CExtKey& b)
240
18
    {
241
18
        return a.nDepth == b.nDepth &&
242
18
            a.fingerprint == b.fingerprint &&
243
18
            a.nChild == b.nChild &&
244
18
            a.chaincode == b.chaincode &&
245
18
            a.key == b.key;
246
18
    }
247
248
130k
    CExtKey() = default;
249
115
    CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), fingerprint(xpub.fingerprint), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in) {}
250
251
    KeyFingerprint id_key_fingerprint() const
252
141k
    {
253
141k
        return key.GetPubKey().GetID().fingerprint();
254
141k
    }
255
256
    void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
257
    void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
258
    [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;
259
    CExtPubKey Neuter() const;
260
    void SetSeed(std::span<const std::byte> seed);
261
};
262
263
//! Get extended key and origin info for a given path
264
//! @param[in] ext_key The extended private key to derive from
265
//! @param[in] path The BIP 32 path
266
//! @return the resulting extended private key and origin info
267
std::optional<std::pair<CExtKey, KeyOriginInfo>> DeriveExtKey(const CExtKey& ext_key, const std::vector<uint32_t>& path);
268
269
/** KeyPair
270
 *
271
 *  Wraps a `secp256k1_keypair` type, an opaque data structure for holding a secret and public key.
272
 *  This is intended for BIP340 keys and allows us to easily determine if the secret key needs to
273
 *  be negated by checking the parity of the public key. This class primarily intended for passing
274
 *  secret keys to libsecp256k1 functions expecting a `secp256k1_keypair`. For all other cases,
275
 *  CKey should be preferred.
276
 *
277
 *  A KeyPair can be created from a CKey with an optional merkle_root tweak (per BIP342). See
278
 *  CKey::ComputeKeyPair for more details.
279
 */
280
class KeyPair
281
{
282
public:
283
    KeyPair() noexcept = default;
284
    KeyPair(KeyPair&&) noexcept = default;
285
    KeyPair& operator=(KeyPair&&) noexcept = default;
286
    KeyPair& operator=(const KeyPair& other)
287
0
    {
288
0
        if (this != &other) {
289
0
            if (other.m_keypair) {
290
0
                MakeKeyPairData();
291
0
                *m_keypair = *other.m_keypair;
292
0
            } else {
293
0
                ClearKeyPairData();
294
0
            }
295
0
        }
296
0
        return *this;
297
0
    }
298
299
0
    KeyPair(const KeyPair& other) { *this = other; }
300
301
    friend KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const;
302
    [[nodiscard]] bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const;
303
304
    //! Check whether this keypair is valid.
305
1.41k
    bool IsValid() const { return !!m_keypair; }
306
307
private:
308
    KeyPair(const CKey& key, const uint256* merkle_root);
309
310
    using KeyType = std::array<unsigned char, 96>;
311
    secure_unique_ptr<KeyType> m_keypair;
312
313
    void MakeKeyPairData()
314
1.41k
    {
315
1.41k
        if (!m_keypair) m_keypair = make_secure_unique<KeyType>();
316
1.41k
    }
317
318
    void ClearKeyPairData()
319
0
    {
320
0
        m_keypair.reset();
321
0
    }
322
};
323
324
/** Check that required EC support is available at runtime. */
325
bool ECC_InitSanityCheck();
326
327
/** Access the secp256k1 context used for signing and MuSig2 nonce generation. */
328
secp256k1_context* GetSecp256k1SignContext();
329
330
/**
331
 * RAII class initializing and deinitializing global state for elliptic curve support.
332
 * Only one instance may be initialized at a time.
333
 *
334
 * In the future global ECC state could be removed, and this class could contain
335
 * state and be passed as an argument to ECC key functions.
336
 */
337
class ECC_Context
338
{
339
public:
340
    ECC_Context();
341
    ~ECC_Context();
342
};
343
344
#endif // BITCOIN_KEY_H