Bitcoin Core 30.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 <musig.h>
11#include <pubkey.h>
12#include <serialize.h>
14#include <uint256.h>
15
16#include <stdexcept>
17#include <vector>
18
19
24typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
25
27constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
28
29// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
30using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
31
32class KeyPair;
33
35class CKey
36{
37public:
41 static const unsigned int SIZE = 279;
42 static const unsigned int COMPRESSED_SIZE = 214;
47 static_assert(
49 "COMPRESSED_SIZE is larger than SIZE");
50
51private:
53 using KeyType = std::array<unsigned char, 32>;
54
56 bool fCompressed{false};
57
60
62 bool static Check(const unsigned char* vch);
63
65 {
66 if (!keydata) keydata = make_secure_unique<KeyType>();
67 }
68
70 {
71 keydata.reset();
72 }
73
74public:
75 CKey() noexcept = default;
76 CKey(CKey&&) noexcept = default;
77 CKey& operator=(CKey&&) noexcept = default;
78
79 CKey& operator=(const CKey& other)
80 {
81 if (this != &other) {
82 if (other.keydata) {
84 *keydata = *other.keydata;
85 } else {
87 }
88 fCompressed = other.fCompressed;
89 }
90 return *this;
91 }
92
93 CKey(const CKey& other) { *this = other; }
94
95 friend bool operator==(const CKey& a, const CKey& b)
96 {
97 return a.fCompressed == b.fCompressed &&
98 a.size() == b.size() &&
99 memcmp(a.data(), b.data(), a.size()) == 0;
100 }
101
103 template <typename T>
104 void Set(const T pbegin, const T pend, bool fCompressedIn)
105 {
106 if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
107 ClearKeyData();
108 } else if (Check(UCharCast(&pbegin[0]))) {
109 MakeKeyData();
110 memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
111 fCompressed = fCompressedIn;
112 } else {
113 ClearKeyData();
114 }
115 }
116
118 unsigned int size() const { return keydata ? keydata->size() : 0; }
119 const std::byte* data() const { return keydata ? reinterpret_cast<const std::byte*>(keydata->data()) : nullptr; }
120 const std::byte* begin() const { return data(); }
121 const std::byte* end() const { return data() + size(); }
122
124 bool IsValid() const { return !!keydata; }
125
127 bool IsCompressed() const { return fCompressed; }
128
130 void MakeNewKey(bool fCompressed);
131
136 CPrivKey GetPrivKey() const;
137
142 CPubKey GetPubKey() const;
143
148 bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const;
149
157 bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
158
174 bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;
175
177 [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
178
183 bool VerifyPubKey(const CPubKey& vchPubKey) const;
184
186 bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
187
196 EllSwiftPubKey EllSwiftCreate(std::span<const std::byte> entropy) const;
197
206 const EllSwiftPubKey& our_ellswift,
207 bool initiating) const;
223 KeyPair ComputeKeyPair(const uint256* merkle_root) const;
224
225 std::vector<uint8_t> CreateMuSig2Nonce(MuSig2SecNonce& secnonce, const uint256& sighash, const CPubKey& aggregate_pubkey, const std::vector<CPubKey>& pubkeys);
226 std::optional<uint256> CreateMuSig2PartialSig(const uint256& hash, const CPubKey& aggregate_pubkey, const std::vector<CPubKey>& pubkeys, const std::map<CPubKey, std::vector<uint8_t>>& pubnonces, MuSig2SecNonce& secnonce, const std::vector<std::pair<uint256, bool>>& tweaks);
227};
228
229CKey GenerateRandomKey(bool compressed = true) noexcept;
230
231struct CExtKey {
232 unsigned char nDepth;
233 unsigned char vchFingerprint[4];
234 unsigned int nChild;
237
238 friend bool operator==(const CExtKey& a, const CExtKey& b)
239 {
240 return a.nDepth == b.nDepth &&
241 memcmp(a.vchFingerprint, b.vchFingerprint, sizeof(vchFingerprint)) == 0 &&
242 a.nChild == b.nChild &&
243 a.chaincode == b.chaincode &&
244 a.key == b.key;
245 }
246
247 CExtKey() = default;
248 CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in)
249 {
250 std::copy(xpub.vchFingerprint, xpub.vchFingerprint + sizeof(xpub.vchFingerprint), vchFingerprint);
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
326{
327public:
328 ECC_Context();
329 ~ECC_Context();
330};
331
332#endif // BITCOIN_KEY_H
An encapsulated private key.
Definition: key.h:36
CKey() noexcept=default
KeyPair ComputeKeyPair(const uint256 *merkle_root) const
Compute a KeyPair.
Definition: key.cpp:348
static const unsigned int SIZE
secp256k1:
Definition: key.h:41
void MakeKeyData()
Definition: key.h:64
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:273
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:95
void ClearKeyData()
Definition: key.h:69
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:118
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:124
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:209
const std::byte * begin() const
Definition: key.h:120
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey &their_ellswift, const EllSwiftPubKey &our_ellswift, bool initiating) const
Compute a BIP324-style ECDH shared secret.
Definition: key.cpp:328
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:170
static const unsigned int COMPRESSED_SIZE
Definition: key.h:42
std::optional< uint256 > CreateMuSig2PartialSig(const uint256 &hash, const CPubKey &aggregate_pubkey, const std::vector< CPubKey > &pubkeys, const std::map< CPubKey, std::vector< uint8_t > > &pubnonces, MuSig2SecNonce &secnonce, const std::vector< std::pair< uint256, bool > > &tweaks)
Definition: key.cpp:386
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:127
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:162
bool fCompressed
Whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:56
EllSwiftPubKey EllSwiftCreate(std::span< const std::byte > entropy) const
Create an ellswift-encoded public key for this key, with specified entropy.
Definition: key.cpp:312
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:183
std::vector< uint8_t > CreateMuSig2Nonce(MuSig2SecNonce &secnonce, const uint256 &sighash, const CPubKey &aggregate_pubkey, const std::vector< CPubKey > &pubkeys)
Definition: key.cpp:353
const std::byte * end() const
Definition: key.h:121
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:104
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:237
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
Definition: key.cpp:279
static bool Check(const unsigned char *vch)
Check whether the 32-byte array pointed to by vch is valid keydata.
Definition: key.cpp:158
std::array< unsigned char, 32 > KeyType
see www.keylength.com script supports up to 75 for single byte push
Definition: key.h:53
bool Derive(CKey &keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode &cc) const
Derive BIP32 child key.
Definition: key.cpp:293
secure_unique_ptr< KeyType > keydata
The actual byte data. nullptr for invalid keys.
Definition: key.h:59
CKey(const CKey &other)
Definition: key.h:93
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:250
const std::byte * data() const
Definition: key.h:119
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:326
ECC_Context()
Definition: key.cpp:599
~ECC_Context()
Definition: key.cpp:604
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:549
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
MuSig2SecNonce encapsulates a secret nonce in use in a MuSig2 signing session.
Definition: musig.h:49
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:24
static constexpr size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:27
std::array< std::byte, ECDH_SECRET_SIZE > ECDHSecret
Definition: key.h:30
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:565
CKey GenerateRandomKey(bool compressed=true) noexcept
Definition: key.cpp:475
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:95
Definition: key.h:231
CExtKey()=default
unsigned char vchFingerprint[4]
Definition: key.h:233
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:248
CKey key
Definition: key.h:236
unsigned char nDepth
Definition: key.h:232
ChainCode chaincode
Definition: key.h:235
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:238
unsigned int nChild
Definition: key.h:234
unsigned char vchFingerprint[4]
Definition: pubkey.h:349
An ElligatorSwift-encoded public key.
Definition: pubkey.h:314