Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

key.cpp 19KB

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