Bitcoin Core  31.0.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 
24 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
25 
27 constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
28 
29 // Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
30 using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
31 
32 class KeyPair;
33 
35 class CKey
36 {
37 public:
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 
51 private:
53  using KeyType = std::array<unsigned char, 32>;
54 
56  bool fCompressed{false};
57 
60 
62  bool static Check(const unsigned char* vch);
63 
64  void MakeKeyData()
65  {
66  if (!keydata) keydata = make_secure_unique<KeyType>();
67  }
68 
69  void ClearKeyData()
70  {
71  keydata.reset();
72  }
73 
74 public:
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) {
83  MakeKeyData();
84  *keydata = *other.keydata;
85  } else {
86  ClearKeyData();
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 
205  ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
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 
229 CKey GenerateRandomKey(bool compressed = true) noexcept;
230 
231 struct 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 
271 class KeyPair
272 {
273 public:
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) {
281  MakeKeyPairData();
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 
298 private:
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 
316 bool ECC_InitSanityCheck();
317 
326 {
327 public:
328  ECC_Context();
329  ~ECC_Context();
330 };
331 
332 #endif // BITCOIN_KEY_H
void MakeKeyPairData()
Definition: key.h:304
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:170
unsigned char vchFingerprint[4]
Definition: pubkey.h:339
std::array< unsigned char, 32 > KeyType
see www.keylength.com script supports up to 75 for single byte push
Definition: key.h:53
void ClearKeyPairData()
Definition: key.h:309
std::array< unsigned char, 96 > KeyType
Definition: key.h:301
CKey key
Definition: key.h:236
CKey GenerateRandomKey(bool compressed=true) noexcept
Definition: key.cpp:475
RAII class initializing and deinitializing global state for elliptic curve support.
Definition: key.h:325
bool SignSchnorr(const uint256 &hash, std::span< unsigned char > sig, const uint256 &aux) const
Definition: key.cpp:549
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:237
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:183
Definition: key.h:231
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
unsigned char vchFingerprint[4]
Definition: key.h:233
MuSig2SecNonce encapsulates a secret nonce in use in a MuSig2 signing session.
Definition: musig.h:39
const std::byte * end() const
Definition: key.h:121
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:358
memcpy(result.begin(), stream.data(), stream.size())
static const unsigned int SIZE
secp256k1:
Definition: key.h:41
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey &their_ellswift, const EllSwiftPubKey &our_ellswift, bool initiating) const
Compute a BIP324-style ECDH shared secret.
Definition: key.cpp:328
void ClearKeyData()
Definition: key.h:69
std::unique_ptr< T, SecureUniqueDeleter< T > > secure_unique_ptr
Definition: secure.h:63
KeyPair.
Definition: key.h:271
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
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
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
static const unsigned int COMPRESSED_SIZE
Definition: key.h:42
KeyPair() noexcept=default
KeyPair ComputeKeyPair(const uint256 *merkle_root) const
Compute a KeyPair.
Definition: key.cpp:348
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:302
const std::byte * data() const
Definition: key.h:119
unsigned char nDepth
Definition: key.h:232
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:238
An encapsulated public key.
Definition: pubkey.h:33
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:162
unsigned int nChild
Definition: key.h:234
An ElligatorSwift-encoded public key.
Definition: pubkey.h:308
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:118
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:127
ChainCode chaincode
Definition: key.h:235
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:104
bool IsValid() const
Check whether this keypair is valid.
Definition: key.h:296
256-bit opaque blob.
Definition: uint256.h:195
std::array< std::byte, ECDH_SECRET_SIZE > ECDHSecret
Definition: key.h:30
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
static constexpr size_t ECDH_SECRET_SIZE
Size of ECDH shared secrets.
Definition: key.h:27
bool Derive(CKey &keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode &cc) const
Derive BIP32 child key.
Definition: key.cpp:293
CExtKey(const CExtPubKey &xpub, const CKey &key_in)
Definition: key.h:248
~ECC_Context()
Definition: key.cpp:604
const std::byte * begin() const
Definition: key.h:120
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:56
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:565
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
unsigned char * UCharCast(char *c)
Definition: span.h:95
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:158
An encapsulated private key.
Definition: key.h:35
KeyPair & operator=(const KeyPair &other)
Definition: key.h:277
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
std::vector< uint8_t > CreateMuSig2Nonce(MuSig2SecNonce &secnonce, const uint256 &sighash, const CPubKey &aggregate_pubkey, const std::vector< CPubKey > &pubkeys)
Definition: key.cpp:353
void MakeKeyData()
Definition: key.h:64
KeyPair(const KeyPair &other)
Definition: key.h:290
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:279
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:95
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:124
ECC_Context()
Definition: key.cpp:599