You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

key.cpp 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. // Copyright (c) 2009-2013 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.
  4. #include "key.h"
  5. #include "crypto/sha2.h"
  6. #include <openssl/bn.h>
  7. #include <openssl/ecdsa.h>
  8. #include <openssl/obj_mac.h>
  9. #include <openssl/rand.h>
  10. // anonymous namespace with local implementation code (OpenSSL interaction)
  11. namespace {
  12. // Generate a private key from just the secret parameter
  13. int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
  14. {
  15. int ok = 0;
  16. BN_CTX *ctx = NULL;
  17. EC_POINT *pub_key = NULL;
  18. if (!eckey) return 0;
  19. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  20. if ((ctx = BN_CTX_new()) == NULL)
  21. goto err;
  22. pub_key = EC_POINT_new(group);
  23. if (pub_key == NULL)
  24. goto err;
  25. if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
  26. goto err;
  27. EC_KEY_set_private_key(eckey,priv_key);
  28. EC_KEY_set_public_key(eckey,pub_key);
  29. ok = 1;
  30. err:
  31. if (pub_key)
  32. EC_POINT_free(pub_key);
  33. if (ctx != NULL)
  34. BN_CTX_free(ctx);
  35. return(ok);
  36. }
  37. // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
  38. // recid selects which key is recovered
  39. // if check is non-zero, additional checks are performed
  40. int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
  41. {
  42. if (!eckey) return 0;
  43. int ret = 0;
  44. BN_CTX *ctx = NULL;
  45. BIGNUM *x = NULL;
  46. BIGNUM *e = NULL;
  47. BIGNUM *order = NULL;
  48. BIGNUM *sor = NULL;
  49. BIGNUM *eor = NULL;
  50. BIGNUM *field = NULL;
  51. EC_POINT *R = NULL;
  52. EC_POINT *O = NULL;
  53. EC_POINT *Q = NULL;
  54. BIGNUM *rr = NULL;
  55. BIGNUM *zero = NULL;
  56. int n = 0;
  57. int i = recid / 2;
  58. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  59. if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
  60. BN_CTX_start(ctx);
  61. order = BN_CTX_get(ctx);
  62. if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
  63. x = BN_CTX_get(ctx);
  64. if (!BN_copy(x, order)) { ret=-1; goto err; }
  65. if (!BN_mul_word(x, i)) { ret=-1; goto err; }
  66. if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
  67. field = BN_CTX_get(ctx);
  68. if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
  69. if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
  70. if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  71. if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
  72. if (check)
  73. {
  74. if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  75. if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
  76. if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
  77. }
  78. if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  79. n = EC_GROUP_get_degree(group);
  80. e = BN_CTX_get(ctx);
  81. if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
  82. if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
  83. zero = BN_CTX_get(ctx);
  84. if (!BN_zero(zero)) { ret=-1; goto err; }
  85. if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
  86. rr = BN_CTX_get(ctx);
  87. if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
  88. sor = BN_CTX_get(ctx);
  89. if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
  90. eor = BN_CTX_get(ctx);
  91. if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
  92. if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
  93. if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
  94. ret = 1;
  95. err:
  96. if (ctx) {
  97. BN_CTX_end(ctx);
  98. BN_CTX_free(ctx);
  99. }
  100. if (R != NULL) EC_POINT_free(R);
  101. if (O != NULL) EC_POINT_free(O);
  102. if (Q != NULL) EC_POINT_free(Q);
  103. return ret;
  104. }
  105. // RAII Wrapper around OpenSSL's EC_KEY
  106. class CECKey {
  107. private:
  108. EC_KEY *pkey;
  109. public:
  110. CECKey() {
  111. pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
  112. assert(pkey != NULL);
  113. }
  114. ~CECKey() {
  115. EC_KEY_free(pkey);
  116. }
  117. void GetSecretBytes(unsigned char vch[32]) const {
  118. const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
  119. assert(bn);
  120. int nBytes = BN_num_bytes(bn);
  121. int n=BN_bn2bin(bn,&vch[32 - nBytes]);
  122. assert(n == nBytes);
  123. memset(vch, 0, 32 - nBytes);
  124. }
  125. void SetSecretBytes(const unsigned char vch[32]) {
  126. bool ret;
  127. BIGNUM bn;
  128. BN_init(&bn);
  129. ret = BN_bin2bn(vch, 32, &bn);
  130. assert(ret);
  131. ret = EC_KEY_regenerate_key(pkey, &bn);
  132. assert(ret);
  133. BN_clear_free(&bn);
  134. }
  135. void GetPrivKey(CPrivKey &privkey, bool fCompressed) {
  136. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  137. int nSize = i2d_ECPrivateKey(pkey, NULL);
  138. assert(nSize);
  139. privkey.resize(nSize);
  140. unsigned char* pbegin = &privkey[0];
  141. int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);
  142. assert(nSize == nSize2);
  143. }
  144. bool SetPrivKey(const CPrivKey &privkey, bool fSkipCheck=false) {
  145. const unsigned char* pbegin = &privkey[0];
  146. if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {
  147. if(fSkipCheck)
  148. return true;
  149. // d2i_ECPrivateKey returns true if parsing succeeds.
  150. // This doesn't necessarily mean the key is valid.
  151. if (EC_KEY_check_key(pkey))
  152. return true;
  153. }
  154. return false;
  155. }
  156. void GetPubKey(CPubKey &pubkey, bool fCompressed) {
  157. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  158. int nSize = i2o_ECPublicKey(pkey, NULL);
  159. assert(nSize);
  160. assert(nSize <= 65);
  161. unsigned char c[65];
  162. unsigned char *pbegin = c;
  163. int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
  164. assert(nSize == nSize2);
  165. pubkey.Set(&c[0], &c[nSize]);
  166. }
  167. bool SetPubKey(const CPubKey &pubkey) {
  168. const unsigned char* pbegin = pubkey.begin();
  169. return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());
  170. }
  171. bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) {
  172. vchSig.clear();
  173. ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
  174. if (sig == NULL)
  175. return false;
  176. BN_CTX *ctx = BN_CTX_new();
  177. BN_CTX_start(ctx);
  178. const EC_GROUP *group = EC_KEY_get0_group(pkey);
  179. BIGNUM *order = BN_CTX_get(ctx);
  180. BIGNUM *halforder = BN_CTX_get(ctx);
  181. EC_GROUP_get_order(group, order, ctx);
  182. BN_rshift1(halforder, order);
  183. if (BN_cmp(sig->s, halforder) > 0) {
  184. // enforce low S values, by negating the value (modulo the order) if above order/2.
  185. BN_sub(sig->s, order, sig->s);
  186. }
  187. BN_CTX_end(ctx);
  188. BN_CTX_free(ctx);
  189. unsigned int nSize = ECDSA_size(pkey);
  190. vchSig.resize(nSize); // Make sure it is big enough
  191. unsigned char *pos = &vchSig[0];
  192. nSize = i2d_ECDSA_SIG(sig, &pos);
  193. ECDSA_SIG_free(sig);
  194. vchSig.resize(nSize); // Shrink to fit actual size
  195. return true;
  196. }
  197. bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
  198. // -1 = error, 0 = bad sig, 1 = good
  199. if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
  200. return false;
  201. return true;
  202. }
  203. bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) {
  204. bool fOk = false;
  205. ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
  206. if (sig==NULL)
  207. return false;
  208. memset(p64, 0, 64);
  209. int nBitsR = BN_num_bits(sig->r);
  210. int nBitsS = BN_num_bits(sig->s);
  211. if (nBitsR <= 256 && nBitsS <= 256) {
  212. CPubKey pubkey;
  213. GetPubKey(pubkey, true);
  214. for (int i=0; i<4; i++) {
  215. CECKey keyRec;
  216. if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {
  217. CPubKey pubkeyRec;
  218. keyRec.GetPubKey(pubkeyRec, true);
  219. if (pubkeyRec == pubkey) {
  220. rec = i;
  221. fOk = true;
  222. break;
  223. }
  224. }
  225. }
  226. assert(fOk);
  227. BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
  228. BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
  229. }
  230. ECDSA_SIG_free(sig);
  231. return fOk;
  232. }
  233. // reconstruct public key from a compact signature
  234. // This is only slightly more CPU intensive than just verifying it.
  235. // If this function succeeds, the recovered public key is guaranteed to be valid
  236. // (the signature is a valid signature of the given data for that key)
  237. bool Recover(const uint256 &hash, const unsigned char *p64, int rec)
  238. {
  239. if (rec<0 || rec>=3)
  240. return false;
  241. ECDSA_SIG *sig = ECDSA_SIG_new();
  242. BN_bin2bn(&p64[0], 32, sig->r);
  243. BN_bin2bn(&p64[32], 32, sig->s);
  244. bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
  245. ECDSA_SIG_free(sig);
  246. return ret;
  247. }
  248. static bool TweakSecret(unsigned char vchSecretOut[32], const unsigned char vchSecretIn[32], const unsigned char vchTweak[32])
  249. {
  250. bool ret = true;
  251. BN_CTX *ctx = BN_CTX_new();
  252. BN_CTX_start(ctx);
  253. BIGNUM *bnSecret = BN_CTX_get(ctx);
  254. BIGNUM *bnTweak = BN_CTX_get(ctx);
  255. BIGNUM *bnOrder = BN_CTX_get(ctx);
  256. EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1);
  257. EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
  258. BN_bin2bn(vchTweak, 32, bnTweak);
  259. if (BN_cmp(bnTweak, bnOrder) >= 0)
  260. ret = false; // extremely unlikely
  261. BN_bin2bn(vchSecretIn, 32, bnSecret);
  262. BN_add(bnSecret, bnSecret, bnTweak);
  263. BN_nnmod(bnSecret, bnSecret, bnOrder, ctx);
  264. if (BN_is_zero(bnSecret))
  265. ret = false; // ridiculously unlikely
  266. int nBits = BN_num_bits(bnSecret);
  267. memset(vchSecretOut, 0, 32);
  268. BN_bn2bin(bnSecret, &vchSecretOut[32-(nBits+7)/8]);
  269. EC_GROUP_free(group);
  270. BN_CTX_end(ctx);
  271. BN_CTX_free(ctx);
  272. return ret;
  273. }
  274. bool TweakPublic(const unsigned char vchTweak[32]) {
  275. bool ret = true;
  276. BN_CTX *ctx = BN_CTX_new();
  277. BN_CTX_start(ctx);
  278. BIGNUM *bnTweak = BN_CTX_get(ctx);
  279. BIGNUM *bnOrder = BN_CTX_get(ctx);
  280. BIGNUM *bnOne = BN_CTX_get(ctx);
  281. const EC_GROUP *group = EC_KEY_get0_group(pkey);
  282. EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
  283. BN_bin2bn(vchTweak, 32, bnTweak);
  284. if (BN_cmp(bnTweak, bnOrder) >= 0)
  285. ret = false; // extremely unlikely
  286. EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
  287. BN_one(bnOne);
  288. EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
  289. if (EC_POINT_is_at_infinity(group, point))
  290. ret = false; // ridiculously unlikely
  291. EC_KEY_set_public_key(pkey, point);
  292. EC_POINT_free(point);
  293. BN_CTX_end(ctx);
  294. BN_CTX_free(ctx);
  295. return ret;
  296. }
  297. };
  298. int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
  299. while (c1len > c2len) {
  300. if (*c1)
  301. return 1;
  302. c1++;
  303. c1len--;
  304. }
  305. while (c2len > c1len) {
  306. if (*c2)
  307. return -1;
  308. c2++;
  309. c2len--;
  310. }
  311. while (c1len > 0) {
  312. if (*c1 > *c2)
  313. return 1;
  314. if (*c2 > *c1)
  315. return -1;
  316. c1++;
  317. c2++;
  318. c1len--;
  319. }
  320. return 0;
  321. }
  322. // Order of secp256k1's generator minus 1.
  323. const unsigned char vchMaxModOrder[32] = {
  324. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  325. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
  326. 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
  327. 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
  328. };
  329. // Half of the order of secp256k1's generator minus 1.
  330. const unsigned char vchMaxModHalfOrder[32] = {
  331. 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  332. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  333. 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
  334. 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
  335. };
  336. const unsigned char vchZero[0] = {};
  337. } // anon namespace
  338. bool CKey::Check(const unsigned char *vch) {
  339. return CompareBigEndian(vch, 32, vchZero, 0) > 0 &&
  340. CompareBigEndian(vch, 32, vchMaxModOrder, 32) <= 0;
  341. }
  342. bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
  343. return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
  344. CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
  345. }
  346. void CKey::MakeNewKey(bool fCompressedIn) {
  347. do {
  348. RAND_bytes(vch, sizeof(vch));
  349. } while (!Check(vch));
  350. fValid = true;
  351. fCompressed = fCompressedIn;
  352. }
  353. bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
  354. CECKey key;
  355. if (!key.SetPrivKey(privkey))
  356. return false;
  357. key.GetSecretBytes(vch);
  358. fCompressed = fCompressedIn;
  359. fValid = true;
  360. return true;
  361. }
  362. CPrivKey CKey::GetPrivKey() const {
  363. assert(fValid);
  364. CECKey key;
  365. key.SetSecretBytes(vch);
  366. CPrivKey privkey;
  367. key.GetPrivKey(privkey, fCompressed);
  368. return privkey;
  369. }
  370. CPubKey CKey::GetPubKey() const {
  371. assert(fValid);
  372. CECKey key;
  373. key.SetSecretBytes(vch);
  374. CPubKey pubkey;
  375. key.GetPubKey(pubkey, fCompressed);
  376. return pubkey;
  377. }
  378. bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
  379. if (!fValid)
  380. return false;
  381. CECKey key;
  382. key.SetSecretBytes(vch);
  383. return key.Sign(hash, vchSig);
  384. }
  385. bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
  386. if (!fValid)
  387. return false;
  388. CECKey key;
  389. key.SetSecretBytes(vch);
  390. vchSig.resize(65);
  391. int rec = -1;
  392. if (!key.SignCompact(hash, &vchSig[1], rec))
  393. return false;
  394. assert(rec != -1);
  395. vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
  396. return true;
  397. }
  398. bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {
  399. CECKey key;
  400. if (!key.SetPrivKey(privkey, fSkipCheck))
  401. return false;
  402. key.GetSecretBytes(vch);
  403. fCompressed = vchPubKey.IsCompressed();
  404. fValid = true;
  405. if (fSkipCheck)
  406. return true;
  407. if (GetPubKey() != vchPubKey)
  408. return false;
  409. return true;
  410. }
  411. bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
  412. if (!IsValid())
  413. return false;
  414. CECKey key;
  415. if (!key.SetPubKey(*this))
  416. return false;
  417. if (!key.Verify(hash, vchSig))
  418. return false;
  419. return true;
  420. }
  421. bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
  422. if (vchSig.size() != 65)
  423. return false;
  424. CECKey key;
  425. if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
  426. return false;
  427. key.GetPubKey(*this, (vchSig[0] - 27) & 4);
  428. return true;
  429. }
  430. bool CPubKey::IsFullyValid() const {
  431. if (!IsValid())
  432. return false;
  433. CECKey key;
  434. if (!key.SetPubKey(*this))
  435. return false;
  436. return true;
  437. }
  438. bool CPubKey::Decompress() {
  439. if (!IsValid())
  440. return false;
  441. CECKey key;
  442. if (!key.SetPubKey(*this))
  443. return false;
  444. key.GetPubKey(*this, false);
  445. return true;
  446. }
  447. void static BIP32Hash(const unsigned char chainCode[32], unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]) {
  448. unsigned char num[4];
  449. num[0] = (nChild >> 24) & 0xFF;
  450. num[1] = (nChild >> 16) & 0xFF;
  451. num[2] = (nChild >> 8) & 0xFF;
  452. num[3] = (nChild >> 0) & 0xFF;
  453. CHMAC_SHA512(chainCode, 32).Write(&header, 1)
  454. .Write(data, 32)
  455. .Write(num, 4)
  456. .Finalize(output);
  457. }
  458. bool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
  459. assert(IsValid());
  460. assert(IsCompressed());
  461. unsigned char out[64];
  462. LockObject(out);
  463. if ((nChild >> 31) == 0) {
  464. CPubKey pubkey = GetPubKey();
  465. assert(pubkey.begin() + 33 == pubkey.end());
  466. BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);
  467. } else {
  468. assert(begin() + 32 == end());
  469. BIP32Hash(cc, nChild, 0, begin(), out);
  470. }
  471. memcpy(ccChild, out+32, 32);
  472. bool ret = CECKey::TweakSecret((unsigned char*)keyChild.begin(), begin(), out);
  473. UnlockObject(out);
  474. keyChild.fCompressed = true;
  475. keyChild.fValid = ret;
  476. return ret;
  477. }
  478. bool CPubKey::Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
  479. assert(IsValid());
  480. assert((nChild >> 31) == 0);
  481. assert(begin() + 33 == end());
  482. unsigned char out[64];
  483. BIP32Hash(cc, nChild, *begin(), begin()+1, out);
  484. memcpy(ccChild, out+32, 32);
  485. CECKey key;
  486. bool ret = key.SetPubKey(*this);
  487. ret &= key.TweakPublic(out);
  488. key.GetPubKey(pubkeyChild, true);
  489. return ret;
  490. }
  491. bool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {
  492. out.nDepth = nDepth + 1;
  493. CKeyID id = key.GetPubKey().GetID();
  494. memcpy(&out.vchFingerprint[0], &id, 4);
  495. out.nChild = nChild;
  496. return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);
  497. }
  498. void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
  499. static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
  500. unsigned char out[64];
  501. LockObject(out);
  502. CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(out);
  503. key.Set(&out[0], &out[32], true);
  504. memcpy(vchChainCode, &out[32], 32);
  505. UnlockObject(out);
  506. nDepth = 0;
  507. nChild = 0;
  508. memset(vchFingerprint, 0, sizeof(vchFingerprint));
  509. }
  510. CExtPubKey CExtKey::Neuter() const {
  511. CExtPubKey ret;
  512. ret.nDepth = nDepth;
  513. memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
  514. ret.nChild = nChild;
  515. ret.pubkey = key.GetPubKey();
  516. memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);
  517. return ret;
  518. }
  519. void CExtKey::Encode(unsigned char code[74]) const {
  520. code[0] = nDepth;
  521. memcpy(code+1, vchFingerprint, 4);
  522. code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
  523. code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
  524. memcpy(code+9, vchChainCode, 32);
  525. code[41] = 0;
  526. assert(key.size() == 32);
  527. memcpy(code+42, key.begin(), 32);
  528. }
  529. void CExtKey::Decode(const unsigned char code[74]) {
  530. nDepth = code[0];
  531. memcpy(vchFingerprint, code+1, 4);
  532. nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
  533. memcpy(vchChainCode, code+9, 32);
  534. key.Set(code+42, code+74, true);
  535. }
  536. void CExtPubKey::Encode(unsigned char code[74]) const {
  537. code[0] = nDepth;
  538. memcpy(code+1, vchFingerprint, 4);
  539. code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
  540. code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
  541. memcpy(code+9, vchChainCode, 32);
  542. assert(pubkey.size() == 33);
  543. memcpy(code+41, pubkey.begin(), 33);
  544. }
  545. void CExtPubKey::Decode(const unsigned char code[74]) {
  546. nDepth = code[0];
  547. memcpy(vchFingerprint, code+1, 4);
  548. nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
  549. memcpy(vchChainCode, code+9, 32);
  550. pubkey.Set(code+41, code+74);
  551. }
  552. bool CExtPubKey::Derive(CExtPubKey &out, unsigned int nChild) const {
  553. out.nDepth = nDepth + 1;
  554. CKeyID id = pubkey.GetID();
  555. memcpy(&out.vchFingerprint[0], &id, 4);
  556. out.nChild = nChild;
  557. return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode);
  558. }
  559. bool ECC_InitSanityCheck() {
  560. EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
  561. if(pkey == NULL)
  562. return false;
  563. EC_KEY_free(pkey);
  564. // TODO Is there more EC functionality that could be missing?
  565. return true;
  566. }