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