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 <script/keyorigin.h>
12#include <serialize.h>
14#include <uint256.h>
15
16#include <optional>
17#include <stdexcept>
18#include <utility>
19#include <vector>
20
23
28typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
29
31inline constexpr size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
32
33// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
34using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
35
36class KeyPair;
37
39class CKey
40{
41public:
45 static constexpr unsigned int SIZE{279};
46 static constexpr unsigned int COMPRESSED_SIZE{214};
51 static_assert(
53 "COMPRESSED_SIZE is larger than SIZE");
54
55private:
57 using KeyType = std::array<unsigned char, 32>;
58
60 bool fCompressed{false};
61
64
66 bool static Check(const unsigned char* vch);
67
69 {
70 if (!keydata) keydata = make_secure_unique<KeyType>();
71 }
72
74 {
75 keydata.reset();
76 }
77
78public:
79 CKey() noexcept = default;
80 CKey(CKey&&) noexcept = default;
81 CKey& operator=(CKey&&) noexcept = default;
82
83 CKey& operator=(const CKey& other)
84 {
85 if (this != &other) {
86 if (other.keydata) {
88 *keydata = *other.keydata;
89 } else {
91 }
92 fCompressed = other.fCompressed;
93 }
94 return *this;
95 }
96
97 CKey(const CKey& other) { *this = other; }
98
99 friend bool operator==(const CKey& a, const CKey& b)
100 {
101 return a.fCompressed == b.fCompressed &&
102 a.size() == b.size() &&
103 memcmp(a.data(), b.data(), a.size()) == 0;
104 }
105
107 template <typename T>
108 void Set(const T pbegin, const T pend, bool fCompressedIn)
109 {
110 if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
111 ClearKeyData();
112 } else if (Check(UCharCast(&pbegin[0]))) {
113 MakeKeyData();
114 memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
115 fCompressed = fCompressedIn;
116 } else {
117 ClearKeyData();
118 }
119 }
120
122 unsigned int size() const { return keydata ? keydata->size() : 0; }
123 const std::byte* data() const { return keydata ? reinterpret_cast<const std::byte*>(keydata->data()) : nullptr; }
124 const std::byte* begin() const { return data(); }
125 const std::byte* end() const { return data() + size(); }
126
128 bool IsValid() const { return !!keydata; }
129
131 bool IsCompressed() const { return fCompressed; }
132
134 void MakeNewKey(bool fCompressed);
135
140 CPrivKey GetPrivKey() const;
141
146 CPubKey GetPubKey() const;
147
152 bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const;
153
161 bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
162
178 bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;
179
181 [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
182
187 bool VerifyPubKey(const CPubKey& vchPubKey) const;
188
190 bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
191
200 EllSwiftPubKey EllSwiftCreate(std::span<const std::byte> entropy) const;
201
210 const EllSwiftPubKey& our_ellswift,
211 bool initiating) const;
227 KeyPair ComputeKeyPair(const uint256* merkle_root) const;
228};
229
230CKey GenerateRandomKey(bool compressed = true) noexcept;
231
232struct CExtKey {
233 unsigned char nDepth;
235 unsigned int nChild;
238
239 friend bool operator==(const CExtKey& a, const CExtKey& b)
240 {
241 return a.nDepth == b.nDepth &&
242 a.fingerprint == b.fingerprint &&
243 a.nChild == b.nChild &&
244 a.chaincode == b.chaincode &&
245 a.key == b.key;
246 }
247
248 CExtKey() = default;
249 CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), fingerprint(xpub.fingerprint), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in) {}
250
252 {
253 return key.GetPubKey().GetID().fingerprint();
254 }
255
256 void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
257 void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
258 [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;
259 CExtPubKey Neuter() const;
260 void SetSeed(std::span<const std::byte> seed);
261};
262
267std::optional<std::pair<CExtKey, KeyOriginInfo>> DeriveExtKey(const CExtKey& ext_key, const std::vector<uint32_t>& path);
268
281{
282public:
283 KeyPair() noexcept = default;
284 KeyPair(KeyPair&&) noexcept = default;
285 KeyPair& operator=(KeyPair&&) noexcept = default;
286 KeyPair& operator=(const KeyPair& other)
287 {
288 if (this != &other) {
289 if (other.m_keypair) {
291 *m_keypair = *other.m_keypair;
292 } else {
294 }
295 }
296 return *this;
297 }
298
299 KeyPair(const KeyPair& other) { *this = other; }
300
301 friend KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const;
302 [[nodiscard]] bool SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const;
303
305 bool IsValid() const { return !!m_keypair; }
306
307private:
308 KeyPair(const CKey& key, const uint256* merkle_root);
309
310 using KeyType = std::array<unsigned char, 96>;
312
314 {
315 if (!m_keypair) m_keypair = make_secure_unique<KeyType>();
316 }
317
319 {
320 m_keypair.reset();
321 }
322};
323
326
329
338{
339public:
340 ECC_Context();
341 ~ECC_Context();
342};
343
344#endif // BITCOIN_KEY_H
An encapsulated private key.
Definition: key.h:40
CKey() noexcept=default
KeyPair ComputeKeyPair(const uint256 *merkle_root) const
Compute a KeyPair.
Definition: key.cpp:349
void MakeKeyData()
Definition: key.h:68
static constexpr unsigned int COMPRESSED_SIZE
Definition: key.h:46
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:99
void ClearKeyData()
Definition: key.h:73
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:122
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:128
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:124
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:45
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:131
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:60
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:125
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:108
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:57
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:63
CKey(const CKey &other)
Definition: key.h:97
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:123
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:338
ECC_Context()
Definition: key.cpp:495
~ECC_Context()
Definition: key.cpp:500
KeyPair.
Definition: key.h:281
KeyPair() noexcept=default
bool SignSchnorr(const uint256 &hash, std::span< unsigned char > sig, const uint256 &aux) const
Definition: key.cpp:440
void MakeKeyPairData()
Definition: key.h:313
std::array< unsigned char, 96 > KeyType
Definition: key.h:310
bool IsValid() const
Check whether this keypair is valid.
Definition: key.h:305
secure_unique_ptr< KeyType > m_keypair
Definition: key.h:311
KeyPair(const KeyPair &other)
Definition: key.h:299
void ClearKeyPairData()
Definition: key.h:318
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:28
secp256k1_context * GetSecp256k1SignContext()
Access the secp256k1 context used for signing and MuSig2 nonce generation.
Definition: key.cpp:462
constexpr size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:31
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:34
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:456
CKey GenerateRandomKey(bool compressed=true) noexcept
Definition: key.cpp:354
DecodeResult Decode(const std::string &str, CharLimit limit)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:373
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:357
constexpr 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:232
CExtKey()=default
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:249
KeyFingerprint id_key_fingerprint() const
Definition: key.h:251
KeyFingerprint fingerprint
Definition: key.h:234
CKey key
Definition: key.h:237
unsigned char nDepth
Definition: key.h:233
ChainCode chaincode
Definition: key.h:236
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:239
unsigned int nChild
Definition: key.h:235
An ElligatorSwift-encoded public key.
Definition: pubkey.h:315