1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include "allocators.h"
11 #include "serialize.h"
19 * const unsigned int PRIVATE_KEY_SIZE = 279;
20 * const unsigned int PUBLIC_KEY_SIZE = 65;
21 * const unsigned int SIGNATURE_SIZE = 72;
23 * see www.keylength.com
24 * script supports up to 75 for single byte push
27 /** A reference to a CKey: the Hash160 of its serialized public key */
28 class CKeyID : public uint160
31 CKeyID() : uint160(0) {}
32 CKeyID(const uint160& in) : uint160(in) {}
35 /** An encapsulated public key. */
41 * Just store the serialized data.
42 * Its length can very cheaply be computed from the first byte.
44 unsigned char vch[65];
46 //! Compute the length of a pubkey with a given first byte.
47 unsigned int static GetLen(unsigned char chHeader)
49 if (chHeader == 2 || chHeader == 3)
51 if (chHeader == 4 || chHeader == 6 || chHeader == 7)
56 //! Set this key data to be invalid
63 //! Construct an invalid public key.
69 //! Initialize a public key using begin/end iterators to byte data.
71 void Set(const T pbegin, const T pend)
73 int len = pend == pbegin ? 0 : GetLen(pbegin[0]);
74 if (len && len == (pend - pbegin))
75 memcpy(vch, (unsigned char*)&pbegin[0], len);
80 //! Construct a public key using begin/end iterators to byte data.
82 CPubKey(const T pbegin, const T pend)
87 //! Construct a public key from a byte vector.
88 CPubKey(const std::vector<unsigned char>& vch)
90 Set(vch.begin(), vch.end());
93 //! Simple read-only vector-like interface to the pubkey data.
94 unsigned int size() const { return GetLen(vch[0]); }
95 const unsigned char* begin() const { return vch; }
96 const unsigned char* end() const { return vch + size(); }
97 const unsigned char& operator[](unsigned int pos) const { return vch[pos]; }
99 //! Comparator implementation.
100 friend bool operator==(const CPubKey& a, const CPubKey& b)
102 return a.vch[0] == b.vch[0] &&
103 memcmp(a.vch, b.vch, a.size()) == 0;
105 friend bool operator!=(const CPubKey& a, const CPubKey& b)
109 friend bool operator<(const CPubKey& a, const CPubKey& b)
111 return a.vch[0] < b.vch[0] ||
112 (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0);
115 //! Implement serialization, as if this was a byte vector.
116 unsigned int GetSerializeSize(int nType, int nVersion) const
120 template <typename Stream>
121 void Serialize(Stream& s, int nType, int nVersion) const
123 unsigned int len = size();
124 ::WriteCompactSize(s, len);
125 s.write((char*)vch, len);
127 template <typename Stream>
128 void Unserialize(Stream& s, int nType, int nVersion)
130 unsigned int len = ::ReadCompactSize(s);
132 s.read((char*)vch, len);
134 // invalid pubkey, skip available data
142 //! Get the KeyID of this public key (hash of its serialization)
145 return CKeyID(Hash160(vch, vch + size()));
148 //! Get the 256-bit hash of this public key.
149 uint256 GetHash() const
151 return Hash(vch, vch + size());
155 * Check syntactic correctness.
157 * Note that this is consensus critical as CheckSig() calls it!
164 //! fully validate whether this is a valid public key (more expensive than IsValid())
165 bool IsFullyValid() const;
167 //! Check whether this is a compressed public key.
168 bool IsCompressed() const
174 * Verify a DER signature (~72 bytes).
175 * If this public key is not fully valid, the return value will be false.
177 bool Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const;
179 //! Recover a public key from a compact signature.
180 bool RecoverCompact(const uint256& hash, const std::vector<unsigned char>& vchSig);
182 //! Turn this public key into an uncompressed public key.
185 //! Derive BIP32 child pubkey.
186 bool Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const;
191 * secure_allocator is defined in allocators.h
192 * CPrivKey is a serialized private key, with all parameters included (279 bytes)
194 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
196 /** An encapsulated private key. */
200 //! Whether this private key is valid. We check for correctness when modifying the key
201 //! data, so fValid should always correspond to the actual state.
204 //! Whether the public key corresponding to this private key is (to be) compressed.
207 //! The actual byte data
208 unsigned char vch[32];
210 //! Check whether the 32-byte array pointed to be vch is valid keydata.
211 bool static Check(const unsigned char* vch);
214 //! Construct an invalid private key.
215 CKey() : fValid(false), fCompressed(false)
220 //! Copy constructor. This is necessary because of memlocking.
221 CKey(const CKey& secret) : fValid(secret.fValid), fCompressed(secret.fCompressed)
224 memcpy(vch, secret.vch, sizeof(vch));
227 //! Destructor (again necessary because of memlocking).
233 friend bool operator==(const CKey& a, const CKey& b)
235 return a.fCompressed == b.fCompressed && a.size() == b.size() &&
236 memcmp(&a.vch[0], &b.vch[0], a.size()) == 0;
239 //! Initialize using begin and end iterators to byte data.
240 template <typename T>
241 void Set(const T pbegin, const T pend, bool fCompressedIn)
243 if (pend - pbegin != 32) {
247 if (Check(&pbegin[0])) {
248 memcpy(vch, (unsigned char*)&pbegin[0], 32);
250 fCompressed = fCompressedIn;
256 //! Simple read-only vector-like interface.
257 unsigned int size() const { return (fValid ? 32 : 0); }
258 const unsigned char* begin() const { return vch; }
259 const unsigned char* end() const { return vch + size(); }
261 //! Check whether this private key is valid.
262 bool IsValid() const { return fValid; }
264 //! Check whether the public key corresponding to this private key is (to be) compressed.
265 bool IsCompressed() const { return fCompressed; }
267 //! Initialize from a CPrivKey (serialized OpenSSL private key data).
268 bool SetPrivKey(const CPrivKey& vchPrivKey, bool fCompressed);
270 //! Generate a new private key using a cryptographic PRNG.
271 void MakeNewKey(bool fCompressed);
274 * Convert the private key to a CPrivKey (serialized OpenSSL private key data).
277 CPrivKey GetPrivKey() const;
280 * Compute the public key from a private key.
283 CPubKey GetPubKey() const;
285 //! Create a DER-serialized signature.
286 bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool lowS = true) const;
289 * Create a compact signature (65 bytes), which allows reconstructing the used public key.
290 * The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
291 * The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
292 * 0x1D = second key with even y, 0x1E = second key with odd y,
293 * add 0x04 for compressed keys.
295 bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
297 //! Derive BIP32 child key.
298 bool Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const;
300 //! Load private key and check that public key matches.
301 bool Load(CPrivKey& privkey, CPubKey& vchPubKey, bool fSkipCheck);
303 //! Check whether an element of a signature (r or s) is valid.
304 static bool CheckSignatureElement(const unsigned char* vch, int len, bool half);
308 unsigned char nDepth;
309 unsigned char vchFingerprint[4];
311 unsigned char vchChainCode[32];
314 friend bool operator==(const CExtPubKey& a, const CExtPubKey& b)
316 return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild &&
317 memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.pubkey == b.pubkey;
320 void Encode(unsigned char code[74]) const;
321 void Decode(const unsigned char code[74]);
322 bool Derive(CExtPubKey& out, unsigned int nChild) const;
326 unsigned char nDepth;
327 unsigned char vchFingerprint[4];
329 unsigned char vchChainCode[32];
332 friend bool operator==(const CExtKey& a, const CExtKey& b)
334 return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild &&
335 memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.key == b.key;
338 void Encode(unsigned char code[74]) const;
339 void Decode(const unsigned char code[74]);
340 bool Derive(CExtKey& out, unsigned int nChild) const;
341 CExtPubKey Neuter() const;
342 void SetMaster(const unsigned char* seed, unsigned int nSeedLen);
345 /** Check that required EC support is available at runtime */
346 bool ECC_InitSanityCheck(void);
348 #endif // BITCOIN_KEY_H