Master Core  v0.0.9 - 2abfd2849db8ba7a83957c64eb976b406713c123
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
key.h
Go to the documentation of this file.
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 
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 // secp256k1:
18 // const unsigned int PRIVATE_KEY_SIZE = 279;
19 // const unsigned int PUBLIC_KEY_SIZE = 65;
20 // const unsigned int SIGNATURE_SIZE = 72;
21 //
22 // see www.keylength.com
23 // script supports up to 75 for single byte push
24 
26 class CKeyID : public uint160
27 {
28 public:
29  CKeyID() : uint160(0) { }
30  CKeyID(const uint160 &in) : uint160(in) { }
31 };
32 
34 class CScriptID : public uint160
35 {
36 public:
37  CScriptID() : uint160(0) { }
38  CScriptID(const uint160 &in) : uint160(in) { }
39 };
40 
42 class CPubKey {
43 private:
44  // Just store the serialized data.
45  // Its length can very cheaply be computed from the first byte.
46  unsigned char vch[65];
47 
48  // Compute the length of a pubkey with a given first byte.
49  unsigned int static GetLen(unsigned char chHeader) {
50  if (chHeader == 2 || chHeader == 3)
51  return 33;
52  if (chHeader == 4 || chHeader == 6 || chHeader == 7)
53  return 65;
54  return 0;
55  }
56 
57  // Set this key data to be invalid
58  void Invalidate() {
59  vch[0] = 0xFF;
60  }
61 
62 public:
63  // Construct an invalid public key.
64  CPubKey() {
65  Invalidate();
66  }
67 
68  // Initialize a public key using begin/end iterators to byte data.
69  template<typename T>
70  void Set(const T pbegin, const T pend) {
71  int len = pend == pbegin ? 0 : GetLen(pbegin[0]);
72  if (len && len == (pend-pbegin))
73  memcpy(vch, (unsigned char*)&pbegin[0], len);
74  else
75  Invalidate();
76  }
77 
78  // Construct a public key using begin/end iterators to byte data.
79  template<typename T>
80  CPubKey(const T pbegin, const T pend) {
81  Set(pbegin, pend);
82  }
83 
84  // Construct a public key from a byte vector.
85  CPubKey(const std::vector<unsigned char> &vch) {
86  Set(vch.begin(), vch.end());
87  }
88 
89  // Simple read-only vector-like interface to the pubkey data.
90  unsigned int size() const { return GetLen(vch[0]); }
91  const unsigned char *begin() const { return vch; }
92  const unsigned char *end() const { return vch+size(); }
93  const unsigned char &operator[](unsigned int pos) const { return vch[pos]; }
94 
95  // Comparator implementation.
96  friend bool operator==(const CPubKey &a, const CPubKey &b) {
97  return a.vch[0] == b.vch[0] &&
98  memcmp(a.vch, b.vch, a.size()) == 0;
99  }
100  friend bool operator!=(const CPubKey &a, const CPubKey &b) {
101  return !(a == b);
102  }
103  friend bool operator<(const CPubKey &a, const CPubKey &b) {
104  return a.vch[0] < b.vch[0] ||
105  (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0);
106  }
107 
108  // Implement serialization, as if this was a byte vector.
109  unsigned int GetSerializeSize(int nType, int nVersion) const {
110  return size() + 1;
111  }
112  template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const {
113  unsigned int len = size();
114  ::WriteCompactSize(s, len);
115  s.write((char*)vch, len);
116  }
117  template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) {
118  unsigned int len = ::ReadCompactSize(s);
119  if (len <= 65) {
120  s.read((char*)vch, len);
121  } else {
122  // invalid pubkey, skip available data
123  char dummy;
124  while (len--)
125  s.read(&dummy, 1);
126  Invalidate();
127  }
128  }
129 
130  // Get the KeyID of this public key (hash of its serialization)
131  CKeyID GetID() const {
132  return CKeyID(Hash160(vch, vch+size()));
133  }
134 
135  // Get the 256-bit hash of this public key.
136  uint256 GetHash() const {
137  return Hash(vch, vch+size());
138  }
139 
140  // Check syntactic correctness.
141  //
142  // Note that this is consensus critical as CheckSig() calls it!
143  bool IsValid() const {
144  return size() > 0;
145  }
146 
147  // fully validate whether this is a valid public key (more expensive than IsValid())
148  bool IsFullyValid() const;
149 
150  // Check whether this is a compressed public key.
151  bool IsCompressed() const {
152  return size() == 33;
153  }
154 
155  // Verify a DER signature (~72 bytes).
156  // If this public key is not fully valid, the return value will be false.
157  bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const;
158 
159  // Verify a compact signature (~65 bytes).
160  // See CKey::SignCompact.
161  bool VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const;
162 
163  // Recover a public key from a compact signature.
164  bool RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig);
165 
166  // Turn this public key into an uncompressed public key.
167  bool Decompress();
168 
169  // Derive BIP32 child pubkey.
170  bool Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const;
171 };
172 
173 
174 // secure_allocator is defined in allocators.h
175 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
176 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
177 
179 class CKey {
180 private:
181  // Whether this private key is valid. We check for correctness when modifying the key
182  // data, so fValid should always correspond to the actual state.
183  bool fValid;
184 
185  // Whether the public key corresponding to this private key is (to be) compressed.
187 
188  // The actual byte data
189  unsigned char vch[32];
190 
191  // Check whether the 32-byte array pointed to be vch is valid keydata.
192  bool static Check(const unsigned char *vch);
193 public:
194 
195  // Construct an invalid private key.
196  CKey() : fValid(false) {
197  LockObject(vch);
198  }
199 
200  // Copy constructor. This is necessary because of memlocking.
201  CKey(const CKey &secret) : fValid(secret.fValid), fCompressed(secret.fCompressed) {
202  LockObject(vch);
203  memcpy(vch, secret.vch, sizeof(vch));
204  }
205 
206  // Destructor (again necessary because of memlocking).
207  ~CKey() {
208  UnlockObject(vch);
209  }
210 
211  friend bool operator==(const CKey &a, const CKey &b) {
212  return a.fCompressed == b.fCompressed && a.size() == b.size() &&
213  memcmp(&a.vch[0], &b.vch[0], a.size()) == 0;
214  }
215 
216  // Initialize using begin and end iterators to byte data.
217  template<typename T>
218  void Set(const T pbegin, const T pend, bool fCompressedIn) {
219  if (pend - pbegin != 32) {
220  fValid = false;
221  return;
222  }
223  if (Check(&pbegin[0])) {
224  memcpy(vch, (unsigned char*)&pbegin[0], 32);
225  fValid = true;
226  fCompressed = fCompressedIn;
227  } else {
228  fValid = false;
229  }
230  }
231 
232  // Simple read-only vector-like interface.
233  unsigned int size() const { return (fValid ? 32 : 0); }
234  const unsigned char *begin() const { return vch; }
235  const unsigned char *end() const { return vch + size(); }
236 
237  // Check whether this private key is valid.
238  bool IsValid() const { return fValid; }
239 
240  // Check whether the public key corresponding to this private key is (to be) compressed.
241  bool IsCompressed() const { return fCompressed; }
242 
243  // Initialize from a CPrivKey (serialized OpenSSL private key data).
244  bool SetPrivKey(const CPrivKey &vchPrivKey, bool fCompressed);
245 
246  // Generate a new private key using a cryptographic PRNG.
247  void MakeNewKey(bool fCompressed);
248 
249  // Convert the private key to a CPrivKey (serialized OpenSSL private key data).
250  // This is expensive.
251  CPrivKey GetPrivKey() const;
252 
253  // Compute the public key from a private key.
254  // This is expensive.
255  CPubKey GetPubKey() const;
256 
257  // Create a DER-serialized signature.
258  bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const;
259 
260  // Create a compact signature (65 bytes), which allows reconstructing the used public key.
261  // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
262  // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
263  // 0x1D = second key with even y, 0x1E = second key with odd y,
264  // add 0x04 for compressed keys.
265  bool SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const;
266 
267  // Derive BIP32 child key.
268  bool Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const;
269 
270  // Load private key and check that public key matches.
271  bool Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck);
272 };
273 
274 struct CExtPubKey {
275  unsigned char nDepth;
276  unsigned char vchFingerprint[4];
277  unsigned int nChild;
278  unsigned char vchChainCode[32];
280 
281  friend bool operator==(const CExtPubKey &a, const CExtPubKey &b) {
282  return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild &&
283  memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.pubkey == b.pubkey;
284  }
285 
286  void Encode(unsigned char code[74]) const;
287  void Decode(const unsigned char code[74]);
288  bool Derive(CExtPubKey &out, unsigned int nChild) const;
289 };
290 
291 struct CExtKey {
292  unsigned char nDepth;
293  unsigned char vchFingerprint[4];
294  unsigned int nChild;
295  unsigned char vchChainCode[32];
297 
298  friend bool operator==(const CExtKey &a, const CExtKey &b) {
299  return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild &&
300  memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.key == b.key;
301  }
302 
303  void Encode(unsigned char code[74]) const;
304  void Decode(const unsigned char code[74]);
305  bool Derive(CExtKey &out, unsigned int nChild) const;
306  CExtPubKey Neuter() const;
307  void SetMaster(const unsigned char *seed, unsigned int nSeedLen);
308 };
309 
311 bool ECC_InitSanityCheck(void);
312 
313 #endif
bool VerifyCompact(const uint256 &hash, const std::vector< unsigned char > &vchSig) const
Definition: key.cpp:458
void UnlockObject(const T &t)
Definition: allocators.h:171
void Unserialize(Stream &s, int nType, int nVersion)
Definition: key.h:117
void Encode(unsigned char code[74]) const
Definition: key.cpp:575
unsigned char vchFingerprint[4]
Definition: key.h:276
unsigned static int GetLen(unsigned char chHeader)
Definition: key.h:49
const unsigned char * begin() const
Definition: key.h:234
unsigned char vchChainCode[32]
Definition: key.h:278
CExtPubKey Neuter() const
Definition: key.cpp:565
friend bool operator<(const CPubKey &a, const CPubKey &b)
Definition: key.h:103
CKey key
Definition: key.h:296
uint64_t ReadCompactSize(Stream &is)
Definition: serialize.h:204
const unsigned char * end() const
Definition: key.h:235
Definition: key.h:291
CKeyID(const uint160 &in)
Definition: key.h:30
void Invalidate()
Definition: key.h:58
unsigned int size() const
Definition: key.h:90
void Set(const T pbegin, const T pend)
Definition: key.h:70
unsigned char vchFingerprint[4]
Definition: key.h:293
unsigned char nDepth
Definition: key.h:275
bool Sign(const uint256 &hash, std::vector< unsigned char > &vchSig) const
Definition: key.cpp:397
uint160 Hash160(const T1 pbegin, const T1 pend)
Definition: hash.h:112
CScriptID()
Definition: key.h:37
void Decode(const unsigned char code[74])
Definition: key.cpp:586
bool fValid
Definition: key.h:183
unsigned int nChild
Definition: key.h:277
friend bool operator==(const CPubKey &a, const CPubKey &b)
Definition: key.h:96
bool Derive(CExtPubKey &out, unsigned int nChild) const
Definition: key.cpp:612
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:541
bool IsValid() const
Definition: key.h:238
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
Definition: key.h:176
bool IsCompressed() const
Definition: key.h:241
friend bool operator==(const CExtPubKey &a, const CExtPubKey &b)
Definition: key.h:281
void LockObject(const T &t)
Definition: allocators.h:167
void Serialize(Stream &s, int nType, int nVersion) const
Definition: key.h:112
CPubKey GetPubKey() const
Definition: key.cpp:388
CPrivKey GetPrivKey() const
Definition: key.cpp:379
bool Derive(CKey &keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const
Definition: key.cpp:506
bool RecoverCompact(const uint256 &hash, const std::vector< unsigned char > &vchSig)
Definition: key.cpp:448
unsigned char nDepth
Definition: key.h:292
friend bool operator==(const CExtKey &a, const CExtKey &b)
Definition: key.h:298
CPubKey()
Definition: key.h:64
An encapsulated public key.
Definition: key.h:42
void MakeNewKey(bool fCompressed)
Definition: key.cpp:361
const unsigned char & operator[](unsigned int pos) const
Definition: key.h:93
unsigned int nChild
Definition: key.h:294
~CKey()
Definition: key.h:207
uint256 GetHash() const
Definition: key.h:136
unsigned char vchChainCode[32]
Definition: key.h:295
CPubKey(const std::vector< unsigned char > &vch)
Definition: key.h:85
uint256 Hash(const T1 pbegin, const T1 pend)
Definition: hash.h:19
void Set(const T pbegin, const T pend, bool fCompressedIn)
Definition: key.h:218
unsigned char vch[65]
Definition: key.h:46
const unsigned char * begin() const
Definition: key.h:91
bool Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck)
Definition: key.cpp:419
CScriptID(const uint160 &in)
Definition: key.h:38
bool IsCompressed() const
Definition: key.h:151
void Decode(const unsigned char code[74])
Definition: key.cpp:604
256-bit unsigned integer
Definition: uint256.h:531
bool SetPrivKey(const CPrivKey &vchPrivKey, bool fCompressed)
Definition: key.cpp:369
CKeyID()
Definition: key.h:29
bool SignCompact(const uint256 &hash, std::vector< unsigned char > &vchSig) const
Definition: key.cpp:405
void * memcpy(void *a, const void *b, size_t c)
Definition: glibc_compat.cpp:7
CPubKey(const T pbegin, const T pend)
Definition: key.h:80
A reference to a CKey: the Hash160 of its serialized public key.
Definition: key.h:26
bool fCompressed
Definition: key.h:186
bool IsFullyValid() const
Definition: key.cpp:473
bool IsValid() const
Definition: key.h:143
160-bit unsigned integer
Definition: uint256.h:419
CKey()
Definition: key.h:196
void SetMaster(const unsigned char *seed, unsigned int nSeedLen)
Definition: key.cpp:549
CKey(const CKey &secret)
Definition: key.h:201
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: key.h:34
CPubKey pubkey
Definition: key.h:279
static bool Check(const unsigned char *vch)
Definition: key.cpp:337
An encapsulated private key.
Definition: key.h:179
unsigned char vch[32]
Definition: key.h:189
bool Verify(const uint256 &hash, const std::vector< unsigned char > &vchSig) const
Definition: key.cpp:437
void Encode(unsigned char code[74]) const
Definition: key.cpp:594
bool Derive(CPubKey &pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const
Definition: key.cpp:527
unsigned int size() const
Definition: key.h:233
CKeyID GetID() const
Definition: key.h:131
void WriteCompactSize(Stream &os, uint64_t nSize)
Definition: serialize.h:172
unsigned int GetSerializeSize(int nType, int nVersion) const
Definition: key.h:109
friend bool operator!=(const CPubKey &a, const CPubKey &b)
Definition: key.h:100
const unsigned char * end() const
Definition: key.h:92
bool Decompress()
Definition: key.cpp:482
bool ECC_InitSanityCheck(void)
Check that required EC support is available at runtime.
Definition: key.cpp:620
friend bool operator==(const CKey &a, const CKey &b)
Definition: key.h:211