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.
7 #include <openssl/ecdsa.h>
8 #include <openssl/evp.h>
13 // Generate a private key from just the secret parameter
14 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
18 EC_POINT *pub_key = NULL;
22 const EC_GROUP *group = EC_KEY_get0_group(eckey);
24 if ((ctx = BN_CTX_new()) == NULL)
27 pub_key = EC_POINT_new(group);
32 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
35 EC_KEY_set_private_key(eckey,priv_key);
36 EC_KEY_set_public_key(eckey,pub_key);
43 EC_POINT_free(pub_key);
50 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
51 // recid selects which key is recovered
52 // if check is non-zero, additional checks are performed
53 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
74 const EC_GROUP *group = EC_KEY_get0_group(eckey);
75 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
77 order = BN_CTX_get(ctx);
78 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
80 if (!BN_copy(x, order)) { ret=-1; goto err; }
81 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
83 // Get internal R and S pointers
84 const BIGNUM *ecsig_r, *ecsig_s;
85 ECDSA_SIG_get0(ecsig, &ecsig_r, &ecsig_s);
87 if (!BN_add(x, x, ecsig_r)) { ret=-1; goto err; }
88 field = BN_CTX_get(ctx);
89 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
90 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
91 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
92 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
95 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
96 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
97 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
99 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
100 n = EC_GROUP_get_degree(group);
102 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
103 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
104 zero = BN_CTX_get(ctx);
106 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
107 rr = BN_CTX_get(ctx);
108 if (!BN_mod_inverse(rr, ecsig_r, order, ctx)) { ret=-1; goto err; }
109 sor = BN_CTX_get(ctx);
110 if (!BN_mod_mul(sor, ecsig_s, rr, order, ctx)) { ret=-1; goto err; }
111 eor = BN_CTX_get(ctx);
112 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
113 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
114 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
123 if (R != NULL) EC_POINT_free(R);
124 if (O != NULL) EC_POINT_free(O);
125 if (Q != NULL) EC_POINT_free(Q);
129 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
130 while (c1len > c2len) {
136 while (c2len > c1len) {
154 // Order of secp256k1's generator minus 1.
155 const unsigned char vchMaxModOrder[32] = {
156 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
157 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
158 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
159 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
162 // Half of the order of secp256k1's generator minus 1.
163 const unsigned char vchMaxModHalfOrder[32] = {
164 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
165 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
166 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
167 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
170 const unsigned char *vchZero = NULL;
172 void CKey::SetCompressedPubKey(bool fCompressed)
174 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
182 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
184 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
193 CKey::CKey(const CKey& b)
195 pkey = EC_KEY_dup(b.pkey);
197 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
201 CKey::CKey(const CSecret& b, bool fCompressed)
203 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
205 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
206 SetSecret(b, fCompressed);
209 CKey& CKey::operator=(const CKey& b)
211 if (!EC_KEY_copy(pkey, b.pkey))
212 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
223 bool CKey::IsNull() const
228 bool CKey::IsCompressed() const
230 return (EC_KEY_get_conv_form(pkey) == POINT_CONVERSION_COMPRESSED);
233 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
234 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
235 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
238 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
243 unsigned char *pos = &vchSig[0];
244 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
249 int nSize = i2d_ECDSA_SIG(sig, NULL);
251 vchSig.resize(nSize); // grow or shrink as needed
254 i2d_ECDSA_SIG(sig, &pos);
264 void CKey::MakeNewKey(bool fCompressed)
266 if (!EC_KEY_generate_key(pkey))
267 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
268 SetCompressedPubKey(fCompressed);
272 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
274 const unsigned char* pbegin = &vchPrivKey[0];
275 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
277 // In testing, d2i_ECPrivateKey can return true
278 // but fill in pkey with a key that fails
279 // EC_KEY_check_key, so:
280 if (EC_KEY_check_key(pkey))
286 // If vchPrivKey data is bad d2i_ECPrivateKey() can
287 // leave pkey in a state where calling EC_KEY_free()
288 // crashes. To avoid that, set pkey to NULL and
289 // leak the memory (a leak is better than a crash)
295 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
298 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
300 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
302 if (vchSecret.size() != 32)
303 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
304 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
306 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
307 if (!EC_KEY_regenerate_key(pkey,bn))
310 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
314 SetCompressedPubKey(fCompressed);
318 CSecret CKey::GetSecret(bool &fCompressed) const
322 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
323 int nBytes = BN_num_bytes(bn);
325 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
326 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
328 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
329 fCompressed = IsCompressed();
333 CSecret CKey::GetSecret() const
336 return GetSecret(fCompressed);
339 CPrivKey CKey::GetPrivKey() const
341 int nSize = i2d_ECPrivateKey(pkey, NULL);
343 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
344 CPrivKey vchPrivKey(nSize, 0);
345 unsigned char* pbegin = &vchPrivKey[0];
346 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
347 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
351 CPubKey CKey::GetPubKey() const
353 int nSize = i2o_ECPublicKey(pkey, NULL);
355 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
356 std::vector<unsigned char> vchPubKey(nSize, 0);
357 unsigned char* pbegin = &vchPubKey[0];
358 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
359 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
360 return CPubKey(vchPubKey);
363 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
366 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
369 const EC_GROUP *group = EC_KEY_get0_group(pkey);
371 BIGNUM* order = BN_new(), *halforder = BN_new();
372 EC_GROUP_get_order(group, order, NULL);
373 BN_rshift1(halforder, order);
375 // Get internal R and S pointers
376 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
378 // enforce low S values, by negating the value (modulo the order) if above order/2.
379 if (BN_cmp(current_s, halforder) > 0) {
380 BIGNUM *updated_s = BN_new();
381 BN_copy(updated_s, current_s);
382 BN_sub(updated_s, order, updated_s);
383 ECDSA_SIG_set0(sig, NULL, updated_s);
389 unsigned int nSize = ECDSA_size(pkey);
390 vchSig.resize(nSize); // Make sure it is big enough
391 unsigned char *pos = &vchSig[0];
392 nSize = i2d_ECDSA_SIG(sig, &pos);
394 vchSig.resize(nSize); // Shrink to fit actual size
395 // Testing our new signature
396 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
403 // create a compact signature (65 bytes), which allows reconstructing the used public key
404 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
405 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
406 // 0x1D = second key with even y, 0x1E = second key with odd y
407 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
410 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
413 const EC_GROUP *group = EC_KEY_get0_group(pkey);
414 BIGNUM* order = BN_new(), *halforder = BN_new();
415 EC_GROUP_get_order(group, order, NULL);
416 BN_rshift1(halforder, order);
418 // Get internal R and S pointers
419 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
421 // enforce low S values, by negating the value (modulo the order) if above order/2.
422 if (BN_cmp(current_s, halforder) > 0) {
423 BIGNUM *updated_s = BN_new();
424 BN_copy(updated_s, current_s);
425 BN_sub(updated_s, order, updated_s);
426 ECDSA_SIG_set0(sig, NULL, updated_s);
434 int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
435 int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
436 bool fCompressedPubKey = IsCompressed();
437 if (nBitsR <= 256 && nBitsS <= 256)
440 for (int8_t i=0; i<4; i++)
444 keyRec.SetCompressedPubKey(fCompressedPubKey);
445 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
446 if (keyRec.GetPubKey() == this->GetPubKey())
456 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
459 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
460 BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
461 BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
469 // reconstruct public key from a compact signature
470 // This is only slightly more CPU intensive than just verifying it.
471 // If this function succeeds, the recovered public key is guaranteed to be valid
472 // (the signature is a valid signature of the given data for that key)
473 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
475 if (vchSig.size() != 65)
480 ECDSA_SIG *sig = ECDSA_SIG_new();
481 BIGNUM *sig_r = BN_new(), *sig_s = BN_new();
482 BN_bin2bn(&vchSig[1],32,sig_r);
483 BN_bin2bn(&vchSig[33],32,sig_s);
484 ECDSA_SIG_set0(sig, sig_r, sig_s);
485 bool fSuccessful = false;
486 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
490 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
494 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
496 int nSize = i2o_ECPublicKey(pkey, NULL);
499 std::vector<unsigned char> vchPubKey(nSize, 0);
500 unsigned char* pbegin = &vchPubKey[0];
501 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
503 Set(vchPubKey.begin(), vchPubKey.end());
504 fSuccessful = IsValid();
514 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
516 if (vchSig.empty() || !IsValid())
519 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
520 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
529 uint8_t *norm_der = NULL;
530 const uint8_t* pbegin = &vbytes[0];
531 const uint8_t* sigptr = &vchSig[0];
533 // Trying to parse public key
534 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
536 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
537 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
539 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
542 // -1 = error, 0 = bad sig, 1 = good
543 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
544 OPENSSL_free(norm_der);
547 ECDSA_SIG_free(norm_sig);
553 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
556 if (!key.SetCompactSignature(hash, vchSig))
566 if (!EC_KEY_check_key(pkey))
570 CSecret secret = GetSecret(fCompr);
572 key2.SetSecret(secret, fCompr);
574 return GetPubKey() == key2.GetPubKey();
584 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
586 err = "EC_KEY_new_by_curve_name failed.";
590 point = EC_POINT_new(group);
592 err = "EC_POINT_new failed.";
598 err = "BN_CTX_new failed.";
605 if (group) EC_GROUP_free(group);
606 if (point) EC_POINT_free(point);
607 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
610 bool CPoint::operator!=(const CPoint &a)
612 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
618 if (point) EC_POINT_free(point);
619 if (group) EC_GROUP_free(group);
620 if (ctx) BN_CTX_free(ctx);
623 // Initialize from octets stream
624 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
626 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
632 // Initialize from octets stream
633 bool CPoint::setPubKey(const CPubKey &key)
635 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
636 return setBytes(vchPubKey);
639 // Serialize to octets stream
640 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
642 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
643 vchBytes.resize(nSize);
644 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
650 // ECC multiplication by specified multiplier
651 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
653 BIGNUM* bnMul = bnMultiplier.get();
654 bool ok = EC_POINT_mul(group, point, NULL, point, bnMul, NULL);
655 if (!ok) printf("CPoint::ECMUL() : EC_POINT_mul failed");
661 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
663 BIGNUM* bnMul = bnMultiplier.get();
664 bool ok = EC_POINT_mul(group, point, bnMul, qPoint.point, BN_value_one(), NULL);
665 if (!ok) printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
672 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
674 EC_KEY *eckey = NULL;
675 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
677 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
680 // Use standard key generation function to get r and R values.
682 // r will be presented by private key;
683 // R is ECDSA public key which calculated as G*r
684 if (!EC_KEY_generate_key(eckey)) {
685 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
688 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
690 int nSize = i2o_ECPublicKey(eckey, NULL);
692 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
695 std::vector<unsigned char> vchPubKey(nSize, 0);
696 unsigned char* pbegin_R = &vchPubKey[0];
698 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
699 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
703 R = CPubKey(vchPubKey);
705 // OpenSSL BIGNUM representation of r value
707 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
711 if (!point.setPubKey(pubKeyL)) {
712 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
718 std::vector<unsigned char> vchLr;
719 if (!point.getBytes(vchLr)) {
720 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
723 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
725 bnHash.setuint160(Hash160(vchLr));
728 pointH.setPubKey(pubKeyH);
731 // Calculate P = Hash(L*r)*G + H
732 P.ECMULGEN(bnHash, pointH);
734 if (P.IsInfinity()) {
735 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
738 std::vector<unsigned char> vchResult;
739 P.getBytes(vchResult);
741 vchPubKeyVariant = CPubKey(vchResult);
744 std::string CMalleablePubKey::ToString() const
746 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
748 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
750 return EncodeBase58Check(vch);
753 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
755 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
761 std::vector<unsigned char> CMalleablePubKey::Raw() const
763 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
765 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
770 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
772 std::vector<unsigned char> vchTemp;
773 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
774 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
776 if (vchTemp.size() != 68)
779 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
785 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
787 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
793 void CMalleableKey::Reset()
799 void CMalleableKey::MakeNewKeys()
807 vchSecretL = keyL.GetSecret();
808 vchSecretH = keyH.GetSecret();
811 CMalleableKey::CMalleableKey()
816 CMalleableKey::CMalleableKey(const CMalleableKey &b)
818 SetSecrets(b.vchSecretL, b.vchSecretH);
821 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
826 CMalleableKey::~CMalleableKey()
830 bool CMalleableKey::IsNull() const
832 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
835 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
839 CKey keyL(pvchSecretL);
840 CKey keyH(pvchSecretH);
842 if (!keyL.IsValid() || !keyH.IsValid())
845 vchSecretL = pvchSecretL;
846 vchSecretH = pvchSecretH;
851 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
853 CKey L(vchSecretL), H(vchSecretH);
854 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
858 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
861 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
865 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
869 if (!vchPubKeyVariant.IsValid()) {
870 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
875 if (!point_R.setPubKey(R)) {
876 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
881 CPubKey vchPubKeyH = H.GetPubKey();
884 if (!point_H.setPubKey(vchPubKeyH)) {
885 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
890 if (!point_P.setPubKey(vchPubKeyVariant)) {
891 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
895 // Infinity points are senseless
896 if (point_P.IsInfinity()) {
897 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
902 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
906 std::vector<unsigned char> vchRl;
907 if (!point_R.getBytes(vchRl)) {
908 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
912 // Calculate Hash(R*l)
914 bnHash.setuint160(Hash160(vchRl));
917 // Calculate Ps = Hash(L*r)*G + H
918 point_Ps.ECMULGEN(bnHash, point_H);
920 // Infinity points are senseless
921 if (point_Ps.IsInfinity()) {
922 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
927 if (point_Ps != point_P) {
934 // Check ownership and restore private key
935 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
938 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
942 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
946 if (!vchPubKeyVariant.IsValid()) {
947 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
952 if (!point_R.setPubKey(R)) {
953 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
958 CPubKey vchPubKeyH = H.GetPubKey();
961 if (!point_H.setPubKey(vchPubKeyH)) {
962 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
967 if (!point_P.setPubKey(vchPubKeyVariant)) {
968 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
972 // Infinity points are senseless
973 if (point_P.IsInfinity()) {
974 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
979 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
983 std::vector<unsigned char> vchRl;
984 if (!point_R.getBytes(vchRl)) {
985 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
989 // Calculate Hash(R*l)
991 bnHash.setuint160(Hash160(vchRl));
994 // Calculate Ps = Hash(L*r)*G + H
995 point_Ps.ECMULGEN(bnHash, point_H);
997 // Infinity points are senseless
998 if (point_Ps.IsInfinity()) {
999 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1004 if (point_Ps != point_P) {
1008 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1010 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1012 // Calculate p = Hash(R*l) + h
1013 CBigNum bnp = bnHash + bnh;
1015 std::vector<unsigned char> vchp = bnp.getBytes();
1016 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1021 std::string CMalleableKey::ToString() const
1023 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1025 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1027 return EncodeBase58Check(vch);
1030 std::vector<unsigned char> CMalleableKey::Raw() const
1032 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1034 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1039 bool CMalleableKey::SetString(const std::string& strMutableKey)
1041 std::vector<unsigned char> vchTemp;
1042 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1043 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1045 if (vchTemp.size() != 66)
1047 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1053 // CMalleableKeyView
1055 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1057 SetString(strMalleableKey);
1060 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1062 if (b.vchSecretL.size() != 32)
1063 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1065 if (b.vchSecretH.size() != 32)
1066 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1068 vchSecretL = b.vchSecretL;
1070 CKey H(b.vchSecretH);
1071 vchPubKeyH = H.GetPubKey();
1074 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1076 vchSecretL = b.vchSecretL;
1077 vchPubKeyH = b.vchPubKeyH;
1080 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1082 vchSecretL = b.vchSecretL;
1084 CKey H(b.vchSecretH);
1085 vchPubKeyH = H.GetPubKey();
1090 CMalleableKeyView::~CMalleableKeyView()
1094 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1096 CKey keyL(vchSecretL);
1097 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1101 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1104 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1108 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1112 if (!vchPubKeyVariant.IsValid()) {
1113 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1118 if (!point_R.setPubKey(R)) {
1119 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1124 if (!point_H.setPubKey(vchPubKeyH)) {
1125 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1130 if (!point_P.setPubKey(vchPubKeyVariant)) {
1131 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1135 // Infinity points are senseless
1136 if (point_P.IsInfinity()) {
1137 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1142 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1146 std::vector<unsigned char> vchRl;
1147 if (!point_R.getBytes(vchRl)) {
1148 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1152 // Calculate Hash(R*l)
1154 bnHash.setuint160(Hash160(vchRl));
1157 // Calculate Ps = Hash(L*r)*G + H
1158 point_Ps.ECMULGEN(bnHash, point_H);
1160 // Infinity points are senseless
1161 if (point_Ps.IsInfinity()) {
1162 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1167 if (point_Ps != point_P) {
1174 std::string CMalleableKeyView::ToString() const
1176 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1178 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1180 return EncodeBase58Check(vch);
1183 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1185 std::vector<unsigned char> vchTemp;
1186 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1187 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1190 if (vchTemp.size() != 67)
1193 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1199 std::vector<unsigned char> CMalleableKeyView::Raw() const
1201 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1203 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1209 bool CMalleableKeyView::IsValid() const
1211 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();