8 #include <openssl/bn.h>
9 #include <openssl/ecdsa.h>
10 #include <openssl/obj_mac.h>
11 #include <openssl/rand.h>
17 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
21 EC_POINT *pub_key = NULL;
25 const EC_GROUP *group = EC_KEY_get0_group(eckey);
27 if ((ctx = BN_CTX_new()) == NULL)
30 pub_key = EC_POINT_new(group);
35 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
38 EC_KEY_set_private_key(eckey,priv_key);
39 EC_KEY_set_public_key(eckey,pub_key);
46 EC_POINT_free(pub_key);
56 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig,
const unsigned char *msg,
int msglen,
int recid,
int check)
77 const EC_GROUP *group = EC_KEY_get0_group(eckey);
78 if ((ctx = BN_CTX_new()) == NULL) { ret = -1;
goto err; }
80 order = BN_CTX_get(ctx);
81 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2;
goto err; }
83 if (!BN_copy(x, order)) { ret=-1;
goto err; }
84 if (!BN_mul_word(x, i)) { ret=-1;
goto err; }
85 if (!BN_add(x, x, ecsig->r)) { ret=-1;
goto err; }
86 field = BN_CTX_get(ctx);
87 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2;
goto err; }
88 if (BN_cmp(x, field) >= 0) { ret=0;
goto err; }
89 if ((R = EC_POINT_new(group)) == NULL) { ret = -2;
goto err; }
90 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0;
goto err; }
93 if ((O = EC_POINT_new(group)) == NULL) { ret = -2;
goto err; }
94 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2;
goto err; }
95 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0;
goto err; }
97 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2;
goto err; }
98 n = EC_GROUP_get_degree(group);
100 if (!BN_bin2bn(msg, msglen, e)) { ret=-1;
goto err; }
101 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
102 zero = BN_CTX_get(ctx);
103 if (!BN_zero(zero)) { ret=-1;
goto err; }
104 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1;
goto err; }
105 rr = BN_CTX_get(ctx);
106 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1;
goto err; }
107 sor = BN_CTX_get(ctx);
108 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1;
goto err; }
109 eor = BN_CTX_get(ctx);
110 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1;
goto err; }
111 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2;
goto err; }
112 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2;
goto err; }
121 if (R != NULL) EC_POINT_free(R);
122 if (O != NULL) EC_POINT_free(O);
123 if (Q != NULL) EC_POINT_free(Q);
134 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
135 assert(pkey != NULL);
142 void GetSecretBytes(
unsigned char vch[32])
const {
143 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
145 int nBytes = BN_num_bytes(bn);
146 int n=BN_bn2bin(bn,&vch[32 - nBytes]);
148 memset(vch, 0, 32 - nBytes);
151 void SetSecretBytes(
const unsigned char vch[32]) {
155 ret = BN_bin2bn(vch, 32, &bn);
157 ret = EC_KEY_regenerate_key(pkey, &bn);
162 void GetPrivKey(
CPrivKey &privkey,
bool fCompressed) {
163 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
164 int nSize = i2d_ECPrivateKey(pkey, NULL);
166 privkey.resize(nSize);
167 unsigned char* pbegin = &privkey[0];
168 int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);
169 assert(nSize == nSize2);
172 bool SetPrivKey(
const CPrivKey &privkey,
bool fSkipCheck=
false) {
173 const unsigned char* pbegin = &privkey[0];
174 if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {
180 if (EC_KEY_check_key(pkey))
186 void GetPubKey(
CPubKey &pubkey,
bool fCompressed) {
187 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
188 int nSize = i2o_ECPublicKey(pkey, NULL);
192 unsigned char *pbegin = c;
193 int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
194 assert(nSize == nSize2);
195 pubkey.
Set(&c[0], &c[nSize]);
198 bool SetPubKey(
const CPubKey &pubkey) {
199 const unsigned char* pbegin = pubkey.
begin();
200 return o2i_ECPublicKey(&pkey, &pbegin, pubkey.
size());
203 bool Sign(
const uint256 &hash, std::vector<unsigned char>& vchSig) {
205 ECDSA_SIG *sig = ECDSA_do_sign((
unsigned char*)&hash,
sizeof(hash), pkey);
208 BN_CTX *ctx = BN_CTX_new();
210 const EC_GROUP *group = EC_KEY_get0_group(pkey);
211 BIGNUM *order = BN_CTX_get(ctx);
212 BIGNUM *halforder = BN_CTX_get(ctx);
213 EC_GROUP_get_order(group, order, ctx);
214 BN_rshift1(halforder, order);
215 if (BN_cmp(sig->s, halforder) > 0) {
217 BN_sub(sig->s, order, sig->s);
221 unsigned int nSize = ECDSA_size(pkey);
222 vchSig.resize(nSize);
223 unsigned char *pos = &vchSig[0];
224 nSize = i2d_ECDSA_SIG(sig, &pos);
226 vchSig.resize(nSize);
230 bool Verify(
const uint256 &hash,
const std::vector<unsigned char>& vchSig) {
232 if (ECDSA_verify(0, (
unsigned char*)&hash,
sizeof(hash), &vchSig[0], vchSig.
size(), pkey) != 1)
237 bool SignCompact(
const uint256 &hash,
unsigned char *p64,
int &rec) {
239 ECDSA_SIG *sig = ECDSA_do_sign((
unsigned char*)&hash,
sizeof(hash), pkey);
243 int nBitsR = BN_num_bits(sig->r);
244 int nBitsS = BN_num_bits(sig->s);
245 if (nBitsR <= 256 && nBitsS <= 256) {
247 GetPubKey(pubkey,
true);
248 for (
int i=0; i<4; i++) {
250 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (
unsigned char*)&hash,
sizeof(hash), i, 1) == 1) {
252 keyRec.GetPubKey(pubkeyRec,
true);
253 if (pubkeyRec == pubkey) {
261 BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
262 BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
272 bool Recover(
const uint256 &hash,
const unsigned char *p64,
int rec)
276 ECDSA_SIG *sig = ECDSA_SIG_new();
277 BN_bin2bn(&p64[0], 32, sig->r);
278 BN_bin2bn(&p64[32], 32, sig->s);
279 bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (
unsigned char*)&hash,
sizeof(hash), rec, 0) == 1;
284 static bool TweakSecret(
unsigned char vchSecretOut[32],
const unsigned char vchSecretIn[32],
const unsigned char vchTweak[32])
287 BN_CTX *ctx = BN_CTX_new();
289 BIGNUM *bnSecret = BN_CTX_get(ctx);
290 BIGNUM *bnTweak = BN_CTX_get(ctx);
291 BIGNUM *bnOrder = BN_CTX_get(ctx);
292 EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1);
293 EC_GROUP_get_order(group, bnOrder, ctx);
294 BN_bin2bn(vchTweak, 32, bnTweak);
295 if (BN_cmp(bnTweak, bnOrder) >= 0)
297 BN_bin2bn(vchSecretIn, 32, bnSecret);
298 BN_add(bnSecret, bnSecret, bnTweak);
299 BN_nnmod(bnSecret, bnSecret, bnOrder, ctx);
300 if (BN_is_zero(bnSecret))
302 int nBits = BN_num_bits(bnSecret);
303 memset(vchSecretOut, 0, 32);
304 BN_bn2bin(bnSecret, &vchSecretOut[32-(nBits+7)/8]);
305 EC_GROUP_free(group);
311 bool TweakPublic(
const unsigned char vchTweak[32]) {
313 BN_CTX *ctx = BN_CTX_new();
315 BIGNUM *bnTweak = BN_CTX_get(ctx);
316 BIGNUM *bnOrder = BN_CTX_get(ctx);
317 BIGNUM *bnOne = BN_CTX_get(ctx);
318 const EC_GROUP *group = EC_KEY_get0_group(pkey);
319 EC_GROUP_get_order(group, bnOrder, ctx);
320 BN_bin2bn(vchTweak, 32, bnTweak);
321 if (BN_cmp(bnTweak, bnOrder) >= 0)
323 EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
325 EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
326 if (EC_POINT_is_at_infinity(group, point))
328 EC_KEY_set_public_key(pkey, point);
329 EC_POINT_free(point);
341 static const unsigned char vchMax[32] = {
342 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
343 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
344 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
345 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
348 for (
int i=0; i<32 && fIsZero; i++)
353 for (
int i=0; i<32; i++) {
354 if (vch[i] < vchMax[i])
356 if (vch[i] > vchMax[i])
364 RAND_bytes(
vch,
sizeof(
vch));
367 fCompressed = fCompressedIn;
372 key.SetSecretBytes(vchIn);
373 key.GetSecretBytes(
vch);
374 fCompressed = fCompressedIn;
380 if (!key.SetPrivKey(privkey))
382 key.GetSecretBytes(
vch);
383 fCompressed = fCompressedIn;
391 key.SetSecretBytes(
vch);
393 key.GetPrivKey(privkey, fCompressed);
400 key.SetSecretBytes(
vch);
402 key.GetPubKey(pubkey, fCompressed);
410 key.SetSecretBytes(
vch);
411 return key.Sign(hash, vchSig);
418 key.SetSecretBytes(
vch);
421 if (!key.SignCompact(hash, &vchSig[1], rec))
424 vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
430 if (!key.SetPrivKey(privkey, fSkipCheck))
433 key.GetSecretBytes(
vch);
450 if (!key.SetPubKey(*
this))
452 if (!key.Verify(hash, vchSig))
458 if (vchSig.size() != 65)
461 if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
463 key.GetPubKey(*
this, (vchSig[0] - 27) & 4);
470 if (vchSig.size() != 65)
473 if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
477 if (*
this != pubkeyRec)
486 if (!key.SetPubKey(*
this))
495 if (!key.SetPubKey(*
this))
497 key.GetPubKey(*
this,
false);
501 void static BIP32Hash(
const unsigned char chainCode[32],
unsigned int nChild,
unsigned char header,
const unsigned char data[32],
unsigned char output[64]) {
502 unsigned char num[4];
503 num[0] = (nChild >> 24) & 0xFF;
504 num[1] = (nChild >> 16) & 0xFF;
505 num[2] = (nChild >> 8) & 0xFF;
506 num[3] = (nChild >> 0) & 0xFF;
515 bool CKey::Derive(
CKey& keyChild,
unsigned char ccChild[32],
unsigned int nChild,
const unsigned char cc[32])
const {
518 unsigned char out[64];
520 if ((nChild >> 31) == 0) {
522 assert(pubkey.
begin() + 33 == pubkey.
end());
523 BIP32Hash(cc, nChild, *pubkey.
begin(), pubkey.
begin()+1, out);
526 BIP32Hash(cc, nChild, 0,
begin(), out);
528 memcpy(ccChild, out+32, 32);
529 bool ret = CECKey::TweakSecret((
unsigned char*)keyChild.
begin(),
begin(), out);
536 bool CPubKey::Derive(
CPubKey& pubkeyChild,
unsigned char ccChild[32],
unsigned int nChild,
const unsigned char cc[32])
const {
538 assert((nChild >> 31) == 0);
540 unsigned char out[64];
541 BIP32Hash(cc, nChild, *
begin(),
begin()+1, out);
542 memcpy(ccChild, out+32, 32);
544 bool ret = key.SetPubKey(*
this);
545 ret &= key.TweakPublic(out);
546 key.GetPubKey(pubkeyChild,
true);
559 static const char hashkey[] = {
'B',
'i',
't',
'c',
'o',
'i',
'n',
' ',
's',
'e',
'e',
'd'};
563 unsigned char out[64];
566 key.
Set(&out[0], &out[32],
true);
587 code[5] = (
nChild >> 24) & 0xFF; code[6] = (
nChild >> 16) & 0xFF;
588 code[7] = (
nChild >> 8) & 0xFF; code[8] = (
nChild >> 0) & 0xFF;
598 nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
600 key.
Set(code+42, code+74,
true);
606 code[5] = (
nChild >> 24) & 0xFF; code[6] = (
nChild >> 16) & 0xFF;
607 code[7] = (
nChild >> 8) & 0xFF; code[8] = (
nChild >> 0) & 0xFF;
609 assert(pubkey.
size() == 33);
616 nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
618 pubkey.
Set(code+41, code+74);
630 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
bool VerifyCompact(const uint256 &hash, const std::vector< unsigned char > &vchSig) const
void UnlockObject(const T &t)
void Encode(unsigned char code[74]) const
unsigned char vchFingerprint[4]
const unsigned char * begin() const
unsigned char vchChainCode[32]
CExtPubKey Neuter() const
const unsigned char * end() const
int HMAC_SHA512_Init(HMAC_SHA512_CTX *pctx, const void *pkey, size_t len)
unsigned int size() const
void Set(const T pbegin, const T pend)
unsigned char vchFingerprint[4]
int HMAC_SHA512_Update(HMAC_SHA512_CTX *pctx, const void *pdata, size_t len)
bool Sign(const uint256 &hash, std::vector< unsigned char > &vchSig) const
void Decode(const unsigned char code[74])
bool Derive(CExtPubKey &out, unsigned int nChild) const
bool Derive(CExtKey &out, unsigned int nChild) const
void SetSecret(const unsigned char vchIn[32], bool fCompressed=false)
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
bool IsCompressed() const
void LockObject(const T &t)
CPubKey GetPubKey() const
CPrivKey GetPrivKey() const
bool Derive(CKey &keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const
bool RecoverCompact(const uint256 &hash, const std::vector< unsigned char > &vchSig)
An encapsulated public key.
void MakeNewKey(bool fCompressed)
unsigned char vchChainCode[32]
void Set(const T pbegin, const T pend, bool fCompressedIn)
int HMAC_SHA512_Final(unsigned char *pmd, HMAC_SHA512_CTX *pctx)
const unsigned char * begin() const
bool Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck)
bool IsCompressed() const
void Decode(const unsigned char code[74])
bool SetPrivKey(const CPrivKey &vchPrivKey, bool fCompressed)
bool SignCompact(const uint256 &hash, std::vector< unsigned char > &vchSig) const
void * memcpy(void *a, const void *b, size_t c)
A reference to a CKey: the Hash160 of its serialized public key.
bool IsFullyValid() const
void SetMaster(const unsigned char *seed, unsigned int nSeedLen)
static bool Check(const unsigned char *vch)
An encapsulated private key.
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
bool Verify(const uint256 &hash, const std::vector< unsigned char > &vchSig) const
void Encode(unsigned char code[74]) const
bool Derive(CPubKey &pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const
unsigned int size() const
unsigned int size() const
const unsigned char * end() const