Compact signatures and key recovery
[novacoin.git] / src / key.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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 int static inline EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
43 {
44     int ok = 0;
45     BN_CTX *ctx = NULL;
46     EC_POINT *pub_key = NULL;
47
48     if (!eckey) return 0;
49
50     const EC_GROUP *group = EC_KEY_get0_group(eckey);
51
52     if ((ctx = BN_CTX_new()) == NULL)
53         goto err;
54
55     pub_key = EC_POINT_new(group);
56
57     if (pub_key == NULL)
58         goto err;
59
60     if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
61         goto err;
62
63     EC_KEY_set_private_key(eckey,priv_key);
64     EC_KEY_set_public_key(eckey,pub_key);
65
66     ok = 1;
67
68 err:
69
70     if (pub_key)
71         EC_POINT_free(pub_key);
72     if (ctx != NULL)
73         BN_CTX_free(ctx);
74
75     return(ok);
76 }
77
78 int static inline ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
79 {
80     if (!eckey) return 0;
81
82     int ret = 0;
83     BN_CTX *ctx = NULL;
84
85     BIGNUM *x = NULL;
86     BIGNUM *e = NULL;
87     BIGNUM *order = NULL;
88     BIGNUM *sor = NULL;
89     BIGNUM *eor = NULL;
90     BIGNUM *field = NULL;
91     EC_POINT *R = NULL;
92     EC_POINT *O = NULL;
93     EC_POINT *Q = NULL;
94     BIGNUM *rr = NULL;
95     BIGNUM *zero = NULL;
96     int n = 0;
97     int i = recid / 2;
98
99     const EC_GROUP *group = EC_KEY_get0_group(eckey);
100     if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
101     BN_CTX_start(ctx);
102     order = BN_CTX_get(ctx);
103     if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
104     x = BN_CTX_get(ctx);
105     if (!BN_copy(x, order)) { ret=-1; goto err; }
106     if (!BN_mul_word(x, i)) { ret=-1; goto err; }
107     if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
108     field = BN_CTX_get(ctx);
109     if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
110     if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
111     if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
112     if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
113     if (check)
114     {
115         if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
116         if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
117         if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
118     }
119     if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
120     n = EC_GROUP_get_degree(group);
121     e = BN_CTX_get(ctx);
122     if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
123     if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
124     zero = BN_CTX_get(ctx);
125     if (!BN_zero(zero)) { ret=-1; goto err; }
126     if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
127     rr = BN_CTX_get(ctx);
128     if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
129     sor = BN_CTX_get(ctx);
130     if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
131     eor = BN_CTX_get(ctx);
132     if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
133     if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
134     if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
135
136     ret = 1;
137
138 err:
139     if (ctx) {
140         BN_CTX_end(ctx);
141         BN_CTX_free(ctx);
142     }
143     if (R != NULL) EC_POINT_free(R);
144     if (O != NULL) EC_POINT_free(O);
145     if (Q != NULL) EC_POINT_free(Q);
146     return ret;
147 }
148
149 class key_error : public std::runtime_error
150 {
151 public:
152     explicit key_error(const std::string& str) : std::runtime_error(str) {}
153 };
154
155
156 // secure_allocator is defined in serialize.h
157 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
158 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
159
160 class CKey
161 {
162 protected:
163     EC_KEY* pkey;
164     bool fSet;
165
166 public:
167     CKey()
168     {
169         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
170         if (pkey == NULL)
171             throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
172         fSet = false;
173     }
174
175     CKey(const CKey& b)
176     {
177         pkey = EC_KEY_dup(b.pkey);
178         if (pkey == NULL)
179             throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
180         fSet = b.fSet;
181     }
182
183     CKey& operator=(const CKey& b)
184     {
185         if (!EC_KEY_copy(pkey, b.pkey))
186             throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
187         fSet = b.fSet;
188         return (*this);
189     }
190
191     ~CKey()
192     {
193         EC_KEY_free(pkey);
194     }
195
196     bool IsNull() const
197     {
198         return !fSet;
199     }
200
201     void MakeNewKey()
202     {
203         if (!EC_KEY_generate_key(pkey))
204             throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
205         fSet = true;
206     }
207
208     bool SetPrivKey(const CPrivKey& vchPrivKey)
209     {
210         const unsigned char* pbegin = &vchPrivKey[0];
211         if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
212             return false;
213         fSet = true;
214         return true;
215     }
216
217     bool SetSecret(const CSecret& vchSecret)
218     {
219         EC_KEY_free(pkey);
220         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
221         if (pkey == NULL)
222             throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
223         if (vchSecret.size() != 32)
224             throw key_error("CKey::SetSecret() : secret must be 32 bytes");
225         BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
226         if (bn == NULL) 
227             throw key_error("CKey::SetSecret() : BN_bin2bn failed");
228         if (!EC_KEY_regenerate_key(pkey,bn))
229             throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
230         BN_clear_free(bn);
231         fSet = true;
232         return true;
233     }
234
235     CSecret GetSecret() const
236     {
237         CSecret vchRet;
238         vchRet.resize(32);
239         const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
240         int nBytes = BN_num_bytes(bn);
241         if (bn == NULL)
242             throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
243         int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
244         if (n != nBytes) 
245             throw key_error("CKey::GetSecret(): BN_bn2bin failed");
246         return vchRet;
247     }
248
249     CPrivKey GetPrivKey() const
250     {
251         unsigned int nSize = i2d_ECPrivateKey(pkey, NULL);
252         if (!nSize)
253             throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
254         CPrivKey vchPrivKey(nSize, 0);
255         unsigned char* pbegin = &vchPrivKey[0];
256         if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
257             throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
258         return vchPrivKey;
259     }
260
261     bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
262     {
263         const unsigned char* pbegin = &vchPubKey[0];
264         if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
265             return false;
266         fSet = true;
267         return true;
268     }
269
270     std::vector<unsigned char> GetPubKey() const
271     {
272         unsigned int nSize = i2o_ECPublicKey(pkey, NULL);
273         if (!nSize)
274             throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
275         std::vector<unsigned char> vchPubKey(nSize, 0);
276         unsigned char* pbegin = &vchPubKey[0];
277         if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
278             throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
279         return vchPubKey;
280     }
281
282     bool Sign(uint256 hash, std::vector<unsigned char>& vchSig)
283     {
284         vchSig.clear();
285         unsigned char pchSig[10000];
286         unsigned int nSize = 0;
287         if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), pchSig, &nSize, pkey))
288             return false;
289         vchSig.resize(nSize);
290         memcpy(&vchSig[0], pchSig, nSize);
291         return true;
292     }
293
294     // create a compact signature (65 bytes), which allows reconstructing the used public key
295     bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
296     {
297         bool fOk = false;
298         ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
299         if (sig==NULL)
300             return false;
301         vchSig.clear();
302         vchSig.resize(65,0);
303         int nBitsR = BN_num_bits(sig->r);
304         int nBitsS = BN_num_bits(sig->s);
305         if (nBitsR <= 256 && nBitsS <= 256)
306         {
307             int nRecId = -1;
308             for (int i=0; i<4; i++)
309             {
310                 CKey keyRec;
311                 keyRec.fSet = true;
312                 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
313                     if (keyRec.GetPubKey() == this->GetPubKey())
314                     {
315                         nRecId = i;
316                         break;
317                     }
318             }
319
320             if (nRecId == -1)
321                 throw key_error("CKEy::SignCompact() : unable to construct recoverable key");
322
323             vchSig[0] = nRecId+27;
324             BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
325             BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
326             fOk = true;
327         }
328         ECDSA_SIG_free(sig);
329         return fOk;
330     }
331
332     // reconstruct public key from a compact signature
333     bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
334     {
335         if (vchSig.size() != 65)
336             return false;
337         if (vchSig[0]<27 || vchSig[0]>=31)
338             return false;
339         ECDSA_SIG *sig = ECDSA_SIG_new();
340         BN_bin2bn(&vchSig[1],32,sig->r);
341         BN_bin2bn(&vchSig[33],32,sig->s);
342
343         EC_KEY_free(pkey);
344         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
345         if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), vchSig[0] - 27, 0) == 1)
346         {
347             fSet = true;
348             ECDSA_SIG_free(sig);
349             return true;
350         }
351         return false;
352     }
353
354     bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
355     {
356         // -1 = error, 0 = bad sig, 1 = good
357         if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
358             return false;
359         return true;
360     }
361
362     bool 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         return true;
370     }
371
372     CBitcoinAddress GetAddress() const
373     {
374         return CBitcoinAddress(GetPubKey());
375     }
376 };
377
378 #endif