An encapsulated private key. */
| 24 | |
| 25 | /** An encapsulated private key. */ |
| 26 | class CKey |
| 27 | { |
| 28 | public: |
| 29 | /** |
| 30 | * secp256k1: |
| 31 | */ |
| 32 | static const unsigned int SIZE = 279; |
| 33 | static const unsigned int COMPRESSED_SIZE = 214; |
| 34 | /** |
| 35 | * see www.keylength.com |
| 36 | * script supports up to 75 for single byte push |
| 37 | */ |
| 38 | static_assert( |
| 39 | SIZE >= COMPRESSED_SIZE, |
| 40 | "COMPRESSED_SIZE is larger than SIZE"); |
| 41 | |
| 42 | private: |
| 43 | //! Whether this private key is valid. We check for correctness when modifying the key |
| 44 | //! data, so fValid should always correspond to the actual state. |
| 45 | bool fValid; |
| 46 | |
| 47 | //! Whether the public key corresponding to this private key is (to be) compressed. |
| 48 | bool fCompressed; |
| 49 | |
| 50 | //! The actual byte data |
| 51 | std::vector<unsigned char, secure_allocator<unsigned char> > keydata; |
| 52 | |
| 53 | //! Check whether the 32-byte array pointed to by vch is valid keydata. |
| 54 | bool static Check(const unsigned char* vch); |
| 55 | |
| 56 | public: |
| 57 | //! Construct an invalid private key. |
| 58 | CKey() : fValid(false), fCompressed(false) |
| 59 | { |
| 60 | // Important: vch must be 32 bytes in length to not break serialization |
| 61 | keydata.resize(32); |
| 62 | } |
| 63 | |
| 64 | friend bool operator==(const CKey& a, const CKey& b) |
| 65 | { |
| 66 | return a.fCompressed == b.fCompressed && |
| 67 | a.size() == b.size() && |
| 68 | memcmp(a.keydata.data(), b.keydata.data(), a.size()) == 0; |
| 69 | } |
| 70 | |
| 71 | //! Initialize using begin and end iterators to byte data. |
| 72 | template <typename T> |
| 73 | void Set(const T pbegin, const T pend, bool fCompressedIn) |
| 74 | { |
| 75 | if (size_t(pend - pbegin) != keydata.size()) { |
| 76 | fValid = false; |
| 77 | } else if (Check(&pbegin[0])) { |
| 78 | memcpy(keydata.data(), (unsigned char*)&pbegin[0], keydata.size()); |
| 79 | fValid = true; |
| 80 | fCompressed = fCompressedIn; |
| 81 | } else { |
| 82 | fValid = false; |
| 83 | } |