Bitcoin Core  27.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-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 
32 class CKey
33 {
34 public:
38  static const unsigned int SIZE = 279;
39  static const unsigned int COMPRESSED_SIZE = 214;
44  static_assert(
46  "COMPRESSED_SIZE is larger than SIZE");
47 
48 private:
50  using KeyType = std::array<unsigned char, 32>;
51 
53  bool fCompressed{false};
54 
57 
59  bool static Check(const unsigned char* vch);
60 
61  void MakeKeyData()
62  {
63  if (!keydata) keydata = make_secure_unique<KeyType>();
64  }
65 
66  void ClearKeyData()
67  {
68  keydata.reset();
69  }
70 
71 public:
72  CKey() noexcept = default;
73  CKey(CKey&&) noexcept = default;
74  CKey& operator=(CKey&&) noexcept = default;
75 
76  CKey& operator=(const CKey& other)
77  {
78  if (this != &other) {
79  if (other.keydata) {
80  MakeKeyData();
81  *keydata = *other.keydata;
82  } else {
83  ClearKeyData();
84  }
85  fCompressed = other.fCompressed;
86  }
87  return *this;
88  }
89 
90  CKey(const CKey& other) { *this = other; }
91 
92  friend bool operator==(const CKey& a, const CKey& b)
93  {
94  return a.fCompressed == b.fCompressed &&
95  a.size() == b.size() &&
96  memcmp(a.data(), b.data(), a.size()) == 0;
97  }
98 
100  template <typename T>
101  void Set(const T pbegin, const T pend, bool fCompressedIn)
102  {
103  if (size_t(pend - pbegin) != std::tuple_size_v<KeyType>) {
104  ClearKeyData();
105  } else if (Check(UCharCast(&pbegin[0]))) {
106  MakeKeyData();
107  memcpy(keydata->data(), (unsigned char*)&pbegin[0], keydata->size());
108  fCompressed = fCompressedIn;
109  } else {
110  ClearKeyData();
111  }
112  }
113 
115  unsigned int size() const { return keydata ? keydata->size() : 0; }
116  const std::byte* data() const { return keydata ? reinterpret_cast<const std::byte*>(keydata->data()) : nullptr; }
117  const std::byte* begin() const { return data(); }
118  const std::byte* end() const { return data() + size(); }
119 
121  bool IsValid() const { return !!keydata; }
122 
124  bool IsCompressed() const { return fCompressed; }
125 
127  void MakeNewKey(bool fCompressed);
128 
133  CPrivKey GetPrivKey() const;
134 
139  CPubKey GetPubKey() const;
140 
145  bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const;
146 
154  bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
155 
171  bool SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;
172 
174  [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
175 
180  bool VerifyPubKey(const CPubKey& vchPubKey) const;
181 
183  bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
184 
194 
202  ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
203  const EllSwiftPubKey& our_ellswift,
204  bool initiating) const;
205 };
206 
207 CKey GenerateRandomKey(bool compressed = true) noexcept;
208 
209 struct CExtKey {
210  unsigned char nDepth;
211  unsigned char vchFingerprint[4];
212  unsigned int nChild;
215 
216  friend bool operator==(const CExtKey& a, const CExtKey& b)
217  {
218  return a.nDepth == b.nDepth &&
219  memcmp(a.vchFingerprint, b.vchFingerprint, sizeof(vchFingerprint)) == 0 &&
220  a.nChild == b.nChild &&
221  a.chaincode == b.chaincode &&
222  a.key == b.key;
223  }
224 
225  CExtKey() = default;
226  CExtKey(const CExtPubKey& xpub, const CKey& key_in) : nDepth(xpub.nDepth), nChild(xpub.nChild), chaincode(xpub.chaincode), key(key_in)
227  {
228  std::copy(xpub.vchFingerprint, xpub.vchFingerprint + sizeof(xpub.vchFingerprint), vchFingerprint);
229  }
230 
231  void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
232  void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
233  [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const;
234  CExtPubKey Neuter() const;
235  void SetSeed(Span<const std::byte> seed);
236 };
237 
239 bool ECC_InitSanityCheck();
240 
249 {
250 public:
251  ECC_Context();
252  ~ECC_Context();
253 };
254 
255 #endif // BITCOIN_KEY_H
An encapsulated private key.
Definition: key.h:33
CKey() noexcept=default
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
static const unsigned int SIZE
secp256k1:
Definition: key.h:38
void MakeKeyData()
Definition: key.h:61
const std::byte * end() const
Definition: key.h:118
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:92
void ClearKeyData()
Definition: key.h:66
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:115
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:121
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
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey &their_ellswift, const EllSwiftPubKey &our_ellswift, bool initiating) const
Compute a BIP324-style ECDH shared secret.
Definition: key.cpp:346
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:169
static const unsigned int COMPRESSED_SIZE
Definition: key.h:39
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:124
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:53
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:182
const std::byte * data() const
Definition: key.h:116
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:101
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:236
EllSwiftPubKey EllSwiftCreate(Span< const std::byte > entropy) const
Create an ellswift-encoded public key for this key, with specified entropy.
Definition: key.cpp:330
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
Definition: key.cpp:297
static bool Check(const unsigned char *vch)
Check whether the 32-byte array pointed to by vch is valid keydata.
Definition: key.cpp:157
const std::byte * begin() const
Definition: key.h:117
std::array< unsigned char, 32 > KeyType
see www.keylength.com script supports up to 75 for single byte push
Definition: key.h:50
bool Derive(CKey &keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode &cc) const
Derive BIP32 child key.
Definition: key.cpp:311
secure_unique_ptr< KeyType > keydata
The actual byte data. nullptr for invalid keys.
Definition: key.h:56
CKey(const CKey &other)
Definition: key.h:90
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
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:249
ECC_Context()
Definition: key.cpp:457
~ECC_Context()
Definition: key.cpp:462
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
256-bit opaque blob.
Definition: uint256.h:127
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
constexpr static size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:26
std::array< std::byte, ECDH_SECRET_SIZE > ECDHSecret
Definition: key.h:29
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:423
CKey GenerateRandomKey(bool compressed=true) noexcept
Definition: key.cpp:366
DecodeResult Decode(const std::string &str, CharLimit limit)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:377
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:361
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:288
Definition: key.h:209
CExtKey()=default
unsigned char vchFingerprint[4]
Definition: key.h:211
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:226
CKey key
Definition: key.h:214
unsigned char nDepth
Definition: key.h:210
ChainCode chaincode
Definition: key.h:213
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:216
unsigned int nChild
Definition: key.h:212
unsigned char vchFingerprint[4]
Definition: pubkey.h:345
An ElligatorSwift-encoded public key.
Definition: pubkey.h:310