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