Line data Source code
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> 12 : #include <support/allocators/secure.h> 13 : #include <uint256.h> 14 : 15 : #include <stdexcept> 16 : #include <vector> 17 : 18 : 19 : /** 20 : * CPrivKey is a serialized private key, with all parameters included 21 : * (SIZE bytes) 22 : */ 23 : typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey; 24 : 25 : /** Size of ECDH shared secrets. */ 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 : /** An encapsulated private key. */ 32 : class CKey 33 : { 34 : public: 35 : /** 36 : * secp256k1: 37 : */ 38 : static const unsigned int SIZE = 279; 39 : static const unsigned int COMPRESSED_SIZE = 214; 40 : /** 41 : * see www.keylength.com 42 : * script supports up to 75 for single byte push 43 : */ 44 : static_assert( 45 : SIZE >= COMPRESSED_SIZE, 46 : "COMPRESSED_SIZE is larger than SIZE"); 47 : 48 : private: 49 : //! Whether this private key is valid. We check for correctness when modifying the key 50 : //! data, so fValid should always correspond to the actual state. 51 0 : bool fValid{false}; 52 : 53 : //! Whether the public key corresponding to this private key is (to be) compressed. 54 0 : bool fCompressed{false}; 55 : 56 : //! The actual byte data 57 : std::vector<unsigned char, secure_allocator<unsigned char> > keydata; 58 : 59 : //! Check whether the 32-byte array pointed to by vch is valid keydata. 60 : bool static Check(const unsigned char* vch); 61 : 62 : public: 63 : //! Construct an invalid private key. 64 0 : CKey() 65 : { 66 : // Important: vch must be 32 bytes in length to not break serialization 67 0 : keydata.resize(32); 68 0 : } 69 : 70 0 : friend bool operator==(const CKey& a, const CKey& b) 71 : { 72 0 : return a.fCompressed == b.fCompressed && 73 0 : a.size() == b.size() && 74 0 : memcmp(a.keydata.data(), b.keydata.data(), a.size()) == 0; 75 : } 76 : 77 : //! Initialize using begin and end iterators to byte data. 78 : template <typename T> 79 0 : void Set(const T pbegin, const T pend, bool fCompressedIn) 80 : { 81 0 : if (size_t(pend - pbegin) != keydata.size()) { 82 0 : fValid = false; 83 0 : } else if (Check(&pbegin[0])) { 84 0 : memcpy(keydata.data(), (unsigned char*)&pbegin[0], keydata.size()); 85 0 : fValid = true; 86 0 : fCompressed = fCompressedIn; 87 0 : } else { 88 0 : fValid = false; 89 : } 90 0 : } 91 : 92 : //! Simple read-only vector-like interface. 93 0 : unsigned int size() const { return (fValid ? keydata.size() : 0); } 94 0 : const std::byte* data() const { return reinterpret_cast<const std::byte*>(keydata.data()); } 95 0 : const unsigned char* begin() const { return keydata.data(); } 96 0 : const unsigned char* end() const { return keydata.data() + size(); } 97 : 98 : //! Check whether this private key is valid. 99 0 : bool IsValid() const { return fValid; } 100 : 101 : //! Check whether the public key corresponding to this private key is (to be) compressed. 102 0 : bool IsCompressed() const { return fCompressed; } 103 : 104 : //! Generate a new private key using a cryptographic PRNG. 105 : void MakeNewKey(bool fCompressed); 106 : 107 : //! Negate private key 108 : bool Negate(); 109 : 110 : /** 111 : * Convert the private key to a CPrivKey (serialized OpenSSL private key data). 112 : * This is expensive. 113 : */ 114 : CPrivKey GetPrivKey() const; 115 : 116 : /** 117 : * Compute the public key from a private key. 118 : * This is expensive. 119 : */ 120 : CPubKey GetPubKey() const; 121 : 122 : /** 123 : * Create a DER-serialized signature. 124 : * The test_case parameter tweaks the deterministic nonce. 125 : */ 126 : bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool grind = true, uint32_t test_case = 0) const; 127 : 128 : /** 129 : * Create a compact signature (65 bytes), which allows reconstructing the used public key. 130 : * The format is one header byte, followed by two times 32 bytes for the serialized r and s values. 131 : * The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, 132 : * 0x1D = second key with even y, 0x1E = second key with odd y, 133 : * add 0x04 for compressed keys. 134 : */ 135 : bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const; 136 : 137 : /** 138 : * Create a BIP-340 Schnorr signature, for the xonly-pubkey corresponding to *this, 139 : * optionally tweaked by *merkle_root. Additional nonce entropy is provided through 140 : * aux. 141 : * 142 : * merkle_root is used to optionally perform tweaking of the private key, as specified 143 : * in BIP341: 144 : * - If merkle_root == nullptr: no tweaking is done, sign with key directly (this is 145 : * used for signatures in BIP342 script). 146 : * - If merkle_root->IsNull(): sign with key + H_TapTweak(pubkey) (this is used for 147 : * key path spending when no scripts are present). 148 : * - Otherwise: sign with key + H_TapTweak(pubkey || *merkle_root) 149 : * (this is used for key path spending, with specific 150 : * Merkle root of the script tree). 151 : */ 152 : bool SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const; 153 : 154 : //! Derive BIP32 child key. 155 : [[nodiscard]] bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const; 156 : 157 : /** 158 : * Verify thoroughly whether a private key and a public key match. 159 : * This is done using a different mechanism than just regenerating it. 160 : */ 161 : bool VerifyPubKey(const CPubKey& vchPubKey) const; 162 : 163 : //! Load private key and check that public key matches. 164 : bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck); 165 : 166 : /** Create an ellswift-encoded public key for this key, with specified entropy. 167 : * 168 : * entropy must be a 32-byte span with additional entropy to use in the encoding. Every 169 : * public key has ~2^256 different encodings, and this function will deterministically pick 170 : * one of them, based on entropy. Note that even without truly random entropy, the 171 : * resulting encoding will be indistinguishable from uniform to any adversary who does not 172 : * know the private key (because the private key itself is always used as entropy as well). 173 : */ 174 : EllSwiftPubKey EllSwiftCreate(Span<const std::byte> entropy) const; 175 : 176 : /** Compute a BIP324-style ECDH shared secret. 177 : * 178 : * - their_ellswift: EllSwiftPubKey that was received from the other side. 179 : * - our_ellswift: EllSwiftPubKey that was sent to the other side (must have been generated 180 : * from *this using EllSwiftCreate()). 181 : * - initiating: whether we are the initiating party (true) or responding party (false). 182 : */ 183 : ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, 184 : const EllSwiftPubKey& our_ellswift, 185 : bool initiating) const; 186 : }; 187 : 188 : struct CExtKey { 189 : unsigned char nDepth; 190 : unsigned char vchFingerprint[4]; 191 : unsigned int nChild; 192 : ChainCode chaincode; 193 : CKey key; 194 : 195 0 : friend bool operator==(const CExtKey& a, const CExtKey& b) 196 : { 197 0 : return a.nDepth == b.nDepth && 198 0 : memcmp(a.vchFingerprint, b.vchFingerprint, sizeof(vchFingerprint)) == 0 && 199 0 : a.nChild == b.nChild && 200 0 : a.chaincode == b.chaincode && 201 0 : a.key == b.key; 202 : } 203 : 204 : void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const; 205 : void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]); 206 : [[nodiscard]] bool Derive(CExtKey& out, unsigned int nChild) const; 207 : CExtPubKey Neuter() const; 208 : void SetSeed(Span<const std::byte> seed); 209 : }; 210 : 211 : /** Initialize the elliptic curve support. May not be called twice without calling ECC_Stop first. */ 212 : void ECC_Start(); 213 : 214 : /** Deinitialize the elliptic curve support. No-op if ECC_Start wasn't called first. */ 215 : void ECC_Stop(); 216 : 217 : /** Check that required EC support is available at runtime. */ 218 : bool ECC_InitSanityCheck(); 219 : 220 : #endif // BITCOIN_KEY_H