Merge branch '0.4.x' into 0.5.x
[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 license.txt 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 <openssl/ec.h>
12 #include <openssl/ecdsa.h>
13 #include <openssl/obj_mac.h>
14
15 #include "serialize.h"
16 #include "uint256.h"
17 #include "base58.h"
18
19 // secp160k1
20 // const unsigned int PRIVATE_KEY_SIZE = 192;
21 // const unsigned int PUBLIC_KEY_SIZE  = 41;
22 // const unsigned int SIGNATURE_SIZE   = 48;
23 //
24 // secp192k1
25 // const unsigned int PRIVATE_KEY_SIZE = 222;
26 // const unsigned int PUBLIC_KEY_SIZE  = 49;
27 // const unsigned int SIGNATURE_SIZE   = 57;
28 //
29 // secp224k1
30 // const unsigned int PRIVATE_KEY_SIZE = 250;
31 // const unsigned int PUBLIC_KEY_SIZE  = 57;
32 // const unsigned int SIGNATURE_SIZE   = 66;
33 //
34 // secp256k1:
35 // const unsigned int PRIVATE_KEY_SIZE = 279;
36 // const unsigned int PUBLIC_KEY_SIZE  = 65;
37 // const unsigned int SIGNATURE_SIZE   = 72;
38 //
39 // see www.keylength.com
40 // script supports up to 75 for single byte push
41
42 // Generate a private key from just the secret parameter
43 int static inline EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
44 {
45     int ok = 0;
46     BN_CTX *ctx = NULL;
47     EC_POINT *pub_key = NULL;
48
49     if (!eckey) return 0;
50
51     const EC_GROUP *group = EC_KEY_get0_group(eckey);
52
53     if ((ctx = BN_CTX_new()) == NULL)
54         goto err;
55
56     pub_key = EC_POINT_new(group);
57
58     if (pub_key == NULL)
59         goto err;
60
61     if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
62         goto err;
63
64     EC_KEY_set_private_key(eckey,priv_key);
65     EC_KEY_set_public_key(eckey,pub_key);
66
67     ok = 1;
68
69 err:
70
71     if (pub_key)
72         EC_POINT_free(pub_key);
73     if (ctx != NULL)
74         BN_CTX_free(ctx);
75
76     return(ok);
77 }
78
79 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
80 // recid selects which key is recovered
81 // if check is nonzero, additional checks are performed
82 int static inline ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
83 {
84     if (!eckey) return 0;
85
86     int ret = 0;
87     BN_CTX *ctx = NULL;
88
89     BIGNUM *x = NULL;
90     BIGNUM *e = NULL;
91     BIGNUM *order = NULL;
92     BIGNUM *sor = NULL;
93     BIGNUM *eor = NULL;
94     BIGNUM *field = NULL;
95     EC_POINT *R = NULL;
96     EC_POINT *O = NULL;
97     EC_POINT *Q = NULL;
98     BIGNUM *rr = NULL;
99     BIGNUM *zero = NULL;
100     int n = 0;
101     int i = recid / 2;
102
103     const EC_GROUP *group = EC_KEY_get0_group(eckey);
104     if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
105     BN_CTX_start(ctx);
106     order = BN_CTX_get(ctx);
107     if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
108     x = BN_CTX_get(ctx);
109     if (!BN_copy(x, order)) { ret=-1; goto err; }
110     if (!BN_mul_word(x, i)) { ret=-1; goto err; }
111     if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
112     field = BN_CTX_get(ctx);
113     if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
114     if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
115     if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
116     if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
117     if (check)
118     {
119         if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
120         if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
121         if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
122     }
123     if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
124     n = EC_GROUP_get_degree(group);
125     e = BN_CTX_get(ctx);
126     if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
127     if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
128     zero = BN_CTX_get(ctx);
129     if (!BN_zero(zero)) { ret=-1; goto err; }
130     if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
131     rr = BN_CTX_get(ctx);
132     if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
133     sor = BN_CTX_get(ctx);
134     if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
135     eor = BN_CTX_get(ctx);
136     if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
137     if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
138     if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
139
140     ret = 1;
141
142 err:
143     if (ctx) {
144         BN_CTX_end(ctx);
145         BN_CTX_free(ctx);
146     }
147     if (R != NULL) EC_POINT_free(R);
148     if (O != NULL) EC_POINT_free(O);
149     if (Q != NULL) EC_POINT_free(Q);
150     return ret;
151 }
152
153 class key_error : public std::runtime_error
154 {
155 public:
156     explicit key_error(const std::string& str) : std::runtime_error(str) {}
157 };
158
159
160 // secure_allocator is defined in serialize.h
161 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
162 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
163 // CSecret is a serialization of just the secret parameter (32 bytes)
164 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
165
166 class CKey
167 {
168 protected:
169     EC_KEY* pkey;
170     bool fSet;
171
172     void SetCompressedPubKey()
173     {
174         EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
175     }
176
177 public:
178     CKey()
179     {
180         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
181         if (pkey == NULL)
182             throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
183         fSet = false;
184     }
185
186     CKey(const CKey& b)
187     {
188         pkey = EC_KEY_dup(b.pkey);
189         if (pkey == NULL)
190             throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
191         fSet = b.fSet;
192     }
193
194     CKey& operator=(const CKey& b)
195     {
196         if (!EC_KEY_copy(pkey, b.pkey))
197             throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
198         fSet = b.fSet;
199         return (*this);
200     }
201
202     ~CKey()
203     {
204         EC_KEY_free(pkey);
205     }
206
207     bool IsNull() const
208     {
209         return !fSet;
210     }
211
212     void MakeNewKey()
213     {
214         if (!EC_KEY_generate_key(pkey))
215             throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
216         fSet = true;
217     }
218
219     bool SetPrivKey(const CPrivKey& vchPrivKey)
220     {
221         const unsigned char* pbegin = &vchPrivKey[0];
222         if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
223             return false;
224         fSet = true;
225         return true;
226     }
227
228     bool SetSecret(const CSecret& vchSecret)
229     {
230         EC_KEY_free(pkey);
231         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
232         if (pkey == NULL)
233             throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
234         if (vchSecret.size() != 32)
235             throw key_error("CKey::SetSecret() : secret must be 32 bytes");
236         BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
237         if (bn == NULL)
238             throw key_error("CKey::SetSecret() : BN_bin2bn failed");
239         if (!EC_KEY_regenerate_key(pkey,bn))
240         {
241             BN_clear_free(bn);
242             throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
243         }
244         BN_clear_free(bn);
245         fSet = true;
246         return true;
247     }
248
249     CSecret GetSecret() const
250     {
251         CSecret vchRet;
252         vchRet.resize(32);
253         const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
254         int nBytes = BN_num_bytes(bn);
255         if (bn == NULL)
256             throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
257         int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
258         if (n != nBytes) 
259             throw key_error("CKey::GetSecret(): BN_bn2bin failed");
260         return vchRet;
261     }
262
263     CPrivKey GetPrivKey() const
264     {
265         int nSize = i2d_ECPrivateKey(pkey, NULL);
266         if (!nSize)
267             throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
268         CPrivKey vchPrivKey(nSize, 0);
269         unsigned char* pbegin = &vchPrivKey[0];
270         if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
271             throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
272         return vchPrivKey;
273     }
274
275     bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
276     {
277         const unsigned char* pbegin = &vchPubKey[0];
278         if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
279             return false;
280         fSet = true;
281         return true;
282     }
283
284     std::vector<unsigned char> GetPubKey() const
285     {
286         int nSize = i2o_ECPublicKey(pkey, NULL);
287         if (!nSize)
288             throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
289         std::vector<unsigned char> vchPubKey(nSize, 0);
290         unsigned char* pbegin = &vchPubKey[0];
291         if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
292             throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
293         return vchPubKey;
294     }
295
296     bool Sign(uint256 hash, std::vector<unsigned char>& vchSig)
297     {
298         unsigned int nSize = ECDSA_size(pkey);
299         vchSig.resize(nSize); // Make sure it is big enough
300         if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
301         {
302             vchSig.clear();
303             return false;
304         }
305         vchSig.resize(nSize); // Shrink to fit actual size
306         return true;
307     }
308
309     // create a compact signature (65 bytes), which allows reconstructing the used public key
310     // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
311     // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
312     //                  0x1D = second key with even y, 0x1E = second key with odd y
313     bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
314     {
315         bool fOk = false;
316         ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
317         if (sig==NULL)
318             return false;
319         vchSig.clear();
320         vchSig.resize(65,0);
321         int nBitsR = BN_num_bits(sig->r);
322         int nBitsS = BN_num_bits(sig->s);
323         if (nBitsR <= 256 && nBitsS <= 256)
324         {
325             int nRecId = -1;
326             for (int i=0; i<4; i++)
327             {
328                 CKey keyRec;
329                 keyRec.fSet = true;
330                 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
331                     if (keyRec.GetPubKey() == this->GetPubKey())
332                     {
333                         nRecId = i;
334                         break;
335                     }
336             }
337
338             if (nRecId == -1)
339                 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
340
341             vchSig[0] = nRecId+27;
342             BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
343             BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
344             fOk = true;
345         }
346         ECDSA_SIG_free(sig);
347         return fOk;
348     }
349
350     // reconstruct public key from a compact signature
351     // This is only slightly more CPU intensive than just verifying it.
352     // If this function succeeds, the recovered public key is guaranteed to be valid
353     // (the signature is a valid signature of the given data for that key)
354     bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
355     {
356         if (vchSig.size() != 65)
357             return false;
358         int nV = vchSig[0];
359         if (nV<27 || nV>=35)
360             return false;
361         ECDSA_SIG *sig = ECDSA_SIG_new();
362         BN_bin2bn(&vchSig[1],32,sig->r);
363         BN_bin2bn(&vchSig[33],32,sig->s);
364
365         EC_KEY_free(pkey);
366         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
367         if (nV >= 31)
368         {
369             SetCompressedPubKey();
370             nV -= 4;
371         }
372         if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
373         {
374             fSet = true;
375             ECDSA_SIG_free(sig);
376             return true;
377         }
378         return false;
379     }
380
381     bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
382     {
383         // -1 = error, 0 = bad sig, 1 = good
384         if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
385             return false;
386         return true;
387     }
388
389     // Verify a compact signature
390     bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
391     {
392         CKey key;
393         if (!key.SetCompactSignature(hash, vchSig))
394             return false;
395         if (GetPubKey() != key.GetPubKey())
396             return false;
397         return true;
398     }
399
400     // Get the address corresponding to this key
401     CBitcoinAddress GetAddress() const
402     {
403         return CBitcoinAddress(GetPubKey());
404     }
405
406     bool IsValid()
407     {
408         if (!fSet)
409             return false;
410
411         CSecret secret = GetSecret();
412         CKey key2;
413         key2.SetSecret(secret);
414         return GetPubKey() == key2.GetPubKey();
415     }
416 };
417
418 #endif