Update Bugreport Links
[bitcoinplatinum.git] / src / key.cpp
blob76c45d0635b5ec04c385e7570ee6c63f3b88f1da
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.
5 #include <map>
7 #include <openssl/ecdsa.h>
8 #include <openssl/obj_mac.h>
10 #include "key.h"
12 // Generate a private key from just the secret parameter
13 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
15 int ok = 0;
16 BN_CTX *ctx = NULL;
17 EC_POINT *pub_key = NULL;
19 if (!eckey) return 0;
21 const EC_GROUP *group = EC_KEY_get0_group(eckey);
23 if ((ctx = BN_CTX_new()) == NULL)
24 goto err;
26 pub_key = EC_POINT_new(group);
28 if (pub_key == NULL)
29 goto err;
31 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
32 goto err;
34 EC_KEY_set_private_key(eckey,priv_key);
35 EC_KEY_set_public_key(eckey,pub_key);
37 ok = 1;
39 err:
41 if (pub_key)
42 EC_POINT_free(pub_key);
43 if (ctx != NULL)
44 BN_CTX_free(ctx);
46 return(ok);
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)
54 if (!eckey) return 0;
56 int ret = 0;
57 BN_CTX *ctx = NULL;
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;
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)
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; }
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; }
110 ret = 1;
112 err:
113 if (ctx) {
114 BN_CTX_end(ctx);
115 BN_CTX_free(ctx);
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;
123 void CKey::SetCompressedPubKey()
125 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
126 fCompressedPubKey = true;
129 void CKey::Reset()
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;
140 CKey::CKey()
142 pkey = NULL;
143 Reset();
146 CKey::CKey(const CKey& b)
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;
154 CKey& CKey::operator=(const CKey& b)
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);
162 CKey::~CKey()
164 EC_KEY_free(pkey);
167 bool CKey::IsNull() const
169 return !fSet;
172 bool CKey::IsCompressed() const
174 return fCompressedPubKey;
177 void CKey::MakeNewKey(bool fCompressed)
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;
186 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
188 const unsigned char* pbegin = &vchPrivKey[0];
189 if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
190 return false;
191 fSet = true;
192 return true;
195 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
197 EC_KEY_free(pkey);
198 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
199 if (pkey == NULL)
200 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
201 if (vchSecret.size() != 32)
202 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
203 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
204 if (bn == NULL)
205 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
206 if (!EC_KEY_regenerate_key(pkey,bn))
208 BN_clear_free(bn);
209 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
211 BN_clear_free(bn);
212 fSet = true;
213 if (fCompressed || fCompressedPubKey)
214 SetCompressedPubKey();
215 return true;
218 CSecret CKey::GetSecret(bool &fCompressed) const
220 CSecret vchRet;
221 vchRet.resize(32);
222 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
223 int nBytes = BN_num_bytes(bn);
224 if (bn == NULL)
225 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
226 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
227 if (n != nBytes)
228 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
229 fCompressed = fCompressedPubKey;
230 return vchRet;
233 CPrivKey CKey::GetPrivKey() const
235 int nSize = i2d_ECPrivateKey(pkey, NULL);
236 if (!nSize)
237 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
238 CPrivKey vchPrivKey(nSize, 0);
239 unsigned char* pbegin = &vchPrivKey[0];
240 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
241 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
242 return vchPrivKey;
245 bool CKey::SetPubKey(const CPubKey& vchPubKey)
247 const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
248 if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
249 return false;
250 fSet = true;
251 if (vchPubKey.vchPubKey.size() == 33)
252 SetCompressedPubKey();
253 return true;
256 CPubKey CKey::GetPubKey() const
258 int nSize = i2o_ECPublicKey(pkey, NULL);
259 if (!nSize)
260 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
261 std::vector<unsigned char> vchPubKey(nSize, 0);
262 unsigned char* pbegin = &vchPubKey[0];
263 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
264 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
265 return CPubKey(vchPubKey);
268 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
270 unsigned int nSize = ECDSA_size(pkey);
271 vchSig.resize(nSize); // Make sure it is big enough
272 if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
274 vchSig.clear();
275 return false;
277 vchSig.resize(nSize); // Shrink to fit actual size
278 return true;
281 // create a compact signature (65 bytes), which allows reconstructing the used public key
282 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
283 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
284 // 0x1D = second key with even y, 0x1E = second key with odd y
285 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
287 bool fOk = false;
288 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
289 if (sig==NULL)
290 return false;
291 vchSig.clear();
292 vchSig.resize(65,0);
293 int nBitsR = BN_num_bits(sig->r);
294 int nBitsS = BN_num_bits(sig->s);
295 if (nBitsR <= 256 && nBitsS <= 256)
297 int nRecId = -1;
298 for (int i=0; i<4; i++)
300 CKey keyRec;
301 keyRec.fSet = true;
302 if (fCompressedPubKey)
303 keyRec.SetCompressedPubKey();
304 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
305 if (keyRec.GetPubKey() == this->GetPubKey())
307 nRecId = i;
308 break;
312 if (nRecId == -1)
313 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
315 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
316 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
317 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
318 fOk = true;
320 ECDSA_SIG_free(sig);
321 return fOk;
324 // reconstruct public key from a compact signature
325 // This is only slightly more CPU intensive than just verifying it.
326 // If this function succeeds, the recovered public key is guaranteed to be valid
327 // (the signature is a valid signature of the given data for that key)
328 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
330 if (vchSig.size() != 65)
331 return false;
332 int nV = vchSig[0];
333 if (nV<27 || nV>=35)
334 return false;
335 ECDSA_SIG *sig = ECDSA_SIG_new();
336 BN_bin2bn(&vchSig[1],32,sig->r);
337 BN_bin2bn(&vchSig[33],32,sig->s);
339 EC_KEY_free(pkey);
340 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
341 if (nV >= 31)
343 SetCompressedPubKey();
344 nV -= 4;
346 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
348 fSet = true;
349 ECDSA_SIG_free(sig);
350 return true;
352 return false;
355 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
357 // -1 = error, 0 = bad sig, 1 = good
358 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
359 return false;
361 return true;
364 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
366 CKey key;
367 if (!key.SetCompactSignature(hash, vchSig))
368 return false;
369 if (GetPubKey() != key.GetPubKey())
370 return false;
372 return true;
375 bool CKey::IsValid()
377 if (!fSet)
378 return false;
380 bool fCompr;
381 CSecret secret = GetSecret(fCompr);
382 CKey key2;
383 key2.SetSecret(secret, fCompr);
384 return GetPubKey() == key2.GetPubKey();