1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
11 #include "allocators.h"
12 #include "serialize.h"
17 #include <openssl/ec.h> // for EC_KEY definition
18 #include <openssl/obj_mac.h>
21 // const unsigned int PRIVATE_KEY_SIZE = 192;
22 // const unsigned int PUBLIC_KEY_SIZE = 41;
23 // const unsigned int SIGNATURE_SIZE = 48;
26 // const unsigned int PRIVATE_KEY_SIZE = 222;
27 // const unsigned int PUBLIC_KEY_SIZE = 49;
28 // const unsigned int SIGNATURE_SIZE = 57;
31 // const unsigned int PRIVATE_KEY_SIZE = 250;
32 // const unsigned int PUBLIC_KEY_SIZE = 57;
33 // const unsigned int SIGNATURE_SIZE = 66;
36 // const unsigned int PRIVATE_KEY_SIZE = 279;
37 // const unsigned int PUBLIC_KEY_SIZE = 65;
38 // const unsigned int SIGNATURE_SIZE = 72;
40 // see www.keylength.com
41 // script supports up to 75 for single byte push
43 class key_error : public std::runtime_error
46 explicit key_error(const std::string& str) : std::runtime_error(str) {}
49 /** A reference to a CKey: the Hash160 of its serialized public key */
50 class CKeyID : public uint160
53 CKeyID() : uint160(0) { }
54 CKeyID(const uint160 &in) : uint160(in) { }
57 /** A reference to a CScript: the Hash160 of its serialization (see script.h) */
58 class CScriptID : public uint160
61 CScriptID() : uint160(0) { }
62 CScriptID(const uint160 &in) : uint160(in) { }
65 /** An encapsulated OpenSSL Elliptic Curve key (public) */
71 * Just store the serialized data.
72 * Its length can very cheaply be computed from the first byte.
74 unsigned char vbytes[65];
76 //! Compute the length of a pubkey with a given first byte.
77 unsigned int static GetLen(unsigned char chHeader)
79 if (chHeader == 2 || chHeader == 3)
81 if (chHeader == 4 || chHeader == 6 || chHeader == 7)
86 // Set this key data to be invalid
93 // Construct an invalid public key.
99 // Initialize a public key using begin/end iterators to byte data.
100 template <typename T>
101 void Set(const T pbegin, const T pend)
103 int len = pend == pbegin ? 0 : GetLen(pbegin[0]);
104 if (len && len == (pend - pbegin))
105 memcpy(vbytes, (unsigned char*)&pbegin[0], len);
110 void Set(const std::vector<unsigned char>& vch)
112 Set(vch.begin(), vch.end());
115 template <typename T>
116 CPubKey(const T pbegin, const T pend)
121 CPubKey(const std::vector<unsigned char>& vch)
123 Set(vch.begin(), vch.end());
126 // Read-only vector-like interface to the data.
127 unsigned int size() const { return GetLen(vbytes[0]); }
128 const unsigned char* begin() const { return vbytes; }
129 const unsigned char* end() const { return vbytes + size(); }
130 const unsigned char& operator[](unsigned int pos) const { return vbytes[pos]; }
132 friend bool operator==(const CPubKey& a, const CPubKey& b) { return a.vbytes[0] == b.vbytes[0] && memcmp(a.vbytes, b.vbytes, a.size()) == 0; }
133 friend bool operator!=(const CPubKey& a, const CPubKey& b) { return !(a == b); }
134 friend bool operator<(const CPubKey& a, const CPubKey& b) { return a.vbytes[0] < b.vbytes[0] || (a.vbytes[0] == b.vbytes[0] && memcmp(a.vbytes, b.vbytes, a.size()) < 0); }
136 //! Implement serialization, as if this was a byte vector.
137 unsigned int GetSerializeSize(int nType, int nVersion) const
141 template <typename Stream>
142 void Serialize(Stream& s, int nType, int nVersion) const
144 unsigned int len = size();
145 ::WriteCompactSize(s, len);
146 s.write((char*)vbytes, len);
148 template <typename Stream>
149 void Unserialize(Stream& s, int nType, int nVersion)
151 unsigned int len = ::ReadCompactSize(s);
153 s.read((char*)vbytes, len);
155 // invalid pubkey, skip available data
165 return CKeyID(Hash160(vbytes, vbytes + size()));
168 uint256 GetHash() const
170 return Hash(vbytes, vbytes + size());
174 * Check syntactic correctness.
176 * Note that this is consensus critical as CheckSig() calls it!
183 //! fully validate whether this is a valid public key (more expensive than IsValid())
184 bool IsFullyValid() const
186 const unsigned char* pbegin = &vbytes[0];
187 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
188 if (o2i_ECPublicKey(&pkey, &pbegin, size()))
196 //! Check whether this is a compressed public key.
197 bool IsCompressed() const
202 bool Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const;
203 bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig);
205 bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig);
207 // Reserialize to DER
208 static bool ReserealizeSignature(std::vector<unsigned char>& vchSig);
211 // secure_allocator is defined in allocators.h
212 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
213 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
214 // CSecret is a serialization of just the secret parameter (32 bytes)
215 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
217 /** An encapsulated OpenSSL Elliptic Curve key (private) */
230 CKey(const CSecret& b, bool fCompressed=true);
232 CKey& operator=(const CKey& b);
237 bool IsCompressed() const;
239 void SetCompressedPubKey(bool fCompressed=true);
240 void MakeNewKey(bool fCompressed=true);
241 bool SetPrivKey(const CPrivKey& vchPrivKey);
242 bool SetSecret(const CSecret& vchSecret, bool fCompressed = true);
243 CSecret GetSecret(bool &fCompressed) const;
244 CSecret GetSecret() const;
245 CPrivKey GetPrivKey() const;
246 CPubKey GetPubKey() const;
248 bool Sign(uint256 hash, std::vector<unsigned char>& vchSig);
250 // create a compact signature (65 bytes), which allows reconstructing the used public key
251 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
252 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
253 // 0x1D = second key with even y, 0x1E = second key with odd y
254 bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig);
258 // Check whether an element of a signature (r or s) is valid.
259 static bool CheckSignatureElement(const unsigned char *vch, int len, bool half);
271 bool operator!=(const CPoint &a);
274 // Initialize from octets stream
275 bool setBytes(const std::vector<unsigned char> &vchBytes);
277 // Initialize from pubkey
278 bool setPubKey(const CPubKey &vchPubKey);
280 // Serialize to octets stream
281 bool getBytes(std::vector<unsigned char> &vchBytes);
283 // ECC multiplication by specified multiplier
284 bool ECMUL(const CBigNum &bnMultiplier);
287 bool ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint);
289 bool IsInfinity() { return EC_POINT_is_at_infinity(group, point) != 0; }
292 class CMalleablePubKey
297 friend class CMalleableKey;
299 static const unsigned char CURRENT_VERSION = 1;
302 CMalleablePubKey() { }
303 CMalleablePubKey(const CMalleablePubKey& mpk)
305 pubKeyL = mpk.pubKeyL;
306 pubKeyH = mpk.pubKeyH;
308 CMalleablePubKey(const std::vector<unsigned char> &vchPubKeyPair) { setvch(vchPubKeyPair); }
309 CMalleablePubKey(const std::string& strMalleablePubKey) { SetString(strMalleablePubKey); }
310 CMalleablePubKey(const CPubKey &pubKeyInL, const CPubKey &pubKeyInH) : pubKeyL(pubKeyInL), pubKeyH(pubKeyInH) { }
317 bool IsValid() const {
318 return pubKeyL.IsValid() && pubKeyH.IsValid();
321 bool operator==(const CMalleablePubKey &b);
322 bool operator!=(const CMalleablePubKey &b) { return !(*this == b); }
323 CMalleablePubKey& operator=(const CMalleablePubKey& mpk) {
324 pubKeyL = mpk.pubKeyL;
325 pubKeyH = mpk.pubKeyH;
329 std::string ToString() const;
330 bool SetString(const std::string& strMalleablePubKey);
332 CKeyID GetID() const {
333 return pubKeyL.GetID();
336 bool setvch(const std::vector<unsigned char> &vchPubKeyPair);
337 std::vector<unsigned char> Raw() const;
339 CPubKey& GetL() { return pubKeyL; }
340 CPubKey& GetH() { return pubKeyH; }
341 void GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant);
350 friend class CMalleableKeyView;
354 CMalleableKey(const CMalleableKey &b);
355 CMalleableKey(const CSecret &L, const CSecret &H);
359 READWRITE(vchSecretL);
360 READWRITE(vchSecretH);
363 std::string ToString() const;
364 bool SetString(const std::string& strMalleablePubKey);
365 std::vector<unsigned char> Raw() const;
366 CMalleableKey& operator=(const CMalleableKey& mk) {
367 vchSecretL = mk.vchSecretL;
368 vchSecretH = mk.vchSecretH;
375 bool IsValid() const { return !IsNull() && GetMalleablePubKey().IsValid(); }
376 bool SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH);
378 CSecret GetSecretL() const { return vchSecretL; }
379 CSecret GetSecretH() const { return vchSecretH; }
381 CKeyID GetID() const {
382 return GetMalleablePubKey().GetID();
384 CMalleablePubKey GetMalleablePubKey() const;
385 bool CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const;
386 bool CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const;
389 class CMalleableKeyView
396 CMalleableKeyView() { };
397 CMalleableKeyView(const CMalleableKey &b);
398 CMalleableKeyView(const std::string &strMalleableKey);
400 CMalleableKeyView(const CMalleableKeyView &b);
401 CMalleableKeyView& operator=(const CMalleableKey &b);
402 ~CMalleableKeyView();
405 READWRITE(vchSecretL);
406 READWRITE(vchPubKeyH);
409 bool IsValid() const;
410 std::string ToString() const;
411 bool SetString(const std::string& strMalleablePubKey);
412 std::vector<unsigned char> Raw() const;
413 CMalleableKeyView& operator=(const CMalleableKeyView& mkv) {
414 vchSecretL = mkv.vchSecretL;
415 vchPubKeyH = mkv.vchPubKeyH;
419 CKeyID GetID() const {
420 return GetMalleablePubKey().GetID();
422 CMalleablePubKey GetMalleablePubKey() const;
423 CMalleableKey GetMalleableKey(const CSecret &vchSecretH) const { return CMalleableKey(vchSecretL, vchSecretH); }
424 bool CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const;
426 bool operator <(const CMalleableKeyView& kv) const { return vchPubKeyH.GetID() < kv.vchPubKeyH.GetID(); }