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