Bitcoin Core  28.1.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 
23 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
24 
26 constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
27 
28 // Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
29 using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
30 
31 class KeyPair;
32 
34 class CKey
35 {
36 public:
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 
50 private:
52  using KeyType = std::array<unsigned char, 32>;
53 
55  bool fCompressed{false};
56 
59 
61  bool static Check(const unsigned char* vch);
62 
63  void MakeKeyData()
64  {
65  if (!keydata) keydata = make_secure_unique<KeyType>();
66  }
67 
68  void ClearKeyData()
69  {
70  keydata.reset();
71  }
72 
73 public:
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) {
82  MakeKeyData();
83  *keydata = *other.keydata;
84  } else {
85  ClearKeyData();
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 
204  ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
205  const EllSwiftPubKey& our_ellswift,
206  bool initiating) const;
222  KeyPair ComputeKeyPair(const uint256* merkle_root) const;
223 };
224 
225 CKey GenerateRandomKey(bool compressed = true) noexcept;
226 
227 struct 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 
267 class KeyPair
268 {
269 public:
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) {
277  MakeKeyPairData();
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 
294 private:
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 
312 bool ECC_InitSanityCheck();
313 
322 {
323 public:
324  ECC_Context();
325  ~ECC_Context();
326 };
327 
328 #endif // BITCOIN_KEY_H
void MakeKeyPairData()
Definition: key.h:300
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:169
unsigned char vchFingerprint[4]
Definition: pubkey.h:345
std::array< unsigned char, 32 > KeyType
see www.keylength.com script supports up to 75 for single byte push
Definition: key.h:52
bool SignSchnorr(const uint256 &hash, Span< unsigned char > sig, const uint256 &aux) const
Definition: key.cpp:426
void ClearKeyPairData()
Definition: key.h:305
std::array< unsigned char, 96 > KeyType
Definition: key.h:297
CKey key
Definition: key.h:232
CKey GenerateRandomKey(bool compressed=true) noexcept
Definition: key.cpp:352
EllSwiftPubKey EllSwiftCreate(Span< const std::byte > entropy) const
Create an ellswift-encoded public key for this key, with specified entropy.
Definition: key.cpp:311
RAII class initializing and deinitializing global state for elliptic curve support.
Definition: key.h:321
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:236
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:182
Definition: key.h:227
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
unsigned char vchFingerprint[4]
Definition: key.h:229
const std::byte * end() const
Definition: key.h:120
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:358
static const unsigned int SIZE
secp256k1:
Definition: key.h:40
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
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey &their_ellswift, const EllSwiftPubKey &our_ellswift, bool initiating) const
Compute a BIP324-style ECDH shared secret.
Definition: key.cpp:327
void ClearKeyData()
Definition: key.h:68
std::unique_ptr< T, SecureUniqueDeleter< T > > secure_unique_ptr
Definition: secure.h:68
KeyPair.
Definition: key.h:267
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
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
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
static const unsigned int COMPRESSED_SIZE
Definition: key.h:41
KeyPair() noexcept=default
KeyPair ComputeKeyPair(const uint256 *merkle_root) const
Compute a KeyPair.
Definition: key.cpp:347
DecodeResult Decode(const std::string &str, CharLimit limit)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:374
secure_unique_ptr< KeyType > m_keypair
Definition: key.h:298
const std::byte * data() const
Definition: key.h:118
unsigned char nDepth
Definition: key.h:228
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:234
An encapsulated public key.
Definition: pubkey.h:33
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:161
unsigned int nChild
Definition: key.h:230
An ElligatorSwift-encoded public key.
Definition: pubkey.h:309
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:117
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:126
ChainCode chaincode
Definition: key.h:231
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:103
bool IsValid() const
Check whether this keypair is valid.
Definition: key.h:292
256-bit opaque blob.
Definition: uint256.h:178
std::array< std::byte, ECDH_SECRET_SIZE > ECDHSecret
Definition: key.h:29
static constexpr size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:26
bool Derive(CKey &keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode &cc) const
Derive BIP32 child key.
Definition: key.cpp:292
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:244
~ECC_Context()
Definition: key.cpp:481
const std::byte * begin() const
Definition: key.h:119
const unsigned int BIP32_EXTKEY_SIZE
Definition: pubkey.h:19
bool fCompressed
Whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:55
static const size_t OUTPUT_SIZE
Definition: sha256.h:21
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:442
unsigned char * UCharCast(char *c)
Definition: span.h:288
KeyPair & operator=(KeyPair &&) noexcept=default
static bool Check(const unsigned char *vch)
Check whether the 32-byte array pointed to by vch is valid keydata.
Definition: key.cpp:157
An encapsulated private key.
Definition: key.h:34
A Span is an object that can refer to a contiguous sequence of objects.
Definition: solver.h:20
KeyPair & operator=(const KeyPair &other)
Definition: key.h:273
void MakeKeyData()
Definition: key.h:63
KeyPair(const KeyPair &other)
Definition: key.h:286
CKey() noexcept=default
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
Definition: key.cpp:278
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:94
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:123
ECC_Context()
Definition: key.cpp:476