Update CMakeLists.txt - play with openssl
[novacoin.git] / src / key.h
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.
5 #ifndef BITCOIN_KEY_H
6 #define BITCOIN_KEY_H
7
8 #include <stdexcept>
9 #include <vector>
10
11 #include "allocators.h"
12 #include "serialize.h"
13 #include "uint256.h"
14 #include "bignum.h"
15
16 #include <openssl/ec.h> // for EC_KEY definition
17 #include <openssl/obj_mac.h>
18
19
20 // secp160k1
21 // const unsigned int PRIVATE_KEY_SIZE = 192;
22 // const unsigned int PUBLIC_KEY_SIZE  = 41;
23 // const unsigned int SIGNATURE_SIZE   = 48;
24 //
25 // secp192k1
26 // const unsigned int PRIVATE_KEY_SIZE = 222;
27 // const unsigned int PUBLIC_KEY_SIZE  = 49;
28 // const unsigned int SIGNATURE_SIZE   = 57;
29 //
30 // secp224k1
31 // const unsigned int PRIVATE_KEY_SIZE = 250;
32 // const unsigned int PUBLIC_KEY_SIZE  = 57;
33 // const unsigned int SIGNATURE_SIZE   = 66;
34 //
35 // secp256k1:
36 // const unsigned int PRIVATE_KEY_SIZE = 279;
37 // const unsigned int PUBLIC_KEY_SIZE  = 65;
38 // const unsigned int SIGNATURE_SIZE   = 72;
39 //
40 // see www.keylength.com
41 // script supports up to 75 for single byte push
42
43 class key_error : public std::runtime_error
44 {
45 public:
46     explicit key_error(const std::string& str) : std::runtime_error(str) {}
47 };
48
49 /** A reference to a CKey: the Hash160 of its serialized public key */
50 class CKeyID : public uint160
51 {
52 public:
53     CKeyID();
54     CKeyID(const uint160 &in);
55 };
56
57 /** A reference to a CScript: the Hash160 of its serialization (see script.h) */
58 class CScriptID : public uint160
59 {
60 public:
61     CScriptID();
62     CScriptID(const uint160 &in);
63 };
64
65 /** An encapsulated OpenSSL Elliptic Curve key (public) */
66 class CPubKey
67 {
68 private:
69
70     /**
71      * Just store the serialized data.
72      * Its length can very cheaply be computed from the first byte.
73      */
74     unsigned char vbytes[65];
75
76     //! Compute the length of a pubkey with a given first byte.
77     unsigned int static GetLen(unsigned char chHeader)
78     {
79         if (chHeader == 2 || chHeader == 3)
80             return 33;
81         if (chHeader == 4 || chHeader == 6 || chHeader == 7)
82             return 65;
83         return 0;
84     }
85
86     // Set this key data to be invalid
87     void Invalidate()
88     {
89         vbytes[0] = 0xFF;
90     }
91
92 public:
93     // Construct an invalid public key.
94     CPubKey()
95     {
96         Invalidate();
97     }
98
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)
102     {
103         int len = pend == pbegin ? 0 : GetLen(pbegin[0]);
104         if (len && len == (pend - pbegin))
105             memcpy(vbytes, (unsigned char*)&pbegin[0], len);
106         else
107             Invalidate();
108     }
109
110     void Set(const std::vector<unsigned char>& vch)
111     {
112         Set(vch.begin(), vch.end());
113     }
114
115     template <typename T>
116     CPubKey(const T pbegin, const T pend)
117     {
118         Set(pbegin, pend);
119     }
120
121     CPubKey(const std::vector<unsigned char>& vch)
122     {
123         Set(vch.begin(), vch.end());
124     }
125
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]; }
131
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); }
135
136     //! Implement serialization, as if this was a byte vector.
137     unsigned int GetSerializeSize(int nType, int nVersion) const
138     {
139         return size() + 1;
140     }
141     template <typename Stream>
142     void Serialize(Stream& s, int nType, int nVersion) const
143     {
144         unsigned int len = size();
145         ::WriteCompactSize(s, len);
146         s.write((char*)vbytes, len);
147     }
148     template <typename Stream>
149     void Unserialize(Stream& s, int nType, int nVersion)
150     {
151         unsigned int len = ::ReadCompactSize(s);
152         if (len <= 65) {
153             s.read((char*)vbytes, len);
154         } else {
155             // invalid pubkey, skip available data
156             char dummy;
157             while (len--)
158                 s.read(&dummy, 1);
159             Invalidate();
160         }
161     }
162
163     CKeyID GetID() const;
164     uint256 GetHash() const;
165
166     /*
167      * Check syntactic correctness.
168      *
169      * Note that this is consensus critical as CheckSig() calls it!
170      */
171     bool IsValid() const
172     {
173         return size() > 0;
174     }
175
176     //! fully validate whether this is a valid public key (more expensive than IsValid())
177     bool IsFullyValid() const
178     {
179         const unsigned char* pbegin = &vbytes[0];
180         EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
181         if (o2i_ECPublicKey(&pkey, &pbegin, size()))
182         {
183             EC_KEY_free(pkey);
184             return true;
185         }
186         return false;
187     }
188
189     //! Check whether this is a compressed public key.
190     bool IsCompressed() const
191     {
192         return size() == 33;
193     }
194
195     bool Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const;
196     bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig);
197
198     bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig);
199
200     // Reserialize to DER
201     static bool ReserealizeSignature(std::vector<unsigned char>& vchSig);
202 };
203
204 // secure_allocator is defined in allocators.h
205 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
206 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
207 // CSecret is a serialization of just the secret parameter (32 bytes)
208 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
209
210 /** An encapsulated OpenSSL Elliptic Curve key (private) */
211 class CKey
212 {
213 protected:
214     EC_KEY* pkey;
215     bool fSet;
216
217 public:
218
219     void Reset();
220
221     CKey();
222     CKey(const CKey& b);
223     CKey(const CSecret& b, bool fCompressed=true);
224
225     CKey& operator=(const CKey& b);
226
227     ~CKey();
228
229     bool IsNull() const;
230     bool IsCompressed() const;
231
232     void SetCompressedPubKey(bool fCompressed=true);
233     void MakeNewKey(bool fCompressed=true);
234     bool SetPrivKey(const CPrivKey& vchPrivKey);
235     bool SetSecret(const CSecret& vchSecret, bool fCompressed = true);
236     CSecret GetSecret(bool &fCompressed) const;
237     CSecret GetSecret() const;
238     CPrivKey GetPrivKey() const;
239     CPubKey GetPubKey() const;
240
241     bool Sign(uint256 hash, std::vector<unsigned char>& vchSig);
242
243     // create a compact signature (65 bytes), which allows reconstructing the used public key
244     // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
245     // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
246     //                  0x1D = second key with even y, 0x1E = second key with odd y
247     bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig);
248
249     bool IsValid();
250
251     // Check whether an element of a signature (r or s) is valid.
252     static bool CheckSignatureElement(const unsigned char *vch, int len, bool half);
253 };
254
255 class CPoint
256 {
257 private:
258     EC_POINT *point;
259     EC_GROUP* group;
260     BN_CTX* ctx;
261
262 public:
263     CPoint();
264     bool operator!=(const CPoint &a);
265     ~CPoint();
266
267     // Initialize from octets stream
268     bool setBytes(const std::vector<unsigned char> &vchBytes);
269
270     // Initialize from pubkey
271     bool setPubKey(const CPubKey &vchPubKey);
272
273     // Serialize to octets stream
274     bool getBytes(std::vector<unsigned char> &vchBytes);
275
276     // ECC multiplication by specified multiplier
277     bool ECMUL(const CBigNum &bnMultiplier);
278
279     // Calculate G*m + q
280     bool ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint);
281
282     bool IsInfinity() { return EC_POINT_is_at_infinity(group, point) != 0; }
283 };
284
285 class CMalleablePubKey
286 {
287 private:
288     CPubKey pubKeyL;
289     CPubKey pubKeyH;
290     friend class CMalleableKey;
291
292     static const unsigned char CURRENT_VERSION = 1;
293
294 public:
295     CMalleablePubKey() { }
296     CMalleablePubKey(const CMalleablePubKey& mpk)
297     {
298         pubKeyL = mpk.pubKeyL;
299         pubKeyH = mpk.pubKeyH;
300     }
301     CMalleablePubKey(const std::vector<unsigned char> &vchPubKeyPair) { setvch(vchPubKeyPair); }
302     CMalleablePubKey(const std::string& strMalleablePubKey) { SetString(strMalleablePubKey); }
303     CMalleablePubKey(const CPubKey &pubKeyInL, const CPubKey &pubKeyInH) : pubKeyL(pubKeyInL), pubKeyH(pubKeyInH) { }
304
305     IMPLEMENT_SERIALIZE(
306         READWRITE(pubKeyL);
307         READWRITE(pubKeyH);
308     )
309
310     bool IsValid() const {
311         return pubKeyL.IsValid() && pubKeyH.IsValid();
312     }
313
314     bool operator==(const CMalleablePubKey &b);
315     bool operator!=(const CMalleablePubKey &b) { return !(*this == b); }
316     CMalleablePubKey& operator=(const CMalleablePubKey& mpk) {
317         pubKeyL = mpk.pubKeyL;
318         pubKeyH = mpk.pubKeyH;
319         return *this;
320     }
321
322     std::string ToString() const;
323     bool SetString(const std::string& strMalleablePubKey);
324
325     CKeyID GetID() const {
326         return pubKeyL.GetID();
327     }
328
329     bool setvch(const std::vector<unsigned char> &vchPubKeyPair);
330     std::vector<unsigned char> Raw() const;
331
332     CPubKey& GetL() { return pubKeyL; }
333     CPubKey& GetH() { return pubKeyH; }
334     void GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant);
335 };
336
337 class CMalleableKey
338 {
339 private:
340     CSecret vchSecretL;
341     CSecret vchSecretH;
342
343     friend class CMalleableKeyView;
344
345 public:
346     CMalleableKey();
347     CMalleableKey(const CMalleableKey &b);
348     CMalleableKey(const CSecret &L, const CSecret &H);
349     ~CMalleableKey();
350
351     IMPLEMENT_SERIALIZE(
352         READWRITE(vchSecretL);
353         READWRITE(vchSecretH);
354     )
355
356     std::string ToString() const;
357     bool SetString(const std::string& strMalleablePubKey);
358     std::vector<unsigned char> Raw() const;
359     CMalleableKey& operator=(const CMalleableKey& mk) {
360         vchSecretL = mk.vchSecretL;
361         vchSecretH = mk.vchSecretH;
362         return *this;
363     }
364
365     void Reset();
366     void MakeNewKeys();
367     bool IsNull() const;
368     bool IsValid() const { return !IsNull() && GetMalleablePubKey().IsValid(); }
369     bool SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH);
370
371     CSecret GetSecretL() const { return vchSecretL; }
372     CSecret GetSecretH() const { return vchSecretH; }
373
374     CKeyID GetID() const {
375         return GetMalleablePubKey().GetID();
376     }
377     CMalleablePubKey GetMalleablePubKey() const;
378     bool CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const;
379     bool CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const;
380 };
381
382 class CMalleableKeyView
383 {
384 private:
385     CSecret vchSecretL;
386     CPubKey vchPubKeyH;
387
388 public:
389     CMalleableKeyView() { };
390     CMalleableKeyView(const CMalleableKey &b);
391     CMalleableKeyView(const std::string &strMalleableKey);
392
393     CMalleableKeyView(const CMalleableKeyView &b);
394     CMalleableKeyView& operator=(const CMalleableKey &b);
395     ~CMalleableKeyView();
396
397     IMPLEMENT_SERIALIZE(
398         READWRITE(vchSecretL);
399         READWRITE(vchPubKeyH);
400     )
401
402     bool IsValid() const;
403     std::string ToString() const;
404     bool SetString(const std::string& strMalleablePubKey);
405     std::vector<unsigned char> Raw() const;
406     CMalleableKeyView& operator=(const CMalleableKeyView& mkv) {
407         vchSecretL = mkv.vchSecretL;
408         vchPubKeyH = mkv.vchPubKeyH;
409         return *this;
410     }
411
412     CKeyID GetID() const {
413         return GetMalleablePubKey().GetID();
414     }
415     CMalleablePubKey GetMalleablePubKey() const;
416     CMalleableKey GetMalleableKey(const CSecret &vchSecretH) const { return CMalleableKey(vchSecretL, vchSecretH); }
417     bool CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const;
418
419     bool operator <(const CMalleableKeyView& kv) const;
420 };
421
422 #endif