Back to home page

Bitcoin sources

 
 

    


File indexing completed on 2020-06-26 13:31:55

0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #ifndef BITCOIN_KEY_H
0006 #define BITCOIN_KEY_H
0007 
0008 #include <stdexcept>
0009 #include <vector>
0010 
0011 #include <openssl/ec.h>
0012 #include <openssl/ecdsa.h>
0013 #include <openssl/obj_mac.h>
0014 
0015 #include "serialize.h"
0016 #include "uint256.h"
0017 
0018 // secp160k1
0019 // const unsigned int PRIVATE_KEY_SIZE = 192;
0020 // const unsigned int PUBLIC_KEY_SIZE  = 41;
0021 // const unsigned int SIGNATURE_SIZE   = 48;
0022 //
0023 // secp192k1
0024 // const unsigned int PRIVATE_KEY_SIZE = 222;
0025 // const unsigned int PUBLIC_KEY_SIZE  = 49;
0026 // const unsigned int SIGNATURE_SIZE   = 57;
0027 //
0028 // secp224k1
0029 // const unsigned int PRIVATE_KEY_SIZE = 250;
0030 // const unsigned int PUBLIC_KEY_SIZE  = 57;
0031 // const unsigned int SIGNATURE_SIZE   = 66;
0032 //
0033 // secp256k1:
0034 // const unsigned int PRIVATE_KEY_SIZE = 279;
0035 // const unsigned int PUBLIC_KEY_SIZE  = 65;
0036 // const unsigned int SIGNATURE_SIZE   = 72;
0037 //
0038 // see www.keylength.com
0039 // script supports up to 75 for single byte push
0040 
0041 // Generate a private key from just the secret parameter
0042 int static inline EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
0043 {
0044     int ok = 0;
0045     BN_CTX *ctx = NULL;
0046     EC_POINT *pub_key = NULL;
0047 
0048     if (!eckey) return 0;
0049 
0050     const EC_GROUP *group = EC_KEY_get0_group(eckey);
0051 
0052     if ((ctx = BN_CTX_new()) == NULL)
0053         goto err;
0054 
0055     pub_key = EC_POINT_new(group);
0056 
0057     if (pub_key == NULL)
0058         goto err;
0059 
0060     if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
0061         goto err;
0062 
0063     EC_KEY_set_private_key(eckey,priv_key);
0064     EC_KEY_set_public_key(eckey,pub_key);
0065 
0066     ok = 1;
0067 
0068 err:
0069 
0070     if (pub_key)
0071         EC_POINT_free(pub_key);
0072     if (ctx != NULL)
0073         BN_CTX_free(ctx);
0074 
0075     return(ok);
0076 }
0077 
0078 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
0079 // recid selects which key is recovered
0080 // if check is nonzero, additional checks are performed
0081 int static inline ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
0082 {
0083     if (!eckey) return 0;
0084 
0085     int ret = 0;
0086     BN_CTX *ctx = NULL;
0087 
0088     BIGNUM *x = NULL;
0089     BIGNUM *e = NULL;
0090     BIGNUM *order = NULL;
0091     BIGNUM *sor = NULL;
0092     BIGNUM *eor = NULL;
0093     BIGNUM *field = NULL;
0094     EC_POINT *R = NULL;
0095     EC_POINT *O = NULL;
0096     EC_POINT *Q = NULL;
0097     BIGNUM *rr = NULL;
0098     BIGNUM *zero = NULL;
0099     int n = 0;
0100     int i = recid / 2;
0101 
0102     const EC_GROUP *group = EC_KEY_get0_group(eckey);
0103     if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
0104     BN_CTX_start(ctx);
0105     order = BN_CTX_get(ctx);
0106     if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
0107     x = BN_CTX_get(ctx);
0108     if (!BN_copy(x, order)) { ret=-1; goto err; }
0109     if (!BN_mul_word(x, i)) { ret=-1; goto err; }
0110     if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
0111     field = BN_CTX_get(ctx);
0112     if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
0113     if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
0114     if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
0115     if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
0116     if (check)
0117     {
0118         if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
0119         if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
0120         if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
0121     }
0122     if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
0123     n = EC_GROUP_get_degree(group);
0124     e = BN_CTX_get(ctx);
0125     if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
0126     if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
0127     zero = BN_CTX_get(ctx);
0128     if (!BN_zero(zero)) { ret=-1; goto err; }
0129     if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
0130     rr = BN_CTX_get(ctx);
0131     if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
0132     sor = BN_CTX_get(ctx);
0133     if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
0134     eor = BN_CTX_get(ctx);
0135     if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
0136     if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
0137     if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
0138 
0139     ret = 1;
0140 
0141 err:
0142     if (ctx) {
0143         BN_CTX_end(ctx);
0144         BN_CTX_free(ctx);
0145     }
0146     if (R != NULL) EC_POINT_free(R);
0147     if (O != NULL) EC_POINT_free(O);
0148     if (Q != NULL) EC_POINT_free(Q);
0149     return ret;
0150 }
0151 
0152 class key_error : public std::runtime_error
0153 {
0154 public:
0155     explicit key_error(const std::string& str) : std::runtime_error(str) {}
0156 };
0157 
0158 
0159 // secure_allocator is defined in serialize.h
0160 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
0161 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
0162 // CSecret is a serialization of just the secret parameter (32 bytes)
0163 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
0164 
0165 class CKey
0166 {
0167 protected:
0168     EC_KEY* pkey;
0169     bool fSet;
0170 
0171 public:
0172     CKey()
0173     {
0174         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
0175         if (pkey == NULL)
0176             throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
0177         fSet = false;
0178     }
0179 
0180     CKey(const CKey& b)
0181     {
0182         pkey = EC_KEY_dup(b.pkey);
0183         if (pkey == NULL)
0184             throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
0185         fSet = b.fSet;
0186     }
0187 
0188     CKey& operator=(const CKey& b)
0189     {
0190         if (!EC_KEY_copy(pkey, b.pkey))
0191             throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
0192         fSet = b.fSet;
0193         return (*this);
0194     }
0195 
0196     ~CKey()
0197     {
0198         EC_KEY_free(pkey);
0199     }
0200 
0201     bool IsNull() const
0202     {
0203         return !fSet;
0204     }
0205 
0206     void MakeNewKey()
0207     {
0208         if (!EC_KEY_generate_key(pkey))
0209             throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
0210         fSet = true;
0211     }
0212 
0213     bool SetPrivKey(const CPrivKey& vchPrivKey)
0214     {
0215         const unsigned char* pbegin = &vchPrivKey[0];
0216         if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
0217             return false;
0218         fSet = true;
0219         return true;
0220     }
0221 
0222     bool SetSecret(const CSecret& vchSecret)
0223     {
0224         EC_KEY_free(pkey);
0225         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
0226         if (pkey == NULL)
0227             throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
0228         if (vchSecret.size() != 32)
0229             throw key_error("CKey::SetSecret() : secret must be 32 bytes");
0230         BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
0231         if (bn == NULL)
0232             throw key_error("CKey::SetSecret() : BN_bin2bn failed");
0233         if (!EC_KEY_regenerate_key(pkey,bn))
0234         {
0235             BN_clear_free(bn);
0236             throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
0237         }
0238         BN_clear_free(bn);
0239         fSet = true;
0240         return true;
0241     }
0242 
0243     CSecret GetSecret() const
0244     {
0245         CSecret vchRet;
0246         vchRet.resize(32);
0247         const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
0248         int nBytes = BN_num_bytes(bn);
0249         if (bn == NULL)
0250             throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
0251         int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
0252         if (n != nBytes) 
0253             throw key_error("CKey::GetSecret(): BN_bn2bin failed");
0254         return vchRet;
0255     }
0256 
0257     CPrivKey GetPrivKey() const
0258     {
0259         unsigned int nSize = i2d_ECPrivateKey(pkey, NULL);
0260         if (!nSize)
0261             throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
0262         CPrivKey vchPrivKey(nSize, 0);
0263         unsigned char* pbegin = &vchPrivKey[0];
0264         if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
0265             throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
0266         return vchPrivKey;
0267     }
0268 
0269     bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
0270     {
0271         const unsigned char* pbegin = &vchPubKey[0];
0272         if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
0273             return false;
0274         fSet = true;
0275         return true;
0276     }
0277 
0278     std::vector<unsigned char> GetPubKey() const
0279     {
0280         unsigned int nSize = i2o_ECPublicKey(pkey, NULL);
0281         if (!nSize)
0282             throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
0283         std::vector<unsigned char> vchPubKey(nSize, 0);
0284         unsigned char* pbegin = &vchPubKey[0];
0285         if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
0286             throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
0287         return vchPubKey;
0288     }
0289 
0290     bool Sign(uint256 hash, std::vector<unsigned char>& vchSig)
0291     {
0292         vchSig.clear();
0293         ECDSA_SIG *sig = ECDSA_do_sign((unsigned char *) &hash, sizeof(hash), pkey);
0294 
0295         if (sig == NULL)
0296         {
0297             printf("ERROR, ECDSA_sign failed in key.h:Sign()\n");
0298             return false;
0299         }
0300 
0301         BN_CTX *ctx = BN_CTX_new();
0302         BN_CTX_start(ctx);
0303         const EC_GROUP *group = EC_KEY_get0_group(pkey);
0304         BIGNUM *order = BN_CTX_get(ctx);
0305         BIGNUM *halforder = BN_CTX_get(ctx);
0306         EC_GROUP_get_order(group, order, ctx);
0307         BN_rshift1(halforder, order);
0308 
0309         if (fHighS && (BN_cmp(sig->s, halforder) < 0))
0310         {
0311             // enforce high S values
0312             BN_sub(sig->s, order, sig->s);
0313         }
0314 
0315         if (fLowS && (BN_cmp(sig->s, halforder) > 0))
0316         {
0317             // enforce low S values
0318             BN_sub(sig->s, order, sig->s);
0319         }
0320 
0321         BN_CTX_end(ctx);
0322         BN_CTX_free(ctx);
0323         unsigned int nSize = ECDSA_size(pkey);
0324         vchSig.resize(nSize); // Make sure it is big enough
0325         unsigned char *pos = &vchSig[0];
0326         nSize = i2d_ECDSA_SIG(sig, &pos);
0327         //printf("DEBUG DER R: 0x%s\n", BN_bn2hex(sig->r));
0328         //printf("DEBUG DER R:   %s\n", BN_bn2dec(sig->r));
0329         //printf("DEBUG DER S: 0x%s\n", BN_bn2hex(sig->s));
0330         //printf("DEBUG DER S:   %s\n", BN_bn2dec(sig->s));
0331         ECDSA_SIG_free(sig);
0332         vchSig.resize(nSize); // Shrink to fit actual size
0333         return true;
0334     }
0335 
0336     // create a compact signature (65 bytes), which allows reconstructing the used public key
0337     // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
0338     // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
0339     //                  0x1D = second key with even y, 0x1E = second key with odd y
0340     bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
0341     {
0342         bool fOk = false;
0343         ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
0344         if (sig==NULL)
0345             return false;
0346         vchSig.clear();
0347         vchSig.resize(65,0);
0348         int nBitsR = BN_num_bits(sig->r);
0349         int nBitsS = BN_num_bits(sig->s);
0350         if (nBitsR <= 256 && nBitsS <= 256)
0351         {
0352             int nRecId = -1;
0353             for (int i=0; i<4; i++)
0354             {
0355                 CKey keyRec;
0356                 keyRec.fSet = true;
0357                 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
0358                     if (keyRec.GetPubKey() == this->GetPubKey())
0359                     {
0360                         nRecId = i;
0361                         break;
0362                     }
0363             }
0364 
0365             if (nRecId == -1)
0366                 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
0367 
0368             vchSig[0] = nRecId+27;
0369             BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
0370             BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
0371             fOk = true;
0372         }
0373         ECDSA_SIG_free(sig);
0374         return fOk;
0375     }
0376 
0377     // reconstruct public key from a compact signature
0378     // This is only slightly more CPU intensive than just verifying it.
0379     // If this function succeeds, the recovered public key is guaranteed to be valid
0380     // (the signature is a valid signature of the given data for that key)
0381     bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
0382     {
0383         if (vchSig.size() != 65)
0384             return false;
0385         if (vchSig[0]<27 || vchSig[0]>=31)
0386             return false;
0387         ECDSA_SIG *sig = ECDSA_SIG_new();
0388         BN_bin2bn(&vchSig[1],32,sig->r);
0389         BN_bin2bn(&vchSig[33],32,sig->s);
0390 
0391         EC_KEY_free(pkey);
0392         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
0393         if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), vchSig[0] - 27, 0) == 1)
0394         {
0395             fSet = true;
0396             ECDSA_SIG_free(sig);
0397             return true;
0398         }
0399         return false;
0400     }
0401 
0402     bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
0403     {
0404         // -1 = error, 0 = bad sig, 1 = good
0405         if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
0406             return false;
0407         return true;
0408     }
0409 
0410     // Verify a compact signature
0411     bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
0412     {
0413         CKey key;
0414         if (!key.SetCompactSignature(hash, vchSig))
0415             return false;
0416         if (GetPubKey() != key.GetPubKey())
0417             return false;
0418         return true;
0419     }
0420 
0421     bool IsValid()
0422     {
0423         if (!fSet)
0424             return false;
0425 
0426         CSecret secret = GetSecret();
0427         CKey key2;
0428         key2.SetSecret(secret);
0429         return GetPubKey() == key2.GetPubKey();
0430     }
0431 };
0432 
0433 #endif