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.h 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef BITCOIN_KEY_H
  6. #define BITCOIN_KEY_H
  7. #include "allocators.h"
  8. #include "hash.h"
  9. #include "serialize.h"
  10. #include "uint256.h"
  11. #include <stdexcept>
  12. #include <vector>
  13. // secp256k1:
  14. // const unsigned int PRIVATE_KEY_SIZE = 279;
  15. // const unsigned int PUBLIC_KEY_SIZE = 65;
  16. // const unsigned int SIGNATURE_SIZE = 72;
  17. //
  18. // see www.keylength.com
  19. // script supports up to 75 for single byte push
  20. /** A reference to a CKey: the Hash160 of its serialized public key */
  21. class CKeyID : public uint160
  22. {
  23. public:
  24. CKeyID() : uint160(0) { }
  25. CKeyID(const uint160 &in) : uint160(in) { }
  26. };
  27. /** A reference to a CScript: the Hash160 of its serialization (see script.h) */
  28. class CScriptID : public uint160
  29. {
  30. public:
  31. CScriptID() : uint160(0) { }
  32. CScriptID(const uint160 &in) : uint160(in) { }
  33. };
  34. /** An encapsulated public key. */
  35. class CPubKey {
  36. private:
  37. // Just store the serialized data.
  38. // Its length can very cheaply be computed from the first byte.
  39. unsigned char vch[65];
  40. // Compute the length of a pubkey with a given first byte.
  41. unsigned int static GetLen(unsigned char chHeader) {
  42. if (chHeader == 2 || chHeader == 3)
  43. return 33;
  44. if (chHeader == 4 || chHeader == 6 || chHeader == 7)
  45. return 65;
  46. return 0;
  47. }
  48. // Set this key data to be invalid
  49. void Invalidate() {
  50. vch[0] = 0xFF;
  51. }
  52. public:
  53. // Construct an invalid public key.
  54. CPubKey() {
  55. Invalidate();
  56. }
  57. // Initialize a public key using begin/end iterators to byte data.
  58. template<typename T>
  59. void Set(const T pbegin, const T pend) {
  60. int len = pend == pbegin ? 0 : GetLen(pbegin[0]);
  61. if (len && len == (pend-pbegin))
  62. memcpy(vch, (unsigned char*)&pbegin[0], len);
  63. else
  64. Invalidate();
  65. }
  66. // Construct a public key using begin/end iterators to byte data.
  67. template<typename T>
  68. CPubKey(const T pbegin, const T pend) {
  69. Set(pbegin, pend);
  70. }
  71. // Construct a public key from a byte vector.
  72. CPubKey(const std::vector<unsigned char> &vch) {
  73. Set(vch.begin(), vch.end());
  74. }
  75. // Simple read-only vector-like interface to the pubkey data.
  76. unsigned int size() const { return GetLen(vch[0]); }
  77. const unsigned char *begin() const { return vch; }
  78. const unsigned char *end() const { return vch+size(); }
  79. const unsigned char &operator[](unsigned int pos) const { return vch[pos]; }
  80. // Comparator implementation.
  81. friend bool operator==(const CPubKey &a, const CPubKey &b) {
  82. return a.vch[0] == b.vch[0] &&
  83. memcmp(a.vch, b.vch, a.size()) == 0;
  84. }
  85. friend bool operator!=(const CPubKey &a, const CPubKey &b) {
  86. return !(a == b);
  87. }
  88. friend bool operator<(const CPubKey &a, const CPubKey &b) {
  89. return a.vch[0] < b.vch[0] ||
  90. (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0);
  91. }
  92. // Implement serialization, as if this was a byte vector.
  93. unsigned int GetSerializeSize(int nType, int nVersion) const {
  94. return size() + 1;
  95. }
  96. template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const {
  97. unsigned int len = size();
  98. ::WriteCompactSize(s, len);
  99. s.write((char*)vch, len);
  100. }
  101. template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) {
  102. unsigned int len = ::ReadCompactSize(s);
  103. if (len <= 65) {
  104. s.read((char*)vch, len);
  105. } else {
  106. // invalid pubkey, skip available data
  107. char dummy;
  108. while (len--)
  109. s.read(&dummy, 1);
  110. Invalidate();
  111. }
  112. }
  113. // Get the KeyID of this public key (hash of its serialization)
  114. CKeyID GetID() const {
  115. return CKeyID(Hash160(vch, vch+size()));
  116. }
  117. // Get the 256-bit hash of this public key.
  118. uint256 GetHash() const {
  119. return Hash(vch, vch+size());
  120. }
  121. // just check syntactic correctness.
  122. bool IsValid() const {
  123. return size() > 0;
  124. }
  125. // fully validate whether this is a valid public key (more expensive than IsValid())
  126. bool IsFullyValid() const;
  127. // Check whether this is a compressed public key.
  128. bool IsCompressed() const {
  129. return size() == 33;
  130. }
  131. // Verify a DER signature (~72 bytes).
  132. // If this public key is not fully valid, the return value will be false.
  133. bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const;
  134. // Verify a compact signature (~65 bytes).
  135. // See CKey::SignCompact.
  136. bool VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const;
  137. // Recover a public key from a compact signature.
  138. bool RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig);
  139. // Turn this public key into an uncompressed public key.
  140. bool Decompress();
  141. // Derive BIP32 child pubkey.
  142. bool Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const;
  143. };
  144. // secure_allocator is defined in allocators.h
  145. // CPrivKey is a serialized private key, with all parameters included (279 bytes)
  146. typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
  147. /** An encapsulated private key. */
  148. class CKey {
  149. private:
  150. // Whether this private key is valid. We check for correctness when modifying the key
  151. // data, so fValid should always correspond to the actual state.
  152. bool fValid;
  153. // Whether the public key corresponding to this private key is (to be) compressed.
  154. bool fCompressed;
  155. // The actual byte data
  156. unsigned char vch[32];
  157. // Check whether the 32-byte array pointed to be vch is valid keydata.
  158. bool static Check(const unsigned char *vch);
  159. public:
  160. // Construct an invalid private key.
  161. CKey() : fValid(false) {
  162. LockObject(vch);
  163. }
  164. // Copy constructor. This is necessary because of memlocking.
  165. CKey(const CKey &secret) : fValid(secret.fValid), fCompressed(secret.fCompressed) {
  166. LockObject(vch);
  167. memcpy(vch, secret.vch, sizeof(vch));
  168. }
  169. // Destructor (again necessary because of memlocking).
  170. ~CKey() {
  171. UnlockObject(vch);
  172. }
  173. friend bool operator==(const CKey &a, const CKey &b) {
  174. return a.fCompressed == b.fCompressed && a.size() == b.size() &&
  175. memcmp(&a.vch[0], &b.vch[0], a.size()) == 0;
  176. }
  177. // Initialize using begin and end iterators to byte data.
  178. template<typename T>
  179. void Set(const T pbegin, const T pend, bool fCompressedIn) {
  180. if (pend - pbegin != 32) {
  181. fValid = false;
  182. return;
  183. }
  184. if (Check(&pbegin[0])) {
  185. memcpy(vch, (unsigned char*)&pbegin[0], 32);
  186. fValid = true;
  187. fCompressed = fCompressedIn;
  188. } else {
  189. fValid = false;
  190. }
  191. }
  192. // Simple read-only vector-like interface.
  193. unsigned int size() const { return (fValid ? 32 : 0); }
  194. const unsigned char *begin() const { return vch; }
  195. const unsigned char *end() const { return vch + size(); }
  196. // Check whether this private key is valid.
  197. bool IsValid() const { return fValid; }
  198. // Check whether the public key corresponding to this private key is (to be) compressed.
  199. bool IsCompressed() const { return fCompressed; }
  200. // Initialize from a CPrivKey (serialized OpenSSL private key data).
  201. bool SetPrivKey(const CPrivKey &vchPrivKey, bool fCompressed);
  202. // Generate a new private key using a cryptographic PRNG.
  203. void MakeNewKey(bool fCompressed);
  204. // Convert the private key to a CPrivKey (serialized OpenSSL private key data).
  205. // This is expensive.
  206. CPrivKey GetPrivKey() const;
  207. // Compute the public key from a private key.
  208. // This is expensive.
  209. CPubKey GetPubKey() const;
  210. // Create a DER-serialized signature.
  211. bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const;
  212. // Create a compact signature (65 bytes), which allows reconstructing the used public key.
  213. // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
  214. // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
  215. // 0x1D = second key with even y, 0x1E = second key with odd y,
  216. // add 0x04 for compressed keys.
  217. bool SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const;
  218. // Derive BIP32 child key.
  219. bool Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const;
  220. // Load private key and check that public key matches.
  221. bool Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck);
  222. };
  223. struct CExtPubKey {
  224. unsigned char nDepth;
  225. unsigned char vchFingerprint[4];
  226. unsigned int nChild;
  227. unsigned char vchChainCode[32];
  228. CPubKey pubkey;
  229. friend bool operator==(const CExtPubKey &a, const CExtPubKey &b) {
  230. return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild &&
  231. memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.pubkey == b.pubkey;
  232. }
  233. void Encode(unsigned char code[74]) const;
  234. void Decode(const unsigned char code[74]);
  235. bool Derive(CExtPubKey &out, unsigned int nChild) const;
  236. };
  237. struct CExtKey {
  238. unsigned char nDepth;
  239. unsigned char vchFingerprint[4];
  240. unsigned int nChild;
  241. unsigned char vchChainCode[32];
  242. CKey key;
  243. friend bool operator==(const CExtKey &a, const CExtKey &b) {
  244. return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild &&
  245. memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.key == b.key;
  246. }
  247. void Encode(unsigned char code[74]) const;
  248. void Decode(const unsigned char code[74]);
  249. bool Derive(CExtKey &out, unsigned int nChild) const;
  250. CExtPubKey Neuter() const;
  251. void SetMaster(const unsigned char *seed, unsigned int nSeedLen);
  252. };
  253. #endif