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