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