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.
7 #include <boost/tuple/tuple.hpp>
8 #include <openssl/ecdsa.h>
9 #include <openssl/obj_mac.h>
14 // Generate a private key from just the secret parameter
15 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
19 EC_POINT *pub_key = NULL;
23 const EC_GROUP *group = EC_KEY_get0_group(eckey);
25 if ((ctx = BN_CTX_new()) == NULL)
28 pub_key = EC_POINT_new(group);
33 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
36 EC_KEY_set_private_key(eckey,priv_key);
37 EC_KEY_set_public_key(eckey,pub_key);
44 EC_POINT_free(pub_key);
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)
75 const EC_GROUP *group = EC_KEY_get0_group(eckey);
76 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
78 order = BN_CTX_get(ctx);
79 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
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; }
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; }
95 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
96 n = EC_GROUP_get_degree(group);
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; }
119 if (R != NULL) EC_POINT_free(R);
120 if (O != NULL) EC_POINT_free(O);
121 if (Q != NULL) EC_POINT_free(Q);
125 void CKey::SetCompressedPubKey()
127 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
128 fCompressedPubKey = true;
133 fCompressedPubKey = false;
134 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
136 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
145 CKey::CKey(const CKey& b)
147 pkey = EC_KEY_dup(b.pkey);
149 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
153 CKey& CKey::operator=(const CKey& b)
155 if (!EC_KEY_copy(pkey, b.pkey))
156 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
166 bool CKey::IsNull() const
171 bool CKey::IsCompressed() const
173 return fCompressedPubKey;
176 void CKey::MakeNewKey(bool fCompressed)
178 if (!EC_KEY_generate_key(pkey))
179 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
181 SetCompressedPubKey();
185 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
187 const unsigned char* pbegin = &vchPrivKey[0];
188 if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
194 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
197 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
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());
204 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
205 if (!EC_KEY_regenerate_key(pkey,bn))
208 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
212 if (fCompressed || fCompressedPubKey)
213 SetCompressedPubKey();
217 CSecret CKey::GetSecret(bool &fCompressed) const
221 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
222 int nBytes = BN_num_bytes(bn);
224 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
225 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
227 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
228 fCompressed = fCompressedPubKey;
232 CPrivKey CKey::GetPrivKey() const
234 int nSize = i2d_ECPrivateKey(pkey, NULL);
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");
244 bool CKey::SetPubKey(const std::vector<unsigned char>& vchPubKey)
246 const unsigned char* pbegin = &vchPubKey[0];
247 if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
250 if (vchPubKey.size() == 33)
251 SetCompressedPubKey();
255 std::vector<unsigned char> CKey::GetPubKey() const
257 int nSize = i2o_ECPublicKey(pkey, NULL);
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");
267 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
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))
276 vchSig.resize(nSize); // Shrink to fit actual size
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)
287 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
292 int nBitsR = BN_num_bits(sig->r);
293 int nBitsS = BN_num_bits(sig->s);
294 if (nBitsR <= 256 && nBitsS <= 256)
297 for (int i=0; i<4; i++)
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())
312 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
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]);
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)
329 if (vchSig.size() != 65)
334 ECDSA_SIG *sig = ECDSA_SIG_new();
335 BN_bin2bn(&vchSig[1],32,sig->r);
336 BN_bin2bn(&vchSig[33],32,sig->s);
339 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
342 SetCompressedPubKey();
345 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
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)
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;
364 GetValidSigCache(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
368 sigdata_type k(hash, vchSig, pubKey);
369 std::set<sigdata_type>::iterator mi = setValidSigCache.find(k);
370 if (mi != setValidSigCache.end())
376 SetValidSigCache(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
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;
387 while (setValidSigCache.size() > nMaxCacheSize)
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);
402 sigdata_type k(hash, vchSig, pubKey);
403 setValidSigCache.insert(k);
407 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
409 if (GetValidSigCache(hash, vchSig, GetPubKey()))
412 // -1 = error, 0 = bad sig, 1 = good
413 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
417 SetValidSigCache(hash, vchSig, GetPubKey());
421 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
423 if (GetValidSigCache(hash, vchSig, GetPubKey()))
427 if (!key.SetCompactSignature(hash, vchSig))
429 if (GetPubKey() != key.GetPubKey())
432 SetValidSigCache(hash, vchSig, GetPubKey());
442 CSecret secret = GetSecret(fCompr);
444 key2.SetSecret(secret, fCompr);
445 return GetPubKey() == key2.GetPubKey();