Bitcoin Core 31.99.0
P2P Digital Currency
key.h
Go to the documentation of this file.
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 <serialize.h>
13#include <uint256.h>
14
15#include <stdexcept>
16#include <vector>
17
20
25typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
26
28constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
29
30// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
31using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
32
33class KeyPair;
34
36class CKey
37{
38public:
42 static const unsigned int SIZE = 279;
43 static const unsigned int COMPRESSED_SIZE = 214;
48 static_assert(
50 "COMPRESSED_SIZE is larger than SIZE");
51
52private:
54 using KeyType = std::array<unsigned char, 32>;
55
57 bool fCompressed{false};
58
61
63 bool static Check(const unsigned char* vch);
64
66 {
67 if (!keydata) keydata = make_secure_unique<KeyType>();
68 }
69
71 {
72 keydata.reset();
73 }
74
75public:
76 CKey() noexcept = default;
77 CKey(CKey&&) noexcept = default;
78 CKey& operator=(CKey&&) noexcept = default;
79
80 CKey& operator=(const CKey& other)
81 {
82 if (this != &other) {
83 if (other.keydata) {
85 *keydata = *other.keydata;
86 } else {
88 }
89 fCompressed = other.fCompressed;
90 }
91 return *this;
92 }
93
94 CKey(const CKey& other) { *this = other; }
95
96 friend bool operator==(const CKey& a, const CKey& b)
97 {
98 return a.fCompressed == b.fCompressed &&
99 a.size() == b.size() &&
100 memcmp(a.data(), b.data(), a.size()) == 0;
101 }
102
104 template <typename T>
105 void Set(const T pbegin, const T pend, bool fCompressedIn)
106 {
107 if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
108 ClearKeyData();
109 } else if (Check(UCharCast(&pbegin[0]))) {
110 MakeKeyData();
111 memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
112 fCompressed = fCompressedIn;
113 } else {
114 ClearKeyData();
115 }
116 }
117
119 unsigned int size() const { return keydata ? keydata->size() : 0; }
120 const std::byte* data() const { return keydata ? reinterpret_cast<const std::byte*>(keydata->data()) : nullptr; }
121 const std::byte* begin() const { return data(); }
122 const std::byte* end() const { return data() + size(); }
123
125 bool IsValid() const { return !!keydata; }
126
128 bool IsCompressed() const { return fCompressed; }
129
131 void MakeNewKey(bool fCompressed);
132
137 CPrivKey GetPrivKey() const;
138
143 CPubKey GetPubKey() const;
144
149 bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const;
150
158 bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
159
175 bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;
176
178 [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
179
184 bool VerifyPubKey(const CPubKey& vchPubKey) const;
185
187 bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
188
197 EllSwiftPubKey EllSwiftCreate(std::span<const std::byte> entropy) const;
198
207 const EllSwiftPubKey& our_ellswift,
208 bool initiating) const;
224 KeyPair ComputeKeyPair(const uint256* merkle_root) const;
225};
226
227CKey GenerateRandomKey(bool compressed = true) noexcept;
228
229struct CExtKey {
230 unsigned char nDepth;
231 unsigned char vchFingerprint[4];
232 unsigned int nChild;
235
236 friend bool operator==(const CExtKey& a, const CExtKey& b)
237 {
238 return a.nDepth == b.nDepth &&
239 memcmp(a.vchFingerprint, b.vchFingerprint, sizeof(vchFingerprint)) == 0 &&
240 a.nChild == b.nChild &&
241 a.chaincode == b.chaincode &&
242 a.key == b.key;
243 }
244
245 CExtKey() = default;
246 CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in)
247 {
248 std::copy(xpub.vchFingerprint, xpub.vchFingerprint + sizeof(xpub.vchFingerprint), vchFingerprint);
249 }
250
251 void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
252 void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
253 [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;
254 CExtPubKey Neuter() const;
255 void SetSeed(std::span<const std::byte> seed);
256};
257
270{
271public:
272 KeyPair() noexcept = default;
273 KeyPair(KeyPair&&) noexcept = default;
274 KeyPair& operator=(KeyPair&&) noexcept = default;
275 KeyPair& operator=(const KeyPair& other)
276 {
277 if (this != &other) {
278 if (other.m_keypair) {
280 *m_keypair = *other.m_keypair;
281 } else {
283 }
284 }
285 return *this;
286 }
287
288 KeyPair(const KeyPair& other) { *this = other; }
289
290 friend KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const;
291 [[nodiscard]] bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const;
292
294 bool IsValid() const { return !!m_keypair; }
295
296private:
297 KeyPair(const CKey& key, const uint256* merkle_root);
298
299 using KeyType = std::array<unsigned char, 96>;
301
303 {
304 if (!m_keypair) m_keypair = make_secure_unique<KeyType>();
305 }
306
308 {
309 m_keypair.reset();
310 }
311};
312
315
318
327{
328public:
329 ECC_Context();
330 ~ECC_Context();
331};
332
333#endif // BITCOIN_KEY_H
An encapsulated private key.
Definition: key.h:37
CKey() noexcept=default
KeyPair ComputeKeyPair(const uint256 *merkle_root) const
Compute a KeyPair.
Definition: key.cpp:347
static const unsigned int SIZE
secp256k1:
Definition: key.h:42
void MakeKeyData()
Definition: key.h:65
bool SignSchnorr(const uint256 &hash, std::span< unsigned char > sig, const uint256 *merkle_root, const uint256 &aux) const
Create a BIP-340 Schnorr signature, for the xonly-pubkey corresponding to *this, optionally tweaked b...
Definition: key.cpp:272
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:96
void ClearKeyData()
Definition: key.h:70
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:119
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:125
bool Sign(const uint256 &hash, std::vector< unsigned char > &vchSig, bool grind=true, uint32_t test_case=0) const
Create a DER-serialized signature.
Definition: key.cpp:208
const std::byte * begin() const
Definition: key.h:121
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey &their_ellswift, const EllSwiftPubKey &our_ellswift, bool initiating) const
Compute a BIP324-style ECDH shared secret.
Definition: key.cpp:327
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:169
static const unsigned int COMPRESSED_SIZE
Definition: key.h:43
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:128
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:161
bool fCompressed
Whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:57
EllSwiftPubKey EllSwiftCreate(std::span< const std::byte > entropy) const
Create an ellswift-encoded public key for this key, with specified entropy.
Definition: key.cpp:311
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:182
const std::byte * end() const
Definition: key.h:122
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:105
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:236
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
Definition: key.cpp:278
static bool Check(const unsigned char *vch)
Check whether the 32-byte array pointed to by vch is valid keydata.
Definition: key.cpp:157
std::array< unsigned char, 32 > KeyType
see www.keylength.com script supports up to 75 for single byte push
Definition: key.h:54
bool Derive(CKey &keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode &cc) const
Derive BIP32 child key.
Definition: key.cpp:292
secure_unique_ptr< KeyType > keydata
The actual byte data. nullptr for invalid keys.
Definition: key.h:60
CKey(const CKey &other)
Definition: key.h:94
bool SignCompact(const uint256 &hash, std::vector< unsigned char > &vchSig) const
Create a compact signature (65 bytes), which allows reconstructing the used public key.
Definition: key.cpp:249
const std::byte * data() const
Definition: key.h:120
An encapsulated public key.
Definition: pubkey.h:34
static const size_t OUTPUT_SIZE
Definition: sha256.h:21
RAII class initializing and deinitializing global state for elliptic curve support.
Definition: key.h:327
ECC_Context()
Definition: key.cpp:481
~ECC_Context()
Definition: key.cpp:486
KeyPair.
Definition: key.h:270
KeyPair() noexcept=default
bool SignSchnorr(const uint256 &hash, std::span< unsigned char > sig, const uint256 &aux) const
Definition: key.cpp:426
void MakeKeyPairData()
Definition: key.h:302
std::array< unsigned char, 96 > KeyType
Definition: key.h:299
bool IsValid() const
Check whether this keypair is valid.
Definition: key.h:294
secure_unique_ptr< KeyType > m_keypair
Definition: key.h:300
KeyPair(const KeyPair &other)
Definition: key.h:288
void ClearKeyPairData()
Definition: key.h:307
256-bit opaque blob.
Definition: uint256.h:196
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
CPrivKey is a serialized private key, with all parameters included (SIZE bytes)
Definition: key.h:25
secp256k1_context * GetSecp256k1SignContext()
Access the secp256k1 context used for signing and MuSig2 nonce generation.
Definition: key.cpp:448
static constexpr size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:28
std::array< std::byte, ECDH_SECRET_SIZE > ECDHSecret
Definition: key.h:31
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:442
CKey GenerateRandomKey(bool compressed=true) noexcept
Definition: key.cpp:352
DecodeResult Decode(const std::string &str, CharLimit limit)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:374
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:358
const unsigned int BIP32_EXTKEY_SIZE
Definition: pubkey.h:19
std::unique_ptr< T, SecureUniqueDeleter< T > > secure_unique_ptr
Definition: secure.h:63
unsigned char * UCharCast(char *c)
Definition: span.h:95
Definition: key.h:229
CExtKey()=default
unsigned char vchFingerprint[4]
Definition: key.h:231
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:246
CKey key
Definition: key.h:234
unsigned char nDepth
Definition: key.h:230
ChainCode chaincode
Definition: key.h:233
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:236
unsigned int nChild
Definition: key.h:232
unsigned char vchFingerprint[4]
Definition: pubkey.h:339
An ElligatorSwift-encoded public key.
Definition: pubkey.h:309