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)
19 BN_CTX *ctx = nullptr;
20 EC_POINT *pub_key = nullptr;
22 const EC_GROUP *group = EC_KEY_get0_group(eckey);
24 if ((ctx = BN_CTX_new()) == nullptr)
27 pub_key = EC_POINT_new(group);
29 if (pub_key == nullptr)
32 if (!EC_POINT_mul(group, pub_key, priv_key, nullptr, nullptr, ctx))
35 if (!EC_KEY_set_private_key(eckey,priv_key))
37 if (!EC_KEY_set_public_key(eckey,pub_key))
45 EC_POINT_free(pub_key);
52 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
53 // recid selects which key is recovered
54 // if check is non-zero, additional checks are performed
55 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
76 const EC_GROUP *group = EC_KEY_get0_group(eckey);
77 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
79 order = BN_CTX_get(ctx);
80 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
82 if (!BN_copy(x, order)) { ret=-1; goto err; }
83 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
85 // Get internal R and S pointers
86 const BIGNUM *ecsig_r, *ecsig_s;
87 ECDSA_SIG_get0(ecsig, &ecsig_r, &ecsig_s);
89 if (!BN_add(x, x, ecsig_r)) { ret=-1; goto err; }
90 field = BN_CTX_get(ctx);
91 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
92 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
93 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
94 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
97 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
98 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
99 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
101 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
102 n = EC_GROUP_get_degree(group);
104 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
105 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
106 zero = BN_CTX_get(ctx);
107 if (!BN_set_word(zero, 0)) { ret=-1; goto err; }
108 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
109 rr = BN_CTX_get(ctx);
110 if (!BN_mod_inverse(rr, ecsig_r, order, ctx)) { ret=-1; goto err; }
111 sor = BN_CTX_get(ctx);
112 if (!BN_mod_mul(sor, ecsig_s, rr, order, ctx)) { ret=-1; goto err; }
113 eor = BN_CTX_get(ctx);
114 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
115 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
116 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
125 if (R != NULL) EC_POINT_free(R);
126 if (O != NULL) EC_POINT_free(O);
127 if (Q != NULL) EC_POINT_free(Q);
131 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
132 while (c1len > c2len) {
138 while (c2len > c1len) {
156 // Order of secp256k1's generator minus 1.
157 const unsigned char vchMaxModOrder[32] = {
158 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
159 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
160 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
161 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
164 // Half of the order of secp256k1's generator minus 1.
165 const unsigned char vchMaxModHalfOrder[32] = {
166 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
167 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
168 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
169 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
172 const unsigned char *vchZero = NULL;
174 void CKey::SetCompressedPubKey(bool fCompressed)
176 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
184 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
186 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
195 CKey::CKey(const CKey& b)
197 pkey = EC_KEY_dup(b.pkey);
199 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
203 CKey::CKey(const CSecret& b, bool fCompressed)
205 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
207 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
208 SetSecret(b, fCompressed);
211 CKey& CKey::operator=(const CKey& b)
213 if (!EC_KEY_copy(pkey, b.pkey))
214 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
225 bool CKey::IsNull() const
230 bool CKey::IsCompressed() const
232 return (EC_KEY_get_conv_form(pkey) == POINT_CONVERSION_COMPRESSED);
235 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
236 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
237 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
240 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
245 unsigned char *pos = &vchSig[0];
246 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
251 int nSize = i2d_ECDSA_SIG(sig, NULL);
253 vchSig.resize(nSize); // grow or shrink as needed
256 i2d_ECDSA_SIG(sig, &pos);
266 void CKey::MakeNewKey(bool fCompressed)
268 if (!EC_KEY_generate_key(pkey))
269 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
270 SetCompressedPubKey(fCompressed);
274 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
276 const unsigned char* pbegin = &vchPrivKey[0];
277 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
279 // In testing, d2i_ECPrivateKey can return true
280 // but fill in pkey with a key that fails
281 // EC_KEY_check_key, so:
282 if (EC_KEY_check_key(pkey))
288 // If vchPrivKey data is bad d2i_ECPrivateKey() can
289 // leave pkey in a state where calling EC_KEY_free()
290 // crashes. To avoid that, set pkey to NULL and
291 // leak the memory (a leak is better than a crash)
297 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
300 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
302 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
304 if (vchSecret.size() != 32)
305 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
306 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
308 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
309 if (!EC_KEY_regenerate_key(pkey,bn))
312 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
316 SetCompressedPubKey(fCompressed);
320 CSecret CKey::GetSecret(bool &fCompressed) const
324 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
325 int nBytes = BN_num_bytes(bn);
327 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
328 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
330 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
331 fCompressed = IsCompressed();
335 CSecret CKey::GetSecret() const
338 return GetSecret(fCompressed);
341 CPrivKey CKey::GetPrivKey() const
343 int nSize = i2d_ECPrivateKey(pkey, NULL);
345 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
346 CPrivKey vchPrivKey(nSize, 0);
347 unsigned char* pbegin = &vchPrivKey[0];
348 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
349 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
353 CPubKey CKey::GetPubKey() const
355 int nSize = i2o_ECPublicKey(pkey, NULL);
357 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
358 std::vector<unsigned char> vchPubKey(nSize, 0);
359 unsigned char* pbegin = &vchPubKey[0];
360 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
361 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
362 return CPubKey(vchPubKey);
365 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
368 ECDSA_SIG *sig = ECDSA_do_sign(hash.begin(), sizeof(hash), pkey);
371 const EC_GROUP *group = EC_KEY_get0_group(pkey);
373 BIGNUM* order = BN_new(), *halforder = BN_new();
374 EC_GROUP_get_order(group, order, nullptr);
375 BN_rshift1(halforder, order);
377 // Get internal R and S pointers
378 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
379 BIGNUM *current_r = BN_dup(ECDSA_SIG_get0_r(sig));
381 // enforce low S values, by negating the value (modulo the order) if above order/2.
382 if (BN_cmp(current_s, halforder) > 0) {
383 BIGNUM *updated_s = BN_new();
384 BN_copy(updated_s, current_s);
385 BN_sub(updated_s, order, updated_s);
386 ECDSA_SIG_set0(sig, current_r, updated_s);
392 unsigned int nSize = ECDSA_size(pkey);
393 vchSig.resize(nSize); // Make sure it is big enough
394 unsigned char *pos = &vchSig[0];
395 nSize = i2d_ECDSA_SIG(sig, &pos);
397 vchSig.resize(nSize); // Shrink to fit actual size
398 // Testing our new signature
399 if (ECDSA_verify(0, hash.begin(), sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
406 // create a compact signature (65 bytes), which allows reconstructing the used public key
407 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
408 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
409 // 0x1D = second key with even y, 0x1E = second key with odd y
410 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
413 ECDSA_SIG *sig = ECDSA_do_sign(hash.begin(), sizeof(hash), pkey);
416 const EC_GROUP *group = EC_KEY_get0_group(pkey);
417 BIGNUM* order = BN_new(), *halforder = BN_new();
418 EC_GROUP_get_order(group, order, nullptr);
419 BN_rshift1(halforder, order);
421 // Get internal R and S pointers
422 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
423 BIGNUM *current_r = BN_dup(ECDSA_SIG_get0_r(sig));
425 // enforce low S values, by negating the value (modulo the order) if above order/2.
426 if (BN_cmp(current_s, halforder) > 0) {
427 BIGNUM *updated_s = BN_new();
428 BN_copy(updated_s, current_s);
429 BN_sub(updated_s, order, updated_s);
430 ECDSA_SIG_set0(sig, current_r, updated_s);
438 int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
439 int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
440 bool fCompressedPubKey = IsCompressed();
441 if (nBitsR <= 256 && nBitsS <= 256)
444 for (int8_t i=0; i<4; i++)
448 keyRec.SetCompressedPubKey(fCompressedPubKey);
449 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, hash.begin(), sizeof(hash), i, 1) == 1)
450 if (keyRec.GetPubKey() == this->GetPubKey())
460 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
463 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
464 BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
465 BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
473 // reconstruct public key from a compact signature
474 // This is only slightly more CPU intensive than just verifying it.
475 // If this function succeeds, the recovered public key is guaranteed to be valid
476 // (the signature is a valid signature of the given data for that key)
477 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
479 if (vchSig.size() != 65)
484 ECDSA_SIG *sig = ECDSA_SIG_new();
485 BIGNUM *sig_r = BN_new(), *sig_s = BN_new();
486 BN_bin2bn(&vchSig[1],32,sig_r);
487 BN_bin2bn(&vchSig[33],32,sig_s);
488 ECDSA_SIG_set0(sig, sig_r, sig_s);
489 bool fSuccessful = false;
490 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
494 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
498 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
500 int nSize = i2o_ECPublicKey(pkey, NULL);
503 std::vector<unsigned char> vchPubKey(nSize, 0);
504 unsigned char* pbegin = &vchPubKey[0];
505 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
507 Set(vchPubKey.begin(), vchPubKey.end());
508 fSuccessful = IsValid();
518 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
520 if (vchSig.empty() || !IsValid())
523 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
524 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
533 uint8_t *norm_der = NULL;
534 const uint8_t* pbegin = &vbytes[0];
535 const uint8_t* sigptr = &vchSig[0];
537 // Trying to parse public key
538 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
540 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
541 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
543 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
546 // -1 = error, 0 = bad sig, 1 = good
547 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
548 OPENSSL_free(norm_der);
551 ECDSA_SIG_free(norm_sig);
557 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
560 if (!key.SetCompactSignature(hash, vchSig))
570 if (!EC_KEY_check_key(pkey))
574 CSecret secret = GetSecret(fCompr);
576 key2.SetSecret(secret, fCompr);
578 return GetPubKey() == key2.GetPubKey();
588 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
590 err = "EC_KEY_new_by_curve_name failed.";
594 point = EC_POINT_new(group);
596 err = "EC_POINT_new failed.";
602 err = "BN_CTX_new failed.";
609 if (group) EC_GROUP_free(group);
610 if (point) EC_POINT_free(point);
611 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
614 bool CPoint::operator!=(const CPoint &a)
616 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
622 if (point) EC_POINT_free(point);
623 if (group) EC_GROUP_free(group);
624 if (ctx) BN_CTX_free(ctx);
627 // Initialize from octets stream
628 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
630 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
636 // Initialize from octets stream
637 bool CPoint::setPubKey(const CPubKey &key)
639 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
640 return setBytes(vchPubKey);
643 // Serialize to octets stream
644 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
646 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
647 vchBytes.resize(nSize);
648 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
654 // ECC multiplication by specified multiplier
655 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
657 BIGNUM* bnMul = bnMultiplier.get();
658 bool ok = EC_POINT_mul(group, point, NULL, point, bnMul, NULL);
659 if (!ok) printf("CPoint::ECMUL() : EC_POINT_mul failed");
665 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
667 BIGNUM* bnMul = bnMultiplier.get();
668 bool ok = EC_POINT_mul(group, point, bnMul, qPoint.point, BN_value_one(), NULL);
669 if (!ok) printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
676 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
678 EC_KEY *eckey = NULL;
679 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
681 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
684 // Use standard key generation function to get r and R values.
686 // r will be presented by private key;
687 // R is ECDSA public key which calculated as G*r
688 if (!EC_KEY_generate_key(eckey)) {
689 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
692 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
694 int nSize = i2o_ECPublicKey(eckey, NULL);
696 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
699 std::vector<unsigned char> vchPubKey(nSize, 0);
700 unsigned char* pbegin_R = &vchPubKey[0];
702 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
703 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
707 R = CPubKey(vchPubKey);
709 // OpenSSL BIGNUM representation of r value
710 CBigNum bnr(EC_KEY_get0_private_key(eckey));
714 if (!point.setPubKey(pubKeyL)) {
715 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
721 std::vector<unsigned char> vchLr;
722 if (!point.getBytes(vchLr)) {
723 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
726 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
728 bnHash.setuint160(Hash160(vchLr));
731 pointH.setPubKey(pubKeyH);
734 // Calculate P = Hash(L*r)*G + H
735 P.ECMULGEN(bnHash, pointH);
737 if (P.IsInfinity()) {
738 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
741 std::vector<unsigned char> vchResult;
742 P.getBytes(vchResult);
744 vchPubKeyVariant = CPubKey(vchResult);
747 std::string CMalleablePubKey::ToString() const
749 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
751 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
753 return EncodeBase58Check(vch);
756 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
758 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
764 std::vector<unsigned char> CMalleablePubKey::Raw() const
766 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
768 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
773 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
775 std::vector<unsigned char> vchTemp;
776 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
777 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
779 if (vchTemp.size() != 68)
782 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
788 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
790 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
796 void CMalleableKey::Reset()
802 void CMalleableKey::MakeNewKeys()
810 vchSecretL = keyL.GetSecret();
811 vchSecretH = keyH.GetSecret();
814 CMalleableKey::CMalleableKey()
819 CMalleableKey::CMalleableKey(const CMalleableKey &b)
821 SetSecrets(b.vchSecretL, b.vchSecretH);
824 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
829 CMalleableKey::~CMalleableKey()
833 bool CMalleableKey::IsNull() const
835 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
838 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
842 CKey keyL(pvchSecretL);
843 CKey keyH(pvchSecretH);
845 if (!keyL.IsValid() || !keyH.IsValid())
848 vchSecretL = pvchSecretL;
849 vchSecretH = pvchSecretH;
854 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
856 CKey L(vchSecretL), H(vchSecretH);
857 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
861 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
864 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
868 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
872 if (!vchPubKeyVariant.IsValid()) {
873 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
878 if (!point_R.setPubKey(R)) {
879 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
884 CPubKey vchPubKeyH = H.GetPubKey();
887 if (!point_H.setPubKey(vchPubKeyH)) {
888 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
893 if (!point_P.setPubKey(vchPubKeyVariant)) {
894 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
898 // Infinity points are senseless
899 if (point_P.IsInfinity()) {
900 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
905 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
909 std::vector<unsigned char> vchRl;
910 if (!point_R.getBytes(vchRl)) {
911 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
915 // Calculate Hash(R*l)
917 bnHash.setuint160(Hash160(vchRl));
920 // Calculate Ps = Hash(L*r)*G + H
921 point_Ps.ECMULGEN(bnHash, point_H);
923 // Infinity points are senseless
924 if (point_Ps.IsInfinity()) {
925 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
930 if (point_Ps != point_P) {
937 // Check ownership and restore private key
938 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
941 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
945 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
949 if (!vchPubKeyVariant.IsValid()) {
950 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
955 if (!point_R.setPubKey(R)) {
956 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
961 CPubKey vchPubKeyH = H.GetPubKey();
964 if (!point_H.setPubKey(vchPubKeyH)) {
965 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
970 if (!point_P.setPubKey(vchPubKeyVariant)) {
971 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
975 // Infinity points are senseless
976 if (point_P.IsInfinity()) {
977 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
982 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
986 std::vector<unsigned char> vchRl;
987 if (!point_R.getBytes(vchRl)) {
988 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
992 // Calculate Hash(R*l)
994 bnHash.setuint160(Hash160(vchRl));
997 // Calculate Ps = Hash(L*r)*G + H
998 point_Ps.ECMULGEN(bnHash, point_H);
1000 // Infinity points are senseless
1001 if (point_Ps.IsInfinity()) {
1002 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1007 if (point_Ps != point_P) {
1011 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1013 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1015 // Calculate p = Hash(R*l) + h
1016 CBigNum bnp = bnHash + bnh;
1018 std::vector<unsigned char> vchp = bnp.getBytes();
1019 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1024 std::string CMalleableKey::ToString() const
1026 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1028 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1030 return EncodeBase58Check(vch);
1033 std::vector<unsigned char> CMalleableKey::Raw() const
1035 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1037 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1042 bool CMalleableKey::SetString(const std::string& strMutableKey)
1044 std::vector<unsigned char> vchTemp;
1045 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1046 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1048 if (vchTemp.size() != 66)
1050 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1056 // CMalleableKeyView
1058 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1060 SetString(strMalleableKey);
1063 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1065 if (b.vchSecretL.size() != 32)
1066 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1068 if (b.vchSecretH.size() != 32)
1069 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1071 vchSecretL = b.vchSecretL;
1073 CKey H(b.vchSecretH);
1074 vchPubKeyH = H.GetPubKey();
1077 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1079 vchSecretL = b.vchSecretL;
1080 vchPubKeyH = b.vchPubKeyH;
1083 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1085 vchSecretL = b.vchSecretL;
1087 CKey H(b.vchSecretH);
1088 vchPubKeyH = H.GetPubKey();
1093 CMalleableKeyView::~CMalleableKeyView()
1097 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1099 CKey keyL(vchSecretL);
1100 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1104 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1107 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1111 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1115 if (!vchPubKeyVariant.IsValid()) {
1116 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1121 if (!point_R.setPubKey(R)) {
1122 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1127 if (!point_H.setPubKey(vchPubKeyH)) {
1128 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1133 if (!point_P.setPubKey(vchPubKeyVariant)) {
1134 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1138 // Infinity points are senseless
1139 if (point_P.IsInfinity()) {
1140 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1145 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1149 std::vector<unsigned char> vchRl;
1150 if (!point_R.getBytes(vchRl)) {
1151 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1155 // Calculate Hash(R*l)
1157 bnHash.setuint160(Hash160(vchRl));
1160 // Calculate Ps = Hash(L*r)*G + H
1161 point_Ps.ECMULGEN(bnHash, point_H);
1163 // Infinity points are senseless
1164 if (point_Ps.IsInfinity()) {
1165 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1170 if (point_Ps != point_P) {
1177 std::string CMalleableKeyView::ToString() const
1179 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1181 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1183 return EncodeBase58Check(vch);
1186 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1188 std::vector<unsigned char> vchTemp;
1189 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1190 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1193 if (vchTemp.size() != 67)
1196 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1202 std::vector<unsigned char> CMalleableKeyView::Raw() const
1204 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1206 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1212 bool CMalleableKeyView::IsValid() const
1214 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();