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