-
+ 724BF58424D75E4994755F2A90E868E6EBBB8364CAF1AFD12491D14E0FF445A70CAE159695BB3C8977E02704416135E0D4B9904F599CDEAF3C288F3C6AE3716A
bitcoin/src/key.h
(0 . 0)(1 . 437)
9499 // /****************************\
9500 // * EXPERIMENTAL BRANCH. *
9501 // * FOR LABORATORY USE ONLY. *
9502 // ********************************
9503 // ************
9504 // **************
9505 // ****************
9506 // **** **** ****
9507 // *** *** ***
9508 // *** *** ***
9509 // *** * * **
9510 // ******** ********
9511 // ******* ******
9512 // *** **
9513 // * ******* **
9514 // ** * * * * *
9515 // ** * * ***
9516 // **** * * * * ****
9517 // **** *** * * ** ***
9518 // **** ********* ******
9519 // ******* ***** *******
9520 // ********* ****** **
9521 // ** ****** ******
9522 // ** ******* **
9523 // ** ******* ***
9524 // **** ******** ************
9525 // ************ ************
9526 // ******** *******
9527 // ****** ****
9528 // *** ***
9529 // ********************************
9530 // Copyright (c) 2009-2010 Satoshi Nakamoto
9531 // Copyright (c) 2009-2012 The Bitcoin developers
9532 // Distributed under the MIT/X11 software license, see the accompanying
9533 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
9534 #ifndef BITCOIN_KEY_H
9535 #define BITCOIN_KEY_H
9536
9537 #include <stdexcept>
9538 #include <vector>
9539
9540 #include <openssl/ec.h>
9541 #include <openssl/ecdsa.h>
9542 #include <openssl/obj_mac.h>
9543
9544 #include "serialize.h"
9545 #include "uint256.h"
9546 #include "base58.h"
9547
9548 // secp160k1
9549 // const unsigned int PRIVATE_KEY_SIZE = 192;
9550 // const unsigned int PUBLIC_KEY_SIZE = 41;
9551 // const unsigned int SIGNATURE_SIZE = 48;
9552 //
9553 // secp192k1
9554 // const unsigned int PRIVATE_KEY_SIZE = 222;
9555 // const unsigned int PUBLIC_KEY_SIZE = 49;
9556 // const unsigned int SIGNATURE_SIZE = 57;
9557 //
9558 // secp224k1
9559 // const unsigned int PRIVATE_KEY_SIZE = 250;
9560 // const unsigned int PUBLIC_KEY_SIZE = 57;
9561 // const unsigned int SIGNATURE_SIZE = 66;
9562 //
9563 // secp256k1:
9564 // const unsigned int PRIVATE_KEY_SIZE = 279;
9565 // const unsigned int PUBLIC_KEY_SIZE = 65;
9566 // const unsigned int SIGNATURE_SIZE = 72;
9567 //
9568 // see www.keylength.com
9569 // script supports up to 75 for single byte push
9570
9571 // Generate a private key from just the secret parameter
9572 int static inline EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
9573 {
9574 int ok = 0;
9575 BN_CTX *ctx = NULL;
9576 EC_POINT *pub_key = NULL;
9577
9578 if (!eckey) return 0;
9579
9580 const EC_GROUP *group = EC_KEY_get0_group(eckey);
9581
9582 if ((ctx = BN_CTX_new()) == NULL)
9583 goto err;
9584
9585 pub_key = EC_POINT_new(group);
9586
9587 if (pub_key == NULL)
9588 goto err;
9589
9590 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
9591 goto err;
9592
9593 EC_KEY_set_private_key(eckey,priv_key);
9594 EC_KEY_set_public_key(eckey,pub_key);
9595
9596 ok = 1;
9597
9598 err:
9599
9600 if (pub_key)
9601 EC_POINT_free(pub_key);
9602 if (ctx != NULL)
9603 BN_CTX_free(ctx);
9604
9605 return(ok);
9606 }
9607
9608 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
9609 // recid selects which key is recovered
9610 // if check is nonzero, additional checks are performed
9611 int static inline ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
9612 {
9613 if (!eckey) return 0;
9614
9615 int ret = 0;
9616 BN_CTX *ctx = NULL;
9617
9618 BIGNUM *x = NULL;
9619 BIGNUM *e = NULL;
9620 BIGNUM *order = NULL;
9621 BIGNUM *sor = NULL;
9622 BIGNUM *eor = NULL;
9623 BIGNUM *field = NULL;
9624 EC_POINT *R = NULL;
9625 EC_POINT *O = NULL;
9626 EC_POINT *Q = NULL;
9627 BIGNUM *rr = NULL;
9628 BIGNUM *zero = NULL;
9629 int n = 0;
9630 int i = recid / 2;
9631
9632 const EC_GROUP *group = EC_KEY_get0_group(eckey);
9633 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
9634 BN_CTX_start(ctx);
9635 order = BN_CTX_get(ctx);
9636 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
9637 x = BN_CTX_get(ctx);
9638 if (!BN_copy(x, order)) { ret=-1; goto err; }
9639 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
9640 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
9641 field = BN_CTX_get(ctx);
9642 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
9643 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
9644 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
9645 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
9646 if (check)
9647 {
9648 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
9649 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
9650 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
9651 }
9652 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
9653 n = EC_GROUP_get_degree(group);
9654 e = BN_CTX_get(ctx);
9655 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
9656 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
9657 zero = BN_CTX_get(ctx);
9658 if (!BN_zero(zero)) { ret=-1; goto err; }
9659 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
9660 rr = BN_CTX_get(ctx);
9661 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
9662 sor = BN_CTX_get(ctx);
9663 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
9664 eor = BN_CTX_get(ctx);
9665 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
9666 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
9667 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
9668
9669 ret = 1;
9670
9671 err:
9672 if (ctx) {
9673 BN_CTX_end(ctx);
9674 BN_CTX_free(ctx);
9675 }
9676 if (R != NULL) EC_POINT_free(R);
9677 if (O != NULL) EC_POINT_free(O);
9678 if (Q != NULL) EC_POINT_free(Q);
9679 return ret;
9680 }
9681
9682 class key_error : public std::runtime_error
9683 {
9684 public:
9685 explicit key_error(const std::string& str) : std::runtime_error(str) {}
9686 };
9687
9688
9689 // secure_allocator is defined in serialize.h
9690 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
9691 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
9692 // CSecret is a serialization of just the secret parameter (32 bytes)
9693 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
9694
9695 class CKey
9696 {
9697 protected:
9698 EC_KEY* pkey;
9699 bool fSet;
9700
9701 public:
9702 CKey()
9703 {
9704 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
9705 if (pkey == NULL)
9706 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
9707 fSet = false;
9708 }
9709
9710 CKey(const CKey& b)
9711 {
9712 pkey = EC_KEY_dup(b.pkey);
9713 if (pkey == NULL)
9714 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
9715 fSet = b.fSet;
9716 }
9717
9718 CKey& operator=(const CKey& b)
9719 {
9720 if (!EC_KEY_copy(pkey, b.pkey))
9721 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
9722 fSet = b.fSet;
9723 return (*this);
9724 }
9725
9726 ~CKey()
9727 {
9728 EC_KEY_free(pkey);
9729 }
9730
9731 bool IsNull() const
9732 {
9733 return !fSet;
9734 }
9735
9736 void MakeNewKey()
9737 {
9738 if (!EC_KEY_generate_key(pkey))
9739 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
9740 fSet = true;
9741 }
9742
9743 bool SetPrivKey(const CPrivKey& vchPrivKey)
9744 {
9745 const unsigned char* pbegin = &vchPrivKey[0];
9746 if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
9747 return false;
9748 fSet = true;
9749 return true;
9750 }
9751
9752 bool SetSecret(const CSecret& vchSecret)
9753 {
9754 EC_KEY_free(pkey);
9755 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
9756 if (pkey == NULL)
9757 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
9758 if (vchSecret.size() != 32)
9759 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
9760 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
9761 if (bn == NULL)
9762 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
9763 if (!EC_KEY_regenerate_key(pkey,bn))
9764 {
9765 BN_clear_free(bn);
9766 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
9767 }
9768 BN_clear_free(bn);
9769 fSet = true;
9770 return true;
9771 }
9772
9773 CSecret GetSecret() const
9774 {
9775 CSecret vchRet;
9776 vchRet.resize(32);
9777 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
9778 int nBytes = BN_num_bytes(bn);
9779 if (bn == NULL)
9780 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
9781 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
9782 if (n != nBytes)
9783 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
9784 return vchRet;
9785 }
9786
9787 CPrivKey GetPrivKey() const
9788 {
9789 unsigned int nSize = i2d_ECPrivateKey(pkey, NULL);
9790 if (!nSize)
9791 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
9792 CPrivKey vchPrivKey(nSize, 0);
9793 unsigned char* pbegin = &vchPrivKey[0];
9794 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
9795 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
9796 return vchPrivKey;
9797 }
9798
9799 bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
9800 {
9801 const unsigned char* pbegin = &vchPubKey[0];
9802 if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
9803 return false;
9804 fSet = true;
9805 return true;
9806 }
9807
9808 std::vector<unsigned char> GetPubKey() const
9809 {
9810 unsigned int nSize = i2o_ECPublicKey(pkey, NULL);
9811 if (!nSize)
9812 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
9813 std::vector<unsigned char> vchPubKey(nSize, 0);
9814 unsigned char* pbegin = &vchPubKey[0];
9815 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
9816 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
9817 return vchPubKey;
9818 }
9819
9820 bool Sign(uint256 hash, std::vector<unsigned char>& vchSig)
9821 {
9822 vchSig.clear();
9823 unsigned char pchSig[10000];
9824 unsigned int nSize = 0;
9825 if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), pchSig, &nSize, pkey))
9826 return false;
9827 vchSig.resize(nSize);
9828 memcpy(&vchSig[0], pchSig, nSize);
9829 return true;
9830 }
9831
9832 // create a compact signature (65 bytes), which allows reconstructing the used public key
9833 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
9834 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
9835 // 0x1D = second key with even y, 0x1E = second key with odd y
9836 bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
9837 {
9838 bool fOk = false;
9839 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
9840 if (sig==NULL)
9841 return false;
9842 vchSig.clear();
9843 vchSig.resize(65,0);
9844 int nBitsR = BN_num_bits(sig->r);
9845 int nBitsS = BN_num_bits(sig->s);
9846 if (nBitsR <= 256 && nBitsS <= 256)
9847 {
9848 int nRecId = -1;
9849 for (int i=0; i<4; i++)
9850 {
9851 CKey keyRec;
9852 keyRec.fSet = true;
9853 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
9854 if (keyRec.GetPubKey() == this->GetPubKey())
9855 {
9856 nRecId = i;
9857 break;
9858 }
9859 }
9860
9861 if (nRecId == -1)
9862 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
9863
9864 vchSig[0] = nRecId+27;
9865 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
9866 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
9867 fOk = true;
9868 }
9869 ECDSA_SIG_free(sig);
9870 return fOk;
9871 }
9872
9873 // reconstruct public key from a compact signature
9874 // This is only slightly more CPU intensive than just verifying it.
9875 // If this function succeeds, the recovered public key is guaranteed to be valid
9876 // (the signature is a valid signature of the given data for that key)
9877 bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
9878 {
9879 if (vchSig.size() != 65)
9880 return false;
9881 if (vchSig[0]<27 || vchSig[0]>=31)
9882 return false;
9883 ECDSA_SIG *sig = ECDSA_SIG_new();
9884 BN_bin2bn(&vchSig[1],32,sig->r);
9885 BN_bin2bn(&vchSig[33],32,sig->s);
9886
9887 EC_KEY_free(pkey);
9888 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
9889 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), vchSig[0] - 27, 0) == 1)
9890 {
9891 fSet = true;
9892 ECDSA_SIG_free(sig);
9893 return true;
9894 }
9895 return false;
9896 }
9897
9898 bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
9899 {
9900 // -1 = error, 0 = bad sig, 1 = good
9901 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
9902 return false;
9903 return true;
9904 }
9905
9906 // Verify a compact signature
9907 bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
9908 {
9909 CKey key;
9910 if (!key.SetCompactSignature(hash, vchSig))
9911 return false;
9912 if (GetPubKey() != key.GetPubKey())
9913 return false;
9914 return true;
9915 }
9916
9917 // Get the address corresponding to this key
9918 CBitcoinAddress GetAddress() const
9919 {
9920 return CBitcoinAddress(GetPubKey());
9921 }
9922
9923 bool IsValid()
9924 {
9925 if (!fSet)
9926 return false;
9927
9928 CSecret secret = GetSecret();
9929 CKey key2;
9930 key2.SetSecret(secret);
9931 return GetPubKey() == key2.GetPubKey();
9932 }
9933 };
9934
9935 #endif