Make CPubKey statically allocated

This commit is contained in:
Pieter Wuille
2013-04-30 21:56:04 +02:00
committed by Pieter Wuille
parent ec0004aca0
commit 5d891489ab
7 changed files with 98 additions and 28 deletions

View File

@@ -63,38 +63,95 @@ public:
/** An encapsulated public key. */
class CPubKey {
private:
std::vector<unsigned char> vchPubKey;
unsigned char vch[65];
unsigned int static GetLen(unsigned char chHeader) {
if (chHeader == 2 || chHeader == 3)
return 33;
if (chHeader == 4 || chHeader == 6 || chHeader == 7)
return 65;
return 0;
}
unsigned char *begin() {
return vch;
}
friend class CKey;
public:
CPubKey() { }
CPubKey(const std::vector<unsigned char> &vchPubKeyIn) : vchPubKey(vchPubKeyIn) { }
friend bool operator==(const CPubKey &a, const CPubKey &b) { return a.vchPubKey == b.vchPubKey; }
friend bool operator!=(const CPubKey &a, const CPubKey &b) { return a.vchPubKey != b.vchPubKey; }
friend bool operator<(const CPubKey &a, const CPubKey &b) { return a.vchPubKey < b.vchPubKey; }
CPubKey() { vch[0] = 0xFF; }
IMPLEMENT_SERIALIZE(
READWRITE(vchPubKey);
)
CPubKey(const std::vector<unsigned char> &vchPubKeyIn) {
int len = vchPubKeyIn.empty() ? 0 : GetLen(vchPubKeyIn[0]);
if (len) {
memcpy(vch, &vchPubKeyIn[0], len);
} else {
vch[0] = 0xFF;
}
}
unsigned int size() const {
return GetLen(vch[0]);
}
const unsigned char *begin() const {
return vch;
}
const unsigned char *end() const {
return vch+size();
}
friend bool operator==(const CPubKey &a, const CPubKey &b) { return memcmp(a.vch, b.vch, a.size()) == 0; }
friend bool operator!=(const CPubKey &a, const CPubKey &b) { return memcmp(a.vch, b.vch, a.size()) != 0; }
friend bool operator<(const CPubKey &a, const CPubKey &b) {
return a.vch[0] < b.vch[0] ||
(a.vch[0] == b.vch[0] && memcmp(a.vch+1, b.vch+1, a.size() - 1) < 0);
}
unsigned int GetSerializeSize(int nType, int nVersion) const {
return size() + 1;
}
template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const {
unsigned int len = size();
::Serialize(s, VARINT(len), nType, nVersion);
s.write((char*)vch, len);
}
template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int len;
::Unserialize(s, VARINT(len), nType, nVersion);
if (len <= 65) {
s.read((char*)vch, len);
} else {
// invalid pubkey
vch[0] = 0xFF;
char dummy;
while (len--)
s.read(&dummy, 1);
}
}
CKeyID GetID() const {
return CKeyID(Hash160(vchPubKey));
return CKeyID(Hash160(vch, vch+size()));
}
uint256 GetHash() const {
return Hash(vchPubKey.begin(), vchPubKey.end());
return Hash(vch, vch+size());
}
bool IsValid() const {
return vchPubKey.size() == 33 || vchPubKey.size() == 65;
return size() > 0;
}
bool IsCompressed() const {
return vchPubKey.size() == 33;
return size() == 33;
}
std::vector<unsigned char> Raw() const {
return vchPubKey;
return std::vector<unsigned char>(vch, vch+size());
}
};