Bitcoin Core 28.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-2022 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
18
23typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
24
26constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
27
28// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
29using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
30
31class KeyPair;
32
34class CKey
35{
36public:
40 static const unsigned int SIZE = 279;
41 static const unsigned int COMPRESSED_SIZE = 214;
46 static_assert(
48 "COMPRESSED_SIZE is larger than SIZE");
49
50private:
52 using KeyType = std::array<unsigned char, 32>;
53
55 bool fCompressed{false};
56
59
61 bool static Check(const unsigned char* vch);
62
64 {
65 if (!keydata) keydata = make_secure_unique<KeyType>();
66 }
67
69 {
70 keydata.reset();
71 }
72
73public:
74 CKey() noexcept = default;
75 CKey(CKey&&) noexcept = default;
76 CKey& operator=(CKey&&) noexcept = default;
77
78 CKey& operator=(const CKey& other)
79 {
80 if (this != &other) {
81 if (other.keydata) {
83 *keydata = *other.keydata;
84 } else {
86 }
87 fCompressed = other.fCompressed;
88 }
89 return *this;
90 }
91
92 CKey(const CKey& other) { *this = other; }
93
94 friend bool operator==(const CKey& a, const CKey& b)
95 {
96 return a.fCompressed == b.fCompressed &&
97 a.size() == b.size() &&
98 memcmp(a.data(), b.data(), a.size()) == 0;
99 }
100
102 template <typename T>
103 void Set(const T pbegin, const T pend, bool fCompressedIn)
104 {
105 if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
106 ClearKeyData();
107 } else if (Check(UCharCast(&pbegin[0]))) {
108 MakeKeyData();
109 memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
110 fCompressed = fCompressedIn;
111 } else {
112 ClearKeyData();
113 }
114 }
115
117 unsigned int size() const { return keydata ? keydata->size() : 0; }
118 const std::byte* data() const { return keydata ? reinterpret_cast<const std::byte*>(keydata->data()) : nullptr; }
119 const std::byte* begin() const { return data(); }
120 const std::byte* end() const { return data() + size(); }
121
123 bool IsValid() const { return !!keydata; }
124
126 bool IsCompressed() const { return fCompressed; }
127
129 void MakeNewKey(bool fCompressed);
130
135 CPrivKey GetPrivKey() const;
136
141 CPubKey GetPubKey() const;
142
147 bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const;
148
156 bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
157
173 bool SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;
174
176 [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
177
182 bool VerifyPubKey(const CPubKey& vchPubKey) const;
183
185 bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
186
196
205 const EllSwiftPubKey& our_ellswift,
206 bool initiating) const;
222 KeyPair ComputeKeyPair(const uint256* merkle_root) const;
223};
224
225CKey GenerateRandomKey(bool compressed = true) noexcept;
226
227struct CExtKey {
228 unsigned char nDepth;
229 unsigned char vchFingerprint[4];
230 unsigned int nChild;
233
234 friend bool operator==(const CExtKey& a, const CExtKey& b)
235 {
236 return a.nDepth == b.nDepth &&
237 memcmp(a.vchFingerprint, b.vchFingerprint, sizeof(vchFingerprint)) == 0 &&
238 a.nChild == b.nChild &&
239 a.chaincode == b.chaincode &&
240 a.key == b.key;
241 }
242
243 CExtKey() = default;
244 CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in)
245 {
246 std::copy(xpub.vchFingerprint, xpub.vchFingerprint + sizeof(xpub.vchFingerprint), vchFingerprint);
247 }
248
249 void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
250 void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
251 [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;
252 CExtPubKey Neuter() const;
253 void SetSeed(Span<const std::byte> seed);
254};
255
268{
269public:
270 KeyPair() noexcept = default;
271 KeyPair(KeyPair&&) noexcept = default;
272 KeyPair& operator=(KeyPair&&) noexcept = default;
273 KeyPair& operator=(const KeyPair& other)
274 {
275 if (this != &other) {
276 if (other.m_keypair) {
278 *m_keypair = *other.m_keypair;
279 } else {
281 }
282 }
283 return *this;
284 }
285
286 KeyPair(const KeyPair& other) { *this = other; }
287
288 friend KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const;
289 [[nodiscard]] bool SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256& aux) const;
290
292 bool IsValid() const { return !!m_keypair; }
293
294private:
295 KeyPair(const CKey& key, const uint256* merkle_root);
296
297 using KeyType = std::array<unsigned char, 96>;
299
301 {
302 if (!m_keypair) m_keypair = make_secure_unique<KeyType>();
303 }
304
306 {
307 m_keypair.reset();
308 }
309};
310
313
322{
323public:
324 ECC_Context();
325 ~ECC_Context();
326};
327
328#endif // BITCOIN_KEY_H
An encapsulated private key.
Definition: key.h:35
CKey() noexcept=default
bool SignSchnorr(const uint256 &hash, 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
KeyPair ComputeKeyPair(const uint256 *merkle_root) const
Compute a KeyPair.
Definition: key.cpp:347
static const unsigned int SIZE
secp256k1:
Definition: key.h:40
void MakeKeyData()
Definition: key.h:63
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:94
void ClearKeyData()
Definition: key.h:68
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:117
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:123
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:119
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:41
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:126
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:55
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:182
const std::byte * end() const
Definition: key.h:120
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:103
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:236
EllSwiftPubKey EllSwiftCreate(Span< const std::byte > entropy) const
Create an ellswift-encoded public key for this key, with specified entropy.
Definition: key.cpp:311
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:52
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:58
CKey(const CKey &other)
Definition: key.h:92
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:118
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:322
ECC_Context()
Definition: key.cpp:476
~ECC_Context()
Definition: key.cpp:481
KeyPair.
Definition: key.h:268
KeyPair() noexcept=default
void MakeKeyPairData()
Definition: key.h:300
std::array< unsigned char, 96 > KeyType
Definition: key.h:297
bool IsValid() const
Check whether this keypair is valid.
Definition: key.h:292
bool SignSchnorr(const uint256 &hash, Span< unsigned char > sig, const uint256 &aux) const
Definition: key.cpp:426
secure_unique_ptr< KeyType > m_keypair
Definition: key.h:298
KeyPair(const KeyPair &other)
Definition: key.h:286
void ClearKeyPairData()
Definition: key.h:305
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
256-bit opaque blob.
Definition: uint256.h:190
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
CPrivKey is a serialized private key, with all parameters included (SIZE bytes)
Definition: key.h:23
static constexpr size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:26
std::array< std::byte, ECDH_SECRET_SIZE > ECDHSecret
Definition: key.h:29
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:68
unsigned char * UCharCast(char *c)
Definition: span.h:281
Definition: key.h:227
CExtKey()=default
unsigned char vchFingerprint[4]
Definition: key.h:229
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:244
CKey key
Definition: key.h:232
unsigned char nDepth
Definition: key.h:228
ChainCode chaincode
Definition: key.h:231
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:234
unsigned int nChild
Definition: key.h:230
unsigned char vchFingerprint[4]
Definition: pubkey.h:345
An ElligatorSwift-encoded public key.
Definition: pubkey.h:310