Bitcoin Core 32.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 <script/keyorigin.h>
12#include <serialize.h>
14#include <support/cleanse.h>
15#include <uint256.h>
16
17#include <array>
18#include <cassert>
19#include <optional>
20#include <span>
21#include <stdexcept>
22#include <utility>
23#include <vector>
24
27
32typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
33
35inline constexpr size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
36
37// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
38using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
39
40class KeyPair;
41
43class CKey
44{
45public:
49 static constexpr unsigned int SIZE{279};
50 static constexpr unsigned int COMPRESSED_SIZE{214};
55 static_assert(
57 "COMPRESSED_SIZE is larger than SIZE");
58
59private:
61 using KeyType = std::array<unsigned char, 32>;
62
64 bool fCompressed{false};
65
68
70 bool static Check(const unsigned char* vch);
71
73 {
74 if (!keydata) keydata = make_secure_unique<KeyType>();
75 }
76
78 {
79 keydata.reset();
80 }
81
82public:
83 CKey() noexcept = default;
84 CKey(CKey&&) noexcept = default;
85 CKey& operator=(CKey&&) noexcept = default;
86
87 CKey& operator=(const CKey& other)
88 {
89 if (this != &other) {
90 if (other.keydata) {
92 *keydata = *other.keydata;
93 } else {
95 }
96 fCompressed = other.fCompressed;
97 }
98 return *this;
99 }
100
101 CKey(const CKey& other) { *this = other; }
102
103 friend bool operator==(const CKey& a, const CKey& b)
104 {
105 return a.fCompressed == b.fCompressed &&
106 a.size() == b.size() &&
107 memcmp(a.data(), b.data(), a.size()) == 0;
108 }
109
111 template <typename T>
112 void Set(const T pbegin, const T pend, bool fCompressedIn)
113 {
114 if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
115 ClearKeyData();
116 } else if (Check(UCharCast(&pbegin[0]))) {
117 MakeKeyData();
118 memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
119 fCompressed = fCompressedIn;
120 } else {
121 ClearKeyData();
122 }
123 }
124
126 unsigned int size() const { return keydata ? keydata->size() : 0; }
127 const std::byte* data() const { return keydata ? reinterpret_cast<const std::byte*>(keydata->data()) : nullptr; }
128 const std::byte* begin() const { return data(); }
129 const std::byte* end() const { return data() + size(); }
130
132 bool IsValid() const { return !!keydata; }
133
135 bool IsCompressed() const { return fCompressed; }
136
138 void MakeNewKey(bool fCompressed);
139
144 CPrivKey GetPrivKey() const;
145
150 CPubKey GetPubKey() const;
151
156 bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const;
157
165 bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
166
182 bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;
183
185 [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
186
191 bool VerifyPubKey(const CPubKey& vchPubKey) const;
192
194 bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
195
204 EllSwiftPubKey EllSwiftCreate(std::span<const std::byte> entropy) const;
205
214 const EllSwiftPubKey& our_ellswift,
215 bool initiating) const;
231 KeyPair ComputeKeyPair(const uint256* merkle_root) const;
232};
233
234CKey GenerateRandomKey(bool compressed = true) noexcept;
235
236struct CExtKey {
237 unsigned char nDepth;
239 unsigned int nChild;
242
243 friend bool operator==(const CExtKey& a, const CExtKey& b)
244 {
245 return a.nDepth == b.nDepth &&
246 a.fingerprint == b.fingerprint &&
247 a.nChild == b.nChild &&
248 a.chaincode == b.chaincode &&
249 a.key == b.key;
250 }
251
252 CExtKey() = default;
253 CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), fingerprint(xpub.fingerprint), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in) {}
254
256 {
257 return key.GetPubKey().GetID().fingerprint();
258 }
259
261 template <typename Stream>
262 void Serialize(Stream& s) const
263 {
264 assert(key.size() == 32);
265 s << nDepth << fingerprint << Using<BigEndianFormatter<4>>(nChild) << chaincode << uint8_t{0} << std::span{key.data(), key.size()};
266 }
267 template <typename Stream>
269 {
270 uint8_t key_prefix;
271 std::vector<unsigned char, secure_allocator<unsigned char>> ser_key(32);
272 s >> nDepth >> fingerprint >> Using<BigEndianFormatter<4>>(nChild) >> chaincode >> key_prefix >> std::span{ser_key};
273 key.Set(ser_key.begin(), ser_key.end(), true);
274 if ((nDepth == 0 && (nChild != 0 || fingerprint != KeyFingerprint{})) || key_prefix != 0) key = CKey();
275 }
276 [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;
277 CExtPubKey Neuter() const;
278 void SetSeed(std::span<const std::byte> seed);
279};
280
285std::optional<std::pair<CExtKey, KeyOriginInfo>> DeriveExtKey(const CExtKey& ext_key, const std::vector<uint32_t>& path);
286
299{
300public:
301 KeyPair() noexcept = default;
302 KeyPair(KeyPair&&) noexcept = default;
303 KeyPair& operator=(KeyPair&&) noexcept = default;
304 KeyPair& operator=(const KeyPair& other)
305 {
306 if (this != &other) {
307 if (other.m_keypair) {
309 *m_keypair = *other.m_keypair;
310 } else {
312 }
313 }
314 return *this;
315 }
316
317 KeyPair(const KeyPair& other) { *this = other; }
318
319 friend KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const;
320 [[nodiscard]] bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const;
321
323 bool IsValid() const { return !!m_keypair; }
324
325private:
326 KeyPair(const CKey& key, const uint256* merkle_root);
327
328 using KeyType = std::array<unsigned char, 96>;
330
332 {
333 if (!m_keypair) m_keypair = make_secure_unique<KeyType>();
334 }
335
337 {
338 m_keypair.reset();
339 }
340};
341
344
347
356{
357public:
358 ECC_Context();
359 ~ECC_Context();
360};
361
362#endif // BITCOIN_KEY_H
An encapsulated private key.
Definition: key.h:44
CKey() noexcept=default
KeyPair ComputeKeyPair(const uint256 *merkle_root) const
Compute a KeyPair.
Definition: key.cpp:349
void MakeKeyData()
Definition: key.h:72
static constexpr unsigned int COMPRESSED_SIZE
Definition: key.h:50
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:274
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:103
void ClearKeyData()
Definition: key.h:77
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:126
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:132
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:210
const std::byte * begin() const
Definition: key.h:128
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey &their_ellswift, const EllSwiftPubKey &our_ellswift, bool initiating) const
Compute a BIP324-style ECDH shared secret.
Definition: key.cpp:329
static constexpr unsigned int SIZE
secp256k1:
Definition: key.h:49
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:171
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:135
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:163
bool fCompressed
Whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:64
EllSwiftPubKey EllSwiftCreate(std::span< const std::byte > entropy) const
Create an ellswift-encoded public key for this key, with specified entropy.
Definition: key.cpp:313
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
const std::byte * end() const
Definition: key.h:129
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:112
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:238
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
Definition: key.cpp:280
static bool Check(const unsigned char *vch)
Check whether the 32-byte array pointed to by vch is valid keydata.
Definition: key.cpp:159
std::array< unsigned char, 32 > KeyType
see www.keylength.com script supports up to 75 for single byte push
Definition: key.h:61
bool Derive(CKey &keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode &cc) const
Derive BIP32 child key.
Definition: key.cpp:294
secure_unique_ptr< KeyType > keydata
The actual byte data. nullptr for invalid keys.
Definition: key.h:67
CKey(const CKey &other)
Definition: key.h:101
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:251
const std::byte * data() const
Definition: key.h:127
KeyFingerprint fingerprint() const
Definition: pubkey.h:33
An encapsulated public key.
Definition: pubkey.h:43
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:169
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:356
ECC_Context()
Definition: key.cpp:476
~ECC_Context()
Definition: key.cpp:481
KeyPair.
Definition: key.h:299
KeyPair() noexcept=default
bool SignSchnorr(const uint256 &hash, std::span< unsigned char > sig, const uint256 &aux) const
Definition: key.cpp:421
void MakeKeyPairData()
Definition: key.h:331
std::array< unsigned char, 96 > KeyType
Definition: key.h:328
bool IsValid() const
Check whether this keypair is valid.
Definition: key.h:323
secure_unique_ptr< KeyType > m_keypair
Definition: key.h:329
KeyPair(const KeyPair &other)
Definition: key.h:317
void ClearKeyPairData()
Definition: key.h:336
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:32
secp256k1_context * GetSecp256k1SignContext()
Access the secp256k1 context used for signing and MuSig2 nonce generation.
Definition: key.cpp:443
constexpr size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:35
std::optional< std::pair< CExtKey, KeyOriginInfo > > DeriveExtKey(const CExtKey &ext_key, const std::vector< uint32_t > &path)
Get extended key and origin info for a given path.
Definition: key.cpp:369
std::array< std::byte, ECDH_SECRET_SIZE > ECDHSecret
Definition: key.h:38
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:437
CKey GenerateRandomKey(bool compressed=true) noexcept
Definition: key.cpp:354
SocketId Stream
Definition: util.h:30
std::array< unsigned char, 4 > KeyFingerprint
Definition: pubkey.h:25
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:236
CExtKey()=default
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:253
KeyFingerprint id_key_fingerprint() const
Definition: key.h:255
void Serialize(Stream &s) const
BIP32 serialization without the version bytes (BIP32_EXTKEY_SIZE bytes)
Definition: key.h:262
KeyFingerprint fingerprint
Definition: key.h:238
CKey key
Definition: key.h:241
unsigned char nDepth
Definition: key.h:237
ChainCode chaincode
Definition: key.h:240
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:243
unsigned int nChild
Definition: key.h:239
void Unserialize(Stream &s)
Definition: key.h:268
An ElligatorSwift-encoded public key.
Definition: pubkey.h:318
assert(!tx.IsCoinBase())