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 constexpr unsigned int SIZE{279};
43 static constexpr 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;
232 unsigned int nChild;
235
236 friend bool operator==(const CExtKey& a, const CExtKey& b)
237 {
238 return a.nDepth == b.nDepth &&
239 a.fingerprint == b.fingerprint &&
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), fingerprint(xpub.fingerprint), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in) {}
247
249 {
250 return key.GetPubKey().GetID().fingerprint();
251 }
252
253 void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
254 void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
255 [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;
256 CExtPubKey Neuter() const;
257 void SetSeed(std::span<const std::byte> seed);
258};
259
272{
273public:
274 KeyPair() noexcept = default;
275 KeyPair(KeyPair&&) noexcept = default;
276 KeyPair& operator=(KeyPair&&) noexcept = default;
277 KeyPair& operator=(const KeyPair& other)
278 {
279 if (this != &other) {
280 if (other.m_keypair) {
282 *m_keypair = *other.m_keypair;
283 } else {
285 }
286 }
287 return *this;
288 }
289
290 KeyPair(const KeyPair& other) { *this = other; }
291
292 friend KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const;
293 [[nodiscard]] bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const;
294
296 bool IsValid() const { return !!m_keypair; }
297
298private:
299 KeyPair(const CKey& key, const uint256* merkle_root);
300
301 using KeyType = std::array<unsigned char, 96>;
303
305 {
306 if (!m_keypair) m_keypair = make_secure_unique<KeyType>();
307 }
308
310 {
311 m_keypair.reset();
312 }
313};
314
317
320
329{
330public:
331 ECC_Context();
332 ~ECC_Context();
333};
334
335#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
void MakeKeyData()
Definition: key.h:65
static constexpr unsigned int COMPRESSED_SIZE
Definition: key.h:43
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
static constexpr unsigned int SIZE
secp256k1:
Definition: key.h:42
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:169
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
KeyFingerprint fingerprint() const
Definition: pubkey.h:30
An encapsulated public key.
Definition: pubkey.h:40
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:166
static constexpr size_t OUTPUT_SIZE
Definition: sha256.h:21
A BIP32 chain code.
Definition: hash.h:23
RAII class initializing and deinitializing global state for elliptic curve support.
Definition: key.h:329
ECC_Context()
Definition: key.cpp:481
~ECC_Context()
Definition: key.cpp:486
KeyPair.
Definition: key.h:272
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:304
std::array< unsigned char, 96 > KeyType
Definition: key.h:301
bool IsValid() const
Check whether this keypair is valid.
Definition: key.h:296
secure_unique_ptr< KeyType > m_keypair
Definition: key.h:302
KeyPair(const KeyPair &other)
Definition: key.h:290
void ClearKeyPairData()
Definition: key.h:309
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::array< unsigned char, 4 > KeyFingerprint
Definition: pubkey.h:22
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
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:246
KeyFingerprint id_key_fingerprint() const
Definition: key.h:248
KeyFingerprint fingerprint
Definition: key.h:231
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
An ElligatorSwift-encoded public key.
Definition: pubkey.h:315