Remove duplicate code

Signed-off-by: Anthony Fieroni <bvbfan@abv.bg>
This commit is contained in:
Anthony Fieroni 2019-12-16 14:29:51 +02:00 committed by Brannon King
parent 5d5f09bafb
commit 2ffd5897af
41 changed files with 514 additions and 756 deletions

View file

@ -411,6 +411,7 @@ claimtrie_libclaimtrie_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
claimtrie_libclaimtrie_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) claimtrie_libclaimtrie_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
claimtrie_libclaimtrie_a_CFLAGS = $(PIE_FLAGS) claimtrie_libclaimtrie_a_CFLAGS = $(PIE_FLAGS)
claimtrie_libclaimtrie_a_SOURCES = \ claimtrie_libclaimtrie_a_SOURCES = \
claimtrie/blob.cpp \
claimtrie/data.cpp \ claimtrie/data.cpp \
claimtrie/forks.cpp \ claimtrie/forks.cpp \
claimtrie/hashes.cpp \ claimtrie/hashes.cpp \

View file

@ -11,23 +11,23 @@
int CAddrInfo::GetTriedBucket(const uint256& nKey) const int CAddrInfo::GetTriedBucket(const uint256& nKey) const
{ {
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash(); auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash();
uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash(); auto hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (GetCheapHash(hash1) % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash();
return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; return GetCheapHash(hash2) % ADDRMAN_TRIED_BUCKET_COUNT;
} }
int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const
{ {
std::vector<unsigned char> vchSourceGroupKey = src.GetGroup(); std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash(); auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash();
uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash(); auto hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (GetCheapHash(hash1) % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash();
return hash2 % ADDRMAN_NEW_BUCKET_COUNT; return GetCheapHash(hash2) % ADDRMAN_NEW_BUCKET_COUNT;
} }
int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const
{ {
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash(); auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash();
return hash1 % ADDRMAN_BUCKET_SIZE; return GetCheapHash(hash1) % ADDRMAN_BUCKET_SIZE;
} }
bool CAddrInfo::IsTerrible(int64_t nNow) const bool CAddrInfo::IsTerrible(int64_t nNow) const

View file

@ -8,6 +8,7 @@ include(../../contrib/cmake/cmake/CPM.cmake)
include(ExternalProject) include(ExternalProject)
set(CLAIMTRIE_SRC set(CLAIMTRIE_SRC
blob.cpp
data.cpp data.cpp
forks.cpp forks.cpp
hashes.cpp hashes.cpp

166
src/claimtrie/blob.cpp Normal file
View file

@ -0,0 +1,166 @@
#include <blob.h>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <iomanip>
#include <sstream>
/** Template base class for fixed-sized opaque blobs. */
template<uint32_t BITS>
CBaseBlob<BITS>::CBaseBlob()
{
SetNull();
}
template<uint32_t BITS>
CBaseBlob<BITS>::CBaseBlob(const std::vector<uint8_t>& vec)
{
assert(vec.size() == size());
std::copy(vec.begin(), vec.end(), begin());
}
template<uint32_t BITS>
CBaseBlob<BITS>::CBaseBlob(const CBaseBlob& o)
{
*this = o;
}
template<uint32_t BITS>
CBaseBlob<BITS>& CBaseBlob<BITS>::operator=(const CBaseBlob& o)
{
if (this != &o)
std::copy(o.begin(), o.end(), begin());
return *this;
}
template<uint32_t BITS>
int CBaseBlob<BITS>::Compare(const CBaseBlob& b) const
{
return std::memcmp(begin(), b.begin(), size());
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::operator<(const CBaseBlob& b) const
{
return Compare(b) < 0;
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::operator==(const CBaseBlob& b) const
{
return Compare(b) == 0;
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::operator!=(const CBaseBlob& b) const
{
return !(*this == b);
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::IsNull() const
{
return std::all_of(begin(), end(), [](uint8_t e) { return e == 0; });
}
template<uint32_t BITS>
void CBaseBlob<BITS>::SetNull()
{
data.fill(0);
}
template<uint32_t BITS>
std::string CBaseBlob<BITS>::GetHex() const
{
std::stringstream ss;
ss << std::hex;
for (auto it = data.rbegin(); it != data.rend(); ++it)
ss << std::setw(2) << std::setfill('0') << uint32_t(*it);
return ss.str();
}
template<uint32_t BITS>
void CBaseBlob<BITS>::SetHex(const char* psz)
{
SetNull();
// skip leading spaces
while (isspace(*psz))
psz++;
// skip 0x
if (psz[0] == '0' && tolower(psz[1]) == 'x')
psz += 2;
auto b = psz;
// advance to end
while (isxdigit(*psz))
psz++;
--psz;
char buf[3] = {};
auto it = begin();
while (psz >= b && it != end()) {
buf[1] = *psz--;
buf[0] = psz >= b ? *psz-- : '0';
*it++ = std::strtoul(buf, nullptr, 16);
}
}
template<uint32_t BITS>
uint64_t CBaseBlob<BITS>::GetUint64(int pos) const
{
assert((pos + 1) * 8 <= size());
const uint8_t* ptr = begin() + pos * 8;
uint64_t res = 0;
for (int i = 0; i < 8; ++i)
res |= (uint64_t(ptr[i]) << (8 * i));
return res;
}
template<uint32_t BITS>
void CBaseBlob<BITS>::SetHex(const std::string& str)
{
SetHex(str.c_str());
}
template<uint32_t BITS>
std::string CBaseBlob<BITS>::ToString() const
{
return GetHex();
}
template<uint32_t BITS>
uint8_t* CBaseBlob<BITS>::begin() noexcept
{
return data.begin();
}
template<uint32_t BITS>
const uint8_t* CBaseBlob<BITS>::begin() const noexcept
{
return data.begin();
}
template<uint32_t BITS>
uint8_t* CBaseBlob<BITS>::end() noexcept
{
return data.end();
}
template<uint32_t BITS>
const uint8_t* CBaseBlob<BITS>::end() const noexcept
{
return data.end();
}
template<uint32_t BITS>
std::size_t CBaseBlob<BITS>::size() const
{
return data.size();
}
template class CBaseBlob<160>;
template class CBaseBlob<256>;

50
src/claimtrie/blob.h Normal file
View file

@ -0,0 +1,50 @@
#ifndef CLAIMTRIE_BLOB_H
#define CLAIMTRIE_BLOB_H
#include <array>
#include <string>
#include <vector>
/** Template base class for fixed-sized opaque blobs. */
template<uint32_t BITS>
class CBaseBlob
{
std::array<uint8_t, BITS / 8> data;
public:
CBaseBlob();
explicit CBaseBlob(const std::vector<uint8_t>& vec);
CBaseBlob(CBaseBlob&&) = default;
CBaseBlob& operator=(CBaseBlob&&) = default;
CBaseBlob(const CBaseBlob& o);
CBaseBlob& operator=(const CBaseBlob& o);
int Compare(const CBaseBlob& b) const;
bool operator<(const CBaseBlob& b) const;
bool operator==(const CBaseBlob& b) const;
bool operator!=(const CBaseBlob& b) const;
uint8_t* begin() noexcept;
const uint8_t* begin() const noexcept;
uint8_t* end() noexcept;
const uint8_t* end() const noexcept;
std::size_t size() const;
bool IsNull() const;
void SetNull();
std::string GetHex() const;
void SetHex(const char* psz);
void SetHex(const std::string& str);
std::string ToString() const;
uint64_t GetUint64(int pos) const;
};
#endif // CLAIMTRIE_BLOB_H

View file

@ -4,7 +4,7 @@
#include <algorithm> #include <algorithm>
#include <sstream> #include <sstream>
CClaimValue::CClaimValue(CTxOutPoint outPoint, CUint160 claimId, int64_t nAmount, int nHeight, int nValidAtHeight) CClaimValue::CClaimValue(COutPoint outPoint, uint160 claimId, int64_t nAmount, int nHeight, int nValidAtHeight)
: outPoint(std::move(outPoint)), claimId(std::move(claimId)), nAmount(nAmount), nEffectiveAmount(nAmount), nHeight(nHeight), nValidAtHeight(nValidAtHeight) : outPoint(std::move(outPoint)), claimId(std::move(claimId)), nAmount(nAmount), nEffectiveAmount(nAmount), nHeight(nHeight), nValidAtHeight(nValidAtHeight)
{ {
} }
@ -44,7 +44,7 @@ std::string CClaimValue::ToString() const
return ss.str(); return ss.str();
} }
CSupportValue::CSupportValue(CTxOutPoint outPoint, CUint160 supportedClaimId, int64_t nAmount, int nHeight, int nValidAtHeight) CSupportValue::CSupportValue(COutPoint outPoint, uint160 supportedClaimId, int64_t nAmount, int nHeight, int nValidAtHeight)
: outPoint(std::move(outPoint)), supportedClaimId(std::move(supportedClaimId)), nAmount(nAmount), nHeight(nHeight), nValidAtHeight(nValidAtHeight) : outPoint(std::move(outPoint)), supportedClaimId(std::move(supportedClaimId)), nAmount(nAmount), nHeight(nHeight), nValidAtHeight(nValidAtHeight)
{ {
} }
@ -70,7 +70,7 @@ std::string CSupportValue::ToString() const
return ss.str(); return ss.str();
} }
CNameOutPointHeightType::CNameOutPointHeightType(std::string name, CTxOutPoint outPoint, int nValidHeight) CNameOutPointHeightType::CNameOutPointHeightType(std::string name, COutPoint outPoint, int nValidHeight)
: name(std::move(name)), outPoint(std::move(outPoint)), nValidHeight(nValidHeight) : name(std::move(name)), outPoint(std::move(outPoint)), nValidHeight(nValidHeight)
{ {
} }
@ -92,7 +92,7 @@ CClaimSupportToName::CClaimSupportToName(std::string name, int nLastTakeoverHeig
static const CClaimNsupports invalid; static const CClaimNsupports invalid;
const CClaimNsupports& CClaimSupportToName::find(const CUint160& claimId) const const CClaimNsupports& CClaimSupportToName::find(const uint160& claimId) const
{ {
auto it = std::find_if(claimsNsupports.begin(), claimsNsupports.end(), [&claimId](const CClaimNsupports& value) { auto it = std::find_if(claimsNsupports.begin(), claimsNsupports.end(), [&claimId](const CClaimNsupports& value) {
return claimId == value.claim.claimId; return claimId == value.claim.claimId;
@ -117,7 +117,7 @@ bool CClaimNsupports::operator<(const CClaimNsupports& other) const
return claim < other.claim; return claim < other.claim;
} }
CClaimTrieProofNode::CClaimTrieProofNode(std::vector<std::pair<unsigned char, CUint256>> children, bool hasValue, CUint256 valHash) CClaimTrieProofNode::CClaimTrieProofNode(std::vector<std::pair<unsigned char, uint256>> children, bool hasValue, uint256 valHash)
: children(std::move(children)), hasValue(hasValue), valHash(std::move(valHash)) : children(std::move(children)), hasValue(hasValue), valHash(std::move(valHash))
{ {
} }

View file

@ -11,15 +11,15 @@
struct CClaimValue struct CClaimValue
{ {
CTxOutPoint outPoint; COutPoint outPoint;
CUint160 claimId; uint160 claimId;
int64_t nAmount = 0; int64_t nAmount = 0;
int64_t nEffectiveAmount = 0; int64_t nEffectiveAmount = 0;
int nHeight = 0; int nHeight = 0;
int nValidAtHeight = 0; int nValidAtHeight = 0;
CClaimValue() = default; CClaimValue() = default;
CClaimValue(CTxOutPoint outPoint, CUint160 claimId, int64_t nAmount, int nHeight, int nValidAtHeight); CClaimValue(COutPoint outPoint, uint160 claimId, int64_t nAmount, int nHeight, int nValidAtHeight);
CClaimValue(CClaimValue&&) = default; CClaimValue(CClaimValue&&) = default;
CClaimValue(const CClaimValue&) = default; CClaimValue(const CClaimValue&) = default;
@ -35,14 +35,14 @@ struct CClaimValue
struct CSupportValue struct CSupportValue
{ {
CTxOutPoint outPoint; COutPoint outPoint;
CUint160 supportedClaimId; uint160 supportedClaimId;
int64_t nAmount = 0; int64_t nAmount = 0;
int nHeight = 0; int nHeight = 0;
int nValidAtHeight = 0; int nValidAtHeight = 0;
CSupportValue() = default; CSupportValue() = default;
CSupportValue(CTxOutPoint outPoint, CUint160 supportedClaimId, int64_t nAmount, int nHeight, int nValidAtHeight); CSupportValue(COutPoint outPoint, uint160 supportedClaimId, int64_t nAmount, int nHeight, int nValidAtHeight);
CSupportValue(CSupportValue&&) = default; CSupportValue(CSupportValue&&) = default;
CSupportValue(const CSupportValue&) = default; CSupportValue(const CSupportValue&) = default;
@ -61,11 +61,11 @@ typedef std::vector<CSupportValue> supportEntryType;
struct CNameOutPointHeightType struct CNameOutPointHeightType
{ {
std::string name; std::string name;
CTxOutPoint outPoint; COutPoint outPoint;
int nValidHeight = 0; int nValidHeight = 0;
CNameOutPointHeightType() = default; CNameOutPointHeightType() = default;
CNameOutPointHeightType(std::string name, CTxOutPoint outPoint, int nValidHeight); CNameOutPointHeightType(std::string name, COutPoint outPoint, int nValidHeight);
}; };
struct CClaimNsupports struct CClaimNsupports
@ -91,7 +91,7 @@ struct CClaimSupportToName
{ {
CClaimSupportToName(std::string name, int nLastTakeoverHeight, std::vector<CClaimNsupports> claimsNsupports, std::vector<CSupportValue> unmatchedSupports); CClaimSupportToName(std::string name, int nLastTakeoverHeight, std::vector<CClaimNsupports> claimsNsupports, std::vector<CSupportValue> unmatchedSupports);
const CClaimNsupports& find(const CUint160& claimId) const; const CClaimNsupports& find(const uint160& claimId) const;
const CClaimNsupports& find(const std::string& partialId) const; const CClaimNsupports& find(const std::string& partialId) const;
const std::string name; const std::string name;
@ -102,7 +102,7 @@ struct CClaimSupportToName
struct CClaimTrieProofNode struct CClaimTrieProofNode
{ {
CClaimTrieProofNode(std::vector<std::pair<unsigned char, CUint256>> children, bool hasValue, CUint256 valHash); CClaimTrieProofNode(std::vector<std::pair<unsigned char, uint256>> children, bool hasValue, uint256 valHash);
CClaimTrieProofNode() = default; CClaimTrieProofNode() = default;
CClaimTrieProofNode(CClaimTrieProofNode&&) = default; CClaimTrieProofNode(CClaimTrieProofNode&&) = default;
@ -110,9 +110,9 @@ struct CClaimTrieProofNode
CClaimTrieProofNode& operator=(CClaimTrieProofNode&&) = default; CClaimTrieProofNode& operator=(CClaimTrieProofNode&&) = default;
CClaimTrieProofNode& operator=(const CClaimTrieProofNode&) = default; CClaimTrieProofNode& operator=(const CClaimTrieProofNode&) = default;
std::vector<std::pair<unsigned char, CUint256>> children; std::vector<std::pair<unsigned char, uint256>> children;
bool hasValue; bool hasValue;
CUint256 valHash; uint256 valHash;
}; };
struct CClaimTrieProof struct CClaimTrieProof
@ -123,11 +123,11 @@ struct CClaimTrieProof
CClaimTrieProof& operator=(CClaimTrieProof&&) = default; CClaimTrieProof& operator=(CClaimTrieProof&&) = default;
CClaimTrieProof& operator=(const CClaimTrieProof&) = default; CClaimTrieProof& operator=(const CClaimTrieProof&) = default;
std::vector<std::pair<bool, CUint256>> pairs; std::vector<std::pair<bool, uint256>> pairs;
std::vector<CClaimTrieProofNode> nodes; std::vector<CClaimTrieProofNode> nodes;
int nHeightOfLastTakeover = 0; int nHeightOfLastTakeover = 0;
bool hasValue = false; bool hasValue = false;
CTxOutPoint outPoint; COutPoint outPoint;
}; };
#endif // CLAIMTRIE_DATA_H #endif // CLAIMTRIE_DATA_H

View file

@ -198,7 +198,7 @@ bool CClaimTrieCacheNormalizationFork::decrementBlock()
return ret; return ret;
} }
bool CClaimTrieCacheNormalizationFork::getProofForName(const std::string& name, const CUint160& claim, CClaimTrieProof& proof) bool CClaimTrieCacheNormalizationFork::getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof)
{ {
return CClaimTrieCacheExpirationFork::getProofForName(normalizeClaimName(name), claim, proof); return CClaimTrieCacheExpirationFork::getProofForName(normalizeClaimName(name), claim, proof);
} }
@ -213,7 +213,7 @@ CClaimSupportToName CClaimTrieCacheNormalizationFork::getClaimsForName(const std
return CClaimTrieCacheExpirationFork::getClaimsForName(normalizeClaimName(name)); return CClaimTrieCacheExpirationFork::getClaimsForName(normalizeClaimName(name));
} }
int CClaimTrieCacheNormalizationFork::getDelayForName(const std::string& name, const CUint160& claimId) const int CClaimTrieCacheNormalizationFork::getDelayForName(const std::string& name, const uint160& claimId) const
{ {
return CClaimTrieCacheExpirationFork::getDelayForName(normalizeClaimName(name), claimId); return CClaimTrieCacheExpirationFork::getDelayForName(normalizeClaimName(name), claimId);
} }
@ -227,10 +227,10 @@ CClaimTrieCacheHashFork::CClaimTrieCacheHashFork(CClaimTrie* base) : CClaimTrieC
{ {
} }
static const auto leafHash = CUint256S("0000000000000000000000000000000000000000000000000000000000000002"); static const auto leafHash = uint256S("0000000000000000000000000000000000000000000000000000000000000002");
static const auto emptyHash = CUint256S("0000000000000000000000000000000000000000000000000000000000000003"); static const auto emptyHash = uint256S("0000000000000000000000000000000000000000000000000000000000000003");
CUint256 ComputeMerkleRoot(std::vector<CUint256> hashes) uint256 ComputeMerkleRoot(std::vector<uint256> hashes)
{ {
while (hashes.size() > 1) { while (hashes.size() > 1) {
if (hashes.size() & 1) if (hashes.size() & 1)
@ -242,23 +242,23 @@ CUint256 ComputeMerkleRoot(std::vector<CUint256> hashes)
hashes.resize(hashes.size() / 2); hashes.resize(hashes.size() / 2);
} }
return hashes.empty() ? CUint256{} : hashes[0]; return hashes.empty() ? uint256{} : hashes[0];
} }
CUint256 CClaimTrieCacheHashFork::computeNodeHash(const std::string& name, int takeoverHeight) uint256 CClaimTrieCacheHashFork::computeNodeHash(const std::string& name, int takeoverHeight)
{ {
if (nNextHeight < base->nAllClaimsInMerkleForkHeight) if (nNextHeight < base->nAllClaimsInMerkleForkHeight)
return CClaimTrieCacheNormalizationFork::computeNodeHash(name, takeoverHeight); return CClaimTrieCacheNormalizationFork::computeNodeHash(name, takeoverHeight);
std::vector<CUint256> childHashes; std::vector<uint256> childHashes;
childHashQuery << name >> [&childHashes](std::string, CUint256 hash) { childHashQuery << name >> [&childHashes](std::string, uint256 hash) {
childHashes.push_back(std::move(hash)); childHashes.push_back(std::move(hash));
}; };
childHashQuery++; childHashQuery++;
std::vector<CUint256> claimHashes; std::vector<uint256> claimHashes;
//if (takeoverHeight > 0) { //if (takeoverHeight > 0) {
CTxOutPoint p; COutPoint p;
for (auto &&row: claimHashQuery << nNextHeight << name) { for (auto &&row: claimHashQuery << nNextHeight << name) {
row >> p.hash >> p.n; row >> p.hash >> p.n;
claimHashes.push_back(getValueHash(p, takeoverHeight)); claimHashes.push_back(getValueHash(p, takeoverHeight));
@ -272,14 +272,14 @@ CUint256 CClaimTrieCacheHashFork::computeNodeHash(const std::string& name, int t
return Hash(left.begin(), left.end(), right.begin(), right.end()); return Hash(left.begin(), left.end(), right.begin(), right.end());
} }
std::vector<CUint256> ComputeMerklePath(const std::vector<CUint256>& hashes, uint32_t idx) std::vector<uint256> ComputeMerklePath(const std::vector<uint256>& hashes, uint32_t idx)
{ {
uint32_t count = 0; uint32_t count = 0;
int matchlevel = -1; int matchlevel = -1;
bool matchh = false; bool matchh = false;
CUint256 inner[32], h; uint256 inner[32], h;
const uint32_t one = 1; const uint32_t one = 1;
std::vector<CUint256> res; std::vector<uint256> res;
const auto iterateInner = [&](int& level) { const auto iterateInner = [&](int& level) {
for (; !(count & (one << level)); level++) { for (; !(count & (one << level)); level++) {
@ -329,12 +329,12 @@ std::vector<CUint256> ComputeMerklePath(const std::vector<CUint256>& hashes, uin
extern const std::string proofClaimQuery_s; extern const std::string proofClaimQuery_s;
bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, const CUint160& claim, CClaimTrieProof& proof) bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof)
{ {
if (nNextHeight < base->nAllClaimsInMerkleForkHeight) if (nNextHeight < base->nAllClaimsInMerkleForkHeight)
return CClaimTrieCacheNormalizationFork::getProofForName(name, claim, proof); return CClaimTrieCacheNormalizationFork::getProofForName(name, claim, proof);
auto fillPairs = [&proof](const std::vector<CUint256>& hashes, uint32_t idx) { auto fillPairs = [&proof](const std::vector<uint256>& hashes, uint32_t idx) {
auto partials = ComputeMerklePath(hashes, idx); auto partials = ComputeMerklePath(hashes, idx);
for (int i = partials.size() - 1; i >= 0; --i) for (int i = partials.size() - 1; i >= 0; --i)
proof.pairs.emplace_back((idx >> i) & 1, partials[i]); proof.pairs.emplace_back((idx >> i) & 1, partials[i]);
@ -348,10 +348,10 @@ bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, const CUi
int takeoverHeight; int takeoverHeight;
row >> key >> takeoverHeight; row >> key >> takeoverHeight;
uint32_t nextCurrentIdx = 0; uint32_t nextCurrentIdx = 0;
std::vector<CUint256> childHashes; std::vector<uint256> childHashes;
for (auto&& child : childHashQuery << key) { for (auto&& child : childHashQuery << key) {
std::string childKey; std::string childKey;
CUint256 childHash; uint256 childHash;
child >> childKey >> childHash; child >> childKey >> childHash;
if (name.find(childKey) == 0) if (name.find(childKey) == 0)
nextCurrentIdx = uint32_t(childHashes.size()); nextCurrentIdx = uint32_t(childHashes.size());
@ -359,11 +359,11 @@ bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, const CUi
} }
childHashQuery++; childHashQuery++;
std::vector<CUint256> claimHashes; std::vector<uint256> claimHashes;
uint32_t claimIdx = 0; uint32_t claimIdx = 0;
for (auto&& child: claimHashQuery << nNextHeight << key) { for (auto&& child: claimHashQuery << nNextHeight << key) {
CTxOutPoint childOutPoint; COutPoint childOutPoint;
CUint160 childClaimID; uint160 childClaimID;
child >> childOutPoint.hash >> childOutPoint.n >> childClaimID; child >> childOutPoint.hash >> childOutPoint.n >> childClaimID;
if (childClaimID == claim && key == name) { if (childClaimID == claim && key == name) {
claimIdx = uint32_t(claimHashes.size()); claimIdx = uint32_t(claimHashes.size());

View file

@ -37,13 +37,13 @@ public:
bool incrementBlock() override; bool incrementBlock() override;
bool decrementBlock() override; bool decrementBlock() override;
bool getProofForName(const std::string& name, const CUint160& claim, CClaimTrieProof& proof) override; bool getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof) override;
bool getInfoForName(const std::string& name, CClaimValue& claim, int heightOffset = 0) const override; bool getInfoForName(const std::string& name, CClaimValue& claim, int heightOffset = 0) const override;
CClaimSupportToName getClaimsForName(const std::string& name) const override; CClaimSupportToName getClaimsForName(const std::string& name) const override;
std::string adjustNameForValidHeight(const std::string& name, int validHeight) const override; std::string adjustNameForValidHeight(const std::string& name, int validHeight) const override;
protected: protected:
int getDelayForName(const std::string& name, const CUint160& claimId) const override; int getDelayForName(const std::string& name, const uint160& claimId) const override;
private: private:
bool normalizeAllNamesInTrieIfNecessary(); bool normalizeAllNamesInTrieIfNecessary();
@ -55,14 +55,14 @@ class CClaimTrieCacheHashFork : public CClaimTrieCacheNormalizationFork
public: public:
explicit CClaimTrieCacheHashFork(CClaimTrie* base); explicit CClaimTrieCacheHashFork(CClaimTrie* base);
bool getProofForName(const std::string& name, const CUint160& claim, CClaimTrieProof& proof) override; bool getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof) override;
void initializeIncrement() override; void initializeIncrement() override;
bool finalizeDecrement() override; bool finalizeDecrement() override;
bool allowSupportMetadata() const; bool allowSupportMetadata() const;
protected: protected:
CUint256 computeNodeHash(const std::string& name, int takeoverHeight) override; uint256 computeNodeHash(const std::string& name, int takeoverHeight) override;
}; };
typedef CClaimTrieCacheHashFork CClaimTrieCache; typedef CClaimTrieCacheHashFork CClaimTrieCache;

View file

@ -2,9 +2,9 @@
#include <hashes.h> #include <hashes.h>
// Bitcoin doubles hash // Bitcoin doubles hash
CUint256 CalcHash(SHA256_CTX* sha) uint256 CalcHash(SHA256_CTX* sha)
{ {
CUint256 result; uint256 result;
SHA256_Final(result.begin(), sha); SHA256_Final(result.begin(), sha);
SHA256_Init(sha); SHA256_Init(sha);
SHA256_Update(sha, result.begin(), result.size()); SHA256_Update(sha, result.begin(), result.size());

View file

@ -6,10 +6,10 @@
#include <uints.h> #include <uints.h>
CUint256 CalcHash(SHA256_CTX* sha); uint256 CalcHash(SHA256_CTX* sha);
template<typename TIterator, typename... Args> template<typename TIterator, typename... Args>
CUint256 CalcHash(SHA256_CTX* sha, TIterator begin, TIterator end, Args... args) uint256 CalcHash(SHA256_CTX* sha, TIterator begin, TIterator end, Args... args)
{ {
static uint8_t blank; static uint8_t blank;
SHA256_Update(sha, begin == end ? &blank : (uint8_t*)&begin[0], std::distance(begin, end) * sizeof(begin[0])); SHA256_Update(sha, begin == end ? &blank : (uint8_t*)&begin[0], std::distance(begin, end) * sizeof(begin[0]));
@ -17,7 +17,7 @@ CUint256 CalcHash(SHA256_CTX* sha, TIterator begin, TIterator end, Args... args)
} }
template<typename TIterator, typename... Args> template<typename TIterator, typename... Args>
CUint256 Hash(TIterator begin, TIterator end, Args... args) uint256 Hash(TIterator begin, TIterator end, Args... args)
{ {
static_assert((sizeof...(args) & 1) != 1, "Parameters should be even number"); static_assert((sizeof...(args) & 1) != 1, "Parameters should be even number");
SHA256_CTX sha; SHA256_CTX sha;

View file

@ -1,6 +1,7 @@
%module(directors="1") libclaimtrie %module(directors="1") libclaimtrie
%{ %{
#include "blob.h"
#include "uints.h" #include "uints.h"
#include "txoutpoint.h" #include "txoutpoint.h"
#include "data.h" #include "data.h"
@ -13,6 +14,7 @@
%include stl.i %include stl.i
%include stdint.i %include stdint.i
%include std_array.i
%include std_pair.i %include std_pair.i
%apply int& OUTPUT { int& nValidAtHeight }; %apply int& OUTPUT { int& nValidAtHeight };
@ -22,8 +24,15 @@
%ignore CClaimTrieProof(CClaimTrieProof &&); %ignore CClaimTrieProof(CClaimTrieProof &&);
%ignore CClaimTrieProofNode(CClaimTrieProofNode &&); %ignore CClaimTrieProofNode(CClaimTrieProofNode &&);
%ignore CClaimValue(CClaimValue &&); %ignore CClaimValue(CClaimValue &&);
%ignore COutPoint(COutPoint &&);
%ignore CSupportValue(CSupportValue &&); %ignore CSupportValue(CSupportValue &&);
%ignore CTxOutPoint(CTxOutPoint &&); %ignore uint160(uint160 &&);
%ignore uint256(uint256 &&);
%include "blob.h"
%template(blob160) CBaseBlob<160>;
%template(blob256) CBaseBlob<256>;
%include "uints.h" %include "uints.h"
%include "txoutpoint.h" %include "txoutpoint.h"
@ -34,20 +43,16 @@
%include "trie.h" %include "trie.h"
%include "forks.h" %include "forks.h"
%template(CUint160) CBaseBlob<160>;
%template(CUint256) CBaseBlob<256>;
%template(uint8vec) std::vector<uint8_t>;
%template(claimEntryType) std::vector<CClaimValue>; %template(claimEntryType) std::vector<CClaimValue>;
%template(supportEntryType) std::vector<CSupportValue>; %template(supportEntryType) std::vector<CSupportValue>;
%template(claimsNsupports) std::vector<CClaimNsupports>; %template(claimsNsupports) std::vector<CClaimNsupports>;
%template(proofPair) std::pair<bool, CUint256>; %template(proofPair) std::pair<bool, uint256>;
%template(proofNodePair) std::pair<unsigned char, CUint256>; %template(proofNodePair) std::pair<unsigned char, uint256>;
%template(proofNodes) std::vector<CClaimTrieProofNode>; %template(proofNodes) std::vector<CClaimTrieProofNode>;
%template(proofPairs) std::vector<std::pair<bool, CUint256>>; %template(proofPairs) std::vector<std::pair<bool, uint256>>;
%template(proofNodeChildren) std::vector<std::pair<unsigned char, CUint256>>; %template(proofNodeChildren) std::vector<std::pair<unsigned char, uint256>>;
%inline %{ %inline %{
struct CIterateCallback { struct CIterateCallback {

View file

@ -13,9 +13,9 @@ class CacheIterateCallback(CIterateCallback):
class TestClaimTrieTypes(unittest.TestCase): class TestClaimTrieTypes(unittest.TestCase):
def setUp(self): def setUp(self):
self.uint256s = "1234567890987654321012345678909876543210123456789098765432101234" self.uint256s = "1234567890987654321012345678909876543210123456789098765432101234"
self.uint160 = CUint160S("1234567890987654321012345678909876543210") self.uint160 = uint160S("1234567890987654321012345678909876543210")
self.uint = CUint256S(self.uint256s) self.uint = uint256S(self.uint256s)
self.txp = CTxOutPoint(self.uint, 1) self.txp = COutPoint(self.uint, 1)
def assertClaimEqual(self, claim, txo, cid, amount, effe, height, validHeight, msg): def assertClaimEqual(self, claim, txo, cid, amount, effe, height, validHeight, msg):
self.assertEqual(claim.outPoint, txo, msg) self.assertEqual(claim.outPoint, txo, msg)
@ -34,14 +34,14 @@ class TestClaimTrieTypes(unittest.TestCase):
def test_uint256(self): def test_uint256(self):
uint = self.uint uint = self.uint
self.assertFalse(uint.IsNull(), "incorrect CUint256S or CBaseBlob::IsNull") self.assertFalse(uint.IsNull(), "incorrect uint256S or CBaseBlob::IsNull")
self.assertEqual(uint.GetHex(), self.uint256s, "incorrect CBaseBlob::GetHex") self.assertEqual(uint.GetHex(), self.uint256s, "incorrect CBaseBlob::GetHex")
self.assertEqual(uint.GetHex(), uint.ToString(), "incorrect CBaseBlob::ToString") self.assertEqual(uint.GetHex(), uint.ToString(), "incorrect CBaseBlob::ToString")
self.assertEqual(uint.size(), 32, "incorrect CBaseBlob::size") self.assertEqual(uint.size(), 32, "incorrect CBaseBlob::size")
copy = CUint256() copy = uint256()
self.assertNotEqual(copy, uint, "incorrect CBaseBlob::operator!=") self.assertNotEqual(copy, uint, "incorrect CBaseBlob::operator!=")
self.assertTrue(copy.IsNull(), "incorrect CBaseBlob::IsNull") self.assertTrue(copy.IsNull(), "incorrect CBaseBlob::IsNull")
copy = CUint256(uint) copy = uint256(uint)
self.assertEqual(copy, uint, "incorrect CBaseBlob::operator==") self.assertEqual(copy, uint, "incorrect CBaseBlob::operator==")
copy.SetNull() copy.SetNull()
self.assertTrue(copy.IsNull()), "incorrect CBaseBlob::SetNull" self.assertTrue(copy.IsNull()), "incorrect CBaseBlob::SetNull"
@ -49,14 +49,14 @@ class TestClaimTrieTypes(unittest.TestCase):
def test_txoupoint(self): def test_txoupoint(self):
txp = self.txp txp = self.txp
uint = self.uint uint = self.uint
self.assertEqual(txp.hash, uint, "incorrect CTxOutPoint::CTxOutPoint") self.assertEqual(txp.hash, uint, "incorrect COutPoint::COutPoint")
self.assertEqual(txp.n, 1, "incorrect CTxOutPoint::CTxOutPoint") self.assertEqual(txp.n, 1, "incorrect COutPoint::COutPoint")
self.assertFalse(txp.IsNull(), "incorrect CTxOutPoint::IsNull") self.assertFalse(txp.IsNull(), "incorrect COutPoint::IsNull")
pcopy = CTxOutPoint() pcopy = COutPoint()
self.assertTrue(pcopy.IsNull(), "incorrect CTxOutPoint::IsNull") self.assertTrue(pcopy.IsNull(), "incorrect COutPoint::IsNull")
self.assertEqual(pcopy.hash, CUint256(), "incorrect CTxOutPoint::CTxOutPoint") self.assertEqual(pcopy.hash, uint256(), "incorrect COutPoint::COutPoint")
self.assertNotEqual(pcopy, txp, "incorrect CTxOutPoint::operator!=") self.assertNotEqual(pcopy, txp, "incorrect COutPoint::operator!=")
self.assertIn(uint.ToString()[:10], txp.ToString(), "incorrect CTxOutPoint::ToString") self.assertIn(uint.ToString()[:10], txp.ToString(), "incorrect COutPoint::ToString")
def test_claim(self): def test_claim(self):
txp = self.txp txp = self.txp
@ -88,7 +88,7 @@ class TestClaimTrieTypes(unittest.TestCase):
nValidAtHeight = -1 nValidAtHeight = -1
# add second claim # add second claim
txp.n = 2 txp.n = 2
uint1601 = CUint160S("1234567890987654321012345678909876543211") uint1601 = uint160S("1234567890987654321012345678909876543211")
self.assertTrue(cache.addClaim("test", txp, uint1601, 20, 1, 1), "incorrect CClaimtrieCache::addClaim") self.assertTrue(cache.addClaim("test", txp, uint1601, 20, 1, 1), "incorrect CClaimtrieCache::addClaim")
result, nValidAtHeight = cache.haveClaimInQueue("test", txp) result, nValidAtHeight = cache.haveClaimInQueue("test", txp)
self.assertTrue(result, "incorrect CClaimTrieCache::haveClaimInQueue") self.assertTrue(result, "incorrect CClaimTrieCache::haveClaimInQueue")

View file

@ -10,19 +10,19 @@
namespace sqlite namespace sqlite
{ {
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const CUint160& val) { inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const uint160& val) {
return sqlite3_bind_blob(stmt, inx, val.begin(), int(val.size()), SQLITE_STATIC); return sqlite3_bind_blob(stmt, inx, val.begin(), int(val.size()), SQLITE_STATIC);
} }
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const CUint256& val) { inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const uint256& val) {
return sqlite3_bind_blob(stmt, inx, val.begin(), int(val.size()), SQLITE_STATIC); return sqlite3_bind_blob(stmt, inx, val.begin(), int(val.size()), SQLITE_STATIC);
} }
inline void store_result_in_db(sqlite3_context* db, const CUint160& val) { inline void store_result_in_db(sqlite3_context* db, const uint160& val) {
sqlite3_result_blob(db, val.begin(), int(val.size()), SQLITE_TRANSIENT); sqlite3_result_blob(db, val.begin(), int(val.size()), SQLITE_TRANSIENT);
} }
inline void store_result_in_db(sqlite3_context* db, const CUint256& val) { inline void store_result_in_db(sqlite3_context* db, const uint256& val) {
sqlite3_result_blob(db, val.begin(), int(val.size()), SQLITE_TRANSIENT); sqlite3_result_blob(db, val.begin(), int(val.size()), SQLITE_TRANSIENT);
} }
} }
@ -31,11 +31,14 @@
namespace sqlite namespace sqlite
{ {
template<>
struct has_sqlite_type<uint256, SQLITE_BLOB, void> : std::true_type {};
template<> template<>
struct has_sqlite_type<CUint160, SQLITE_BLOB, void> : std::true_type {}; struct has_sqlite_type<uint160, SQLITE_BLOB, void> : std::true_type {};
inline CUint160 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<CUint160>) {
CUint160 ret; inline uint160 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<uint160>) {
uint160 ret;
auto ptr = sqlite3_column_blob(stmt, inx); auto ptr = sqlite3_column_blob(stmt, inx);
if (!ptr) return ret; if (!ptr) return ret;
int bytes = sqlite3_column_bytes(stmt, inx); int bytes = sqlite3_column_bytes(stmt, inx);
@ -44,10 +47,8 @@ namespace sqlite
return ret; return ret;
} }
template<> inline uint256 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<uint256>) {
struct has_sqlite_type<CUint256, SQLITE_BLOB, void> : std::true_type {}; uint256 ret;
inline CUint256 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<CUint256>) {
CUint256 ret;
auto ptr = sqlite3_column_blob(stmt, inx); auto ptr = sqlite3_column_blob(stmt, inx);
if (!ptr) return ret; if (!ptr) return ret;
int bytes = sqlite3_column_bytes(stmt, inx); int bytes = sqlite3_column_bytes(stmt, inx);

View file

@ -10,7 +10,7 @@
#define logPrint CLogPrint::global() #define logPrint CLogPrint::global()
static const auto one = CUint256S("0000000000000000000000000000000000000000000000000000000000000001"); static const auto one = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
std::vector<unsigned char> heightToVch(int n) std::vector<unsigned char> heightToVch(int n)
{ {
@ -22,7 +22,7 @@ std::vector<unsigned char> heightToVch(int n)
return vchHeight; return vchHeight;
} }
CUint256 getValueHash(const CTxOutPoint& outPoint, int nHeightOfLastTakeover) uint256 getValueHash(const COutPoint& outPoint, int nHeightOfLastTakeover)
{ {
auto hash1 = Hash(outPoint.hash.begin(), outPoint.hash.end()); auto hash1 = Hash(outPoint.hash.begin(), outPoint.hash.end());
auto snOut = std::to_string(outPoint.n); auto snOut = std::to_string(outPoint.n);
@ -134,7 +134,7 @@ bool CClaimTrie::empty()
return count == 0; return count == 0;
} }
bool CClaimTrieCacheBase::haveClaim(const std::string& name, const CTxOutPoint& outPoint) const bool CClaimTrieCacheBase::haveClaim(const std::string& name, const COutPoint& outPoint) const
{ {
auto query = db << "SELECT 1 FROM claim WHERE nodeName = ?1 AND txID = ?2 AND txN = ?3 " auto query = db << "SELECT 1 FROM claim WHERE nodeName = ?1 AND txID = ?2 AND txN = ?3 "
"AND activationHeight < ?4 AND expirationHeight >= ?4 LIMIT 1" "AND activationHeight < ?4 AND expirationHeight >= ?4 LIMIT 1"
@ -142,7 +142,7 @@ bool CClaimTrieCacheBase::haveClaim(const std::string& name, const CTxOutPoint&
return query.begin() != query.end(); return query.begin() != query.end();
} }
bool CClaimTrieCacheBase::haveSupport(const std::string& name, const CTxOutPoint& outPoint) const bool CClaimTrieCacheBase::haveSupport(const std::string& name, const COutPoint& outPoint) const
{ {
auto query = db << "SELECT 1 FROM support WHERE nodeName = ?1 AND txID = ?2 AND txN = ?3 " auto query = db << "SELECT 1 FROM support WHERE nodeName = ?1 AND txID = ?2 AND txN = ?3 "
"AND activationHeight < ?4 AND expirationHeight >= ?4 LIMIT 1" "AND activationHeight < ?4 AND expirationHeight >= ?4 LIMIT 1"
@ -165,7 +165,7 @@ supportEntryType CClaimTrieCacheBase::getSupportsForName(const std::string& name
return ret; return ret;
} }
bool CClaimTrieCacheBase::haveClaimInQueue(const std::string& name, const CTxOutPoint& outPoint, int& nValidAtHeight) const bool CClaimTrieCacheBase::haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const
{ {
auto query = db << "SELECT activationHeight FROM claim WHERE nodeName = ? AND txID = ? AND txN = ? " auto query = db << "SELECT activationHeight FROM claim WHERE nodeName = ? AND txID = ? AND txN = ? "
"AND activationHeight >= ? AND expirationHeight >= activationHeight LIMIT 1" "AND activationHeight >= ? AND expirationHeight >= activationHeight LIMIT 1"
@ -177,7 +177,7 @@ bool CClaimTrieCacheBase::haveClaimInQueue(const std::string& name, const CTxOut
return false; return false;
} }
bool CClaimTrieCacheBase::haveSupportInQueue(const std::string& name, const CTxOutPoint& outPoint, int& nValidAtHeight) const bool CClaimTrieCacheBase::haveSupportInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const
{ {
auto query = db << "SELECT activationHeight FROM support WHERE nodeName = ? AND txID = ? AND txN = ? " auto query = db << "SELECT activationHeight FROM support WHERE nodeName = ? AND txID = ? AND txN = ? "
"AND activationHeight >= ? AND expirationHeight >= activationHeight LIMIT 1" "AND activationHeight >= ? AND expirationHeight >= activationHeight LIMIT 1"
@ -364,7 +364,7 @@ bool CClaimTrieCacheBase::getInfoForName(const std::string& name, CClaimValue& c
CClaimSupportToName CClaimTrieCacheBase::getClaimsForName(const std::string& name) const CClaimSupportToName CClaimTrieCacheBase::getClaimsForName(const std::string& name) const
{ {
CUint160 claimId; uint160 claimId;
int nLastTakeoverHeight = 0; int nLastTakeoverHeight = 0;
getLastTakeoverForName(name, claimId, nLastTakeoverHeight); getLastTakeoverForName(name, claimId, nLastTakeoverHeight);
@ -399,18 +399,18 @@ CClaimSupportToName CClaimTrieCacheBase::getClaimsForName(const std::string& nam
return {name, nLastTakeoverHeight, std::move(claimsNsupports), std::move(supports)}; return {name, nLastTakeoverHeight, std::move(claimsNsupports), std::move(supports)};
} }
void completeHash(CUint256& partialHash, const std::string& key, int to) void completeHash(uint256& partialHash, const std::string& key, int to)
{ {
for (auto it = key.rbegin(); std::distance(it, key.rend()) > to + 1; ++it) for (auto it = key.rbegin(); std::distance(it, key.rend()) > to + 1; ++it)
partialHash = Hash(it, it + 1, partialHash.begin(), partialHash.end()); partialHash = Hash(it, it + 1, partialHash.begin(), partialHash.end());
} }
CUint256 CClaimTrieCacheBase::computeNodeHash(const std::string& name, int takeoverHeight) uint256 CClaimTrieCacheBase::computeNodeHash(const std::string& name, int takeoverHeight)
{ {
const auto pos = name.size(); const auto pos = name.size();
std::vector<uint8_t> vchToHash; std::vector<uint8_t> vchToHash;
// we have to free up the hash query so it can be reused by a child // we have to free up the hash query so it can be reused by a child
childHashQuery << name >> [&vchToHash, pos](std::string name, CUint256 hash) { childHashQuery << name >> [&vchToHash, pos](std::string name, uint256 hash) {
completeHash(hash, name, pos); completeHash(hash, name, pos);
vchToHash.push_back(name[pos]); vchToHash.push_back(name[pos]);
vchToHash.insert(vchToHash.end(), hash.begin(), hash.end()); vchToHash.insert(vchToHash.end(), hash.begin(), hash.end());
@ -435,7 +435,7 @@ bool CClaimTrieCacheBase::checkConsistency()
"FROM takeover t WHERE t.name = n.name ORDER BY t.height DESC LIMIT 1), 0) FROM node n"; "FROM takeover t WHERE t.name = n.name ORDER BY t.height DESC LIMIT 1), 0) FROM node n";
for (auto&& row: query) { for (auto&& row: query) {
std::string name; std::string name;
CUint256 hash; uint256 hash;
int takeoverHeight; int takeoverHeight;
row >> name >> hash >> takeoverHeight; row >> name >> hash >> takeoverHeight;
auto computedHash = computeNodeHash(name, takeoverHeight); auto computedHash = computeNodeHash(name, takeoverHeight);
@ -445,7 +445,7 @@ bool CClaimTrieCacheBase::checkConsistency()
return true; return true;
} }
bool CClaimTrieCacheBase::validateDb(int height, const CUint256& rootHash) bool CClaimTrieCacheBase::validateDb(int height, const uint256& rootHash)
{ {
base->nNextHeight = nNextHeight = height + 1; base->nNextHeight = nNextHeight = height + 1;
@ -523,12 +523,12 @@ int CClaimTrieCacheBase::expirationTime() const
return base->nOriginalClaimExpirationTime; return base->nOriginalClaimExpirationTime;
} }
CUint256 CClaimTrieCacheBase::getMerkleHash() uint256 CClaimTrieCacheBase::getMerkleHash()
{ {
ensureTreeStructureIsUpToDate(); ensureTreeStructureIsUpToDate();
CUint256 hash; uint256 hash;
db << "SELECT hash FROM node WHERE name = x''" db << "SELECT hash FROM node WHERE name = x''"
>> [&hash](std::unique_ptr<CUint256> rootHash) { >> [&hash](std::unique_ptr<uint256> rootHash) {
if (rootHash) if (rootHash)
hash = std::move(*rootHash); hash = std::move(*rootHash);
}; };
@ -547,13 +547,13 @@ CUint256 CClaimTrieCacheBase::getMerkleHash()
return hash; return hash;
} }
bool CClaimTrieCacheBase::getLastTakeoverForName(const std::string& name, CUint160& claimId, int& takeoverHeight) const bool CClaimTrieCacheBase::getLastTakeoverForName(const std::string& name, uint160& claimId, int& takeoverHeight) const
{ {
auto query = db << "SELECT t.height, t.claimID FROM takeover t " auto query = db << "SELECT t.height, t.claimID FROM takeover t "
"WHERE t.name = ?1 ORDER BY t.height DESC LIMIT 1" << name; "WHERE t.name = ?1 ORDER BY t.height DESC LIMIT 1" << name;
auto it = query.begin(); auto it = query.begin();
if (it != query.end()) { if (it != query.end()) {
std::unique_ptr<CUint160> claimIdOrNull; std::unique_ptr<uint160> claimIdOrNull;
*it >> takeoverHeight >> claimIdOrNull; *it >> takeoverHeight >> claimIdOrNull;
if (claimIdOrNull) { if (claimIdOrNull) {
claimId = *claimIdOrNull; claimId = *claimIdOrNull;
@ -563,7 +563,7 @@ bool CClaimTrieCacheBase::getLastTakeoverForName(const std::string& name, CUint1
return false; return false;
} }
bool CClaimTrieCacheBase::addClaim(const std::string& name, const CTxOutPoint& outPoint, const CUint160& claimId, bool CClaimTrieCacheBase::addClaim(const std::string& name, const COutPoint& outPoint, const uint160& claimId,
int64_t nAmount, int nHeight, int nValidHeight) int64_t nAmount, int nHeight, int nValidHeight)
{ {
ensureTransacting(); ensureTransacting();
@ -595,7 +595,7 @@ bool CClaimTrieCacheBase::addClaim(const std::string& name, const CTxOutPoint& o
return true; return true;
} }
bool CClaimTrieCacheBase::addSupport(const std::string& name, const CTxOutPoint& outPoint, const CUint160& supportedClaimId, bool CClaimTrieCacheBase::addSupport(const std::string& name, const COutPoint& outPoint, const uint160& supportedClaimId,
int64_t nAmount, int nHeight, int nValidHeight) int64_t nAmount, int nHeight, int nValidHeight)
{ {
ensureTransacting(); ensureTransacting();
@ -616,7 +616,7 @@ bool CClaimTrieCacheBase::addSupport(const std::string& name, const CTxOutPoint&
return true; return true;
} }
bool CClaimTrieCacheBase::removeClaim(const CUint160& claimId, const CTxOutPoint& outPoint, std::string& nodeName, int& validHeight) bool CClaimTrieCacheBase::removeClaim(const uint160& claimId, const COutPoint& outPoint, std::string& nodeName, int& validHeight)
{ {
ensureTransacting(); ensureTransacting();
@ -668,7 +668,7 @@ bool CClaimTrieCacheBase::removeClaim(const CUint160& claimId, const CTxOutPoint
return true; return true;
} }
bool CClaimTrieCacheBase::removeSupport(const CTxOutPoint& outPoint, std::string& nodeName, int& validHeight) bool CClaimTrieCacheBase::removeSupport(const COutPoint& outPoint, std::string& nodeName, int& validHeight)
{ {
ensureTransacting(); ensureTransacting();
@ -715,7 +715,7 @@ bool CClaimTrieCacheBase::incrementBlock()
CClaimValue candidateValue; CClaimValue candidateValue;
auto hasCandidate = getInfoForName(nameWithTakeover, candidateValue, 1); auto hasCandidate = getInfoForName(nameWithTakeover, candidateValue, 1);
// now that they're all in get the winner: // now that they're all in get the winner:
CUint160 existingID; uint160 existingID;
int existingHeight = 0; int existingHeight = 0;
auto hasCurrentWinner = getLastTakeoverForName(nameWithTakeover, existingID, existingHeight); auto hasCurrentWinner = getLastTakeoverForName(nameWithTakeover, existingID, existingHeight);
// we have a takeover if we had a winner and its changing or we never had a winner // we have a takeover if we had a winner and its changing or we never had a winner
@ -799,9 +799,9 @@ bool CClaimTrieCacheBase::finalizeDecrement()
return true; return true;
} }
int CClaimTrieCacheBase::getDelayForName(const std::string& name, const CUint160& claimId) const int CClaimTrieCacheBase::getDelayForName(const std::string& name, const uint160& claimId) const
{ {
CUint160 winningClaimId; uint160 winningClaimId;
int winningTakeoverHeight; int winningTakeoverHeight;
auto hasCurrentWinner = getLastTakeoverForName(name, winningClaimId, winningTakeoverHeight); auto hasCurrentWinner = getLastTakeoverForName(name, winningClaimId, winningTakeoverHeight);
if (hasCurrentWinner && winningClaimId == claimId) { if (hasCurrentWinner && winningClaimId == claimId) {
@ -824,7 +824,7 @@ std::string CClaimTrieCacheBase::adjustNameForValidHeight(const std::string& nam
return name; return name;
} }
bool CClaimTrieCacheBase::getProofForName(const std::string& name, const CUint160& finalClaim, CClaimTrieProof& proof) bool CClaimTrieCacheBase::getProofForName(const std::string& name, const uint160& finalClaim, CClaimTrieProof& proof)
{ {
// cache the parent nodes // cache the parent nodes
getMerkleHash(); getMerkleHash();
@ -835,25 +835,25 @@ bool CClaimTrieCacheBase::getProofForName(const std::string& name, const CUint16
int takeoverHeight; int takeoverHeight;
row >> key >> takeoverHeight; row >> key >> takeoverHeight;
bool fNodeHasValue = getInfoForName(key, claim); bool fNodeHasValue = getInfoForName(key, claim);
CUint256 valueHash; uint256 valueHash;
if (fNodeHasValue) if (fNodeHasValue)
valueHash = getValueHash(claim.outPoint, takeoverHeight); valueHash = getValueHash(claim.outPoint, takeoverHeight);
const auto pos = key.size(); const auto pos = key.size();
std::vector<std::pair<unsigned char, CUint256>> children; std::vector<std::pair<unsigned char, uint256>> children;
for (auto&& child : childHashQuery << key) { for (auto&& child : childHashQuery << key) {
std::string childKey; std::string childKey;
CUint256 hash; uint256 hash;
child >> childKey >> hash; child >> childKey >> hash;
if (name.find(childKey) == 0) { if (name.find(childKey) == 0) {
for (auto i = pos; i + 1 < childKey.size(); ++i) { for (auto i = pos; i + 1 < childKey.size(); ++i) {
children.emplace_back(childKey[i], CUint256{}); children.emplace_back(childKey[i], uint256{});
proof.nodes.emplace_back(children, fNodeHasValue, valueHash); proof.nodes.emplace_back(children, fNodeHasValue, valueHash);
children.clear(); children.clear();
valueHash.SetNull(); valueHash.SetNull();
fNodeHasValue = false; fNodeHasValue = false;
} }
children.emplace_back(childKey.back(), CUint256{}); children.emplace_back(childKey.back(), uint256{});
continue; continue;
} }
completeHash(hash, childKey, pos); completeHash(hash, childKey, pos);
@ -897,8 +897,8 @@ void CClaimTrieCacheBase::getNamesInTrie(std::function<void(const std::string&)>
}; };
} }
std::vector<CUint160> CClaimTrieCacheBase::getActivatedClaims(int height) { std::vector<uint160> CClaimTrieCacheBase::getActivatedClaims(int height) {
std::vector<CUint160> ret; std::vector<uint160> ret;
auto query = db << "SELECT DISTINCT claimID FROM claim WHERE activationHeight = ?1 AND blockHeight < ?1" << height; auto query = db << "SELECT DISTINCT claimID FROM claim WHERE activationHeight = ?1 AND blockHeight < ?1" << height;
for (auto&& row: query) { for (auto&& row: query) {
ret.emplace_back(); ret.emplace_back();
@ -906,8 +906,8 @@ std::vector<CUint160> CClaimTrieCacheBase::getActivatedClaims(int height) {
} }
return ret; return ret;
} }
std::vector<CUint160> CClaimTrieCacheBase::getClaimsWithActivatedSupports(int height) { std::vector<uint160> CClaimTrieCacheBase::getClaimsWithActivatedSupports(int height) {
std::vector<CUint160> ret; std::vector<uint160> ret;
auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE activationHeight = ?1 AND blockHeight < ?1" << height; auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE activationHeight = ?1 AND blockHeight < ?1" << height;
for (auto&& row: query) { for (auto&& row: query) {
ret.emplace_back(); ret.emplace_back();
@ -915,8 +915,8 @@ std::vector<CUint160> CClaimTrieCacheBase::getClaimsWithActivatedSupports(int he
} }
return ret; return ret;
} }
std::vector<CUint160> CClaimTrieCacheBase::getExpiredClaims(int height) { std::vector<uint160> CClaimTrieCacheBase::getExpiredClaims(int height) {
std::vector<CUint160> ret; std::vector<uint160> ret;
auto query = db << "SELECT DISTINCT claimID FROM claim WHERE expirationHeight = ?1 AND blockHeight < ?1" << height; auto query = db << "SELECT DISTINCT claimID FROM claim WHERE expirationHeight = ?1 AND blockHeight < ?1" << height;
for (auto&& row: query) { for (auto&& row: query) {
ret.emplace_back(); ret.emplace_back();
@ -924,8 +924,8 @@ std::vector<CUint160> CClaimTrieCacheBase::getExpiredClaims(int height) {
} }
return ret; return ret;
} }
std::vector<CUint160> CClaimTrieCacheBase::getClaimsWithExpiredSupports(int height) { std::vector<uint160> CClaimTrieCacheBase::getClaimsWithExpiredSupports(int height) {
std::vector<CUint160> ret; std::vector<uint160> ret;
auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE expirationHeight = ?1 AND blockHeight < ?1" << height; auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE expirationHeight = ?1 AND blockHeight < ?1" << height;
for (auto&& row: query) { for (auto&& row: query) {
ret.emplace_back(); ret.emplace_back();

View file

@ -13,7 +13,7 @@
#include <unordered_set> #include <unordered_set>
#include <utility> #include <utility>
CUint256 getValueHash(const CTxOutPoint& outPoint, int nHeightOfLastTakeover); uint256 getValueHash(const COutPoint& outPoint, int nHeightOfLastTakeover);
class CClaimTrie class CClaimTrie
{ {
@ -64,27 +64,27 @@ public:
bool flush(); bool flush();
bool checkConsistency(); bool checkConsistency();
CUint256 getMerkleHash(); uint256 getMerkleHash();
bool validateDb(int height, const CUint256& rootHash); bool validateDb(int height, const uint256& rootHash);
std::size_t getTotalNamesInTrie() const; std::size_t getTotalNamesInTrie() const;
std::size_t getTotalClaimsInTrie() const; std::size_t getTotalClaimsInTrie() const;
int64_t getTotalValueOfClaimsInTrie(bool fControllingOnly) const; int64_t getTotalValueOfClaimsInTrie(bool fControllingOnly) const;
bool haveClaim(const std::string& name, const CTxOutPoint& outPoint) const; bool haveClaim(const std::string& name, const COutPoint& outPoint) const;
bool haveClaimInQueue(const std::string& name, const CTxOutPoint& outPoint, int& nValidAtHeight) const; bool haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const;
bool haveSupport(const std::string& name, const CTxOutPoint& outPoint) const; bool haveSupport(const std::string& name, const COutPoint& outPoint) const;
bool haveSupportInQueue(const std::string& name, const CTxOutPoint& outPoint, int& nValidAtHeight) const; bool haveSupportInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const;
bool addClaim(const std::string& name, const CTxOutPoint& outPoint, const CUint160& claimId, int64_t nAmount, bool addClaim(const std::string& name, const COutPoint& outPoint, const uint160& claimId, int64_t nAmount,
int nHeight, int nValidHeight = -1); int nHeight, int nValidHeight = -1);
bool addSupport(const std::string& name, const CTxOutPoint& outPoint, const CUint160& supportedClaimId, int64_t nAmount, bool addSupport(const std::string& name, const COutPoint& outPoint, const uint160& supportedClaimId, int64_t nAmount,
int nHeight, int nValidHeight = -1); int nHeight, int nValidHeight = -1);
bool removeClaim(const CUint160& claimId, const CTxOutPoint& outPoint, std::string& nodeName, int& validHeight); bool removeClaim(const uint160& claimId, const COutPoint& outPoint, std::string& nodeName, int& validHeight);
bool removeSupport(const CTxOutPoint& outPoint, std::string& nodeName, int& validHeight); bool removeSupport(const COutPoint& outPoint, std::string& nodeName, int& validHeight);
virtual bool incrementBlock(); virtual bool incrementBlock();
virtual bool decrementBlock(); virtual bool decrementBlock();
@ -92,20 +92,20 @@ public:
virtual int expirationTime() const; virtual int expirationTime() const;
virtual bool getProofForName(const std::string& name, const CUint160& claim, CClaimTrieProof& proof); virtual bool getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof);
virtual bool getInfoForName(const std::string& name, CClaimValue& claim, int heightOffset = 0) const; virtual bool getInfoForName(const std::string& name, CClaimValue& claim, int heightOffset = 0) const;
virtual CClaimSupportToName getClaimsForName(const std::string& name) const; virtual CClaimSupportToName getClaimsForName(const std::string& name) const;
virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const; virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const;
void getNamesInTrie(std::function<void(const std::string&)> callback) const; void getNamesInTrie(std::function<void(const std::string&)> callback) const;
bool getLastTakeoverForName(const std::string& name, CUint160& claimId, int& takeoverHeight) const; bool getLastTakeoverForName(const std::string& name, uint160& claimId, int& takeoverHeight) const;
bool findNameForClaim(std::vector<unsigned char> claim, CClaimValue& value, std::string& name) const; bool findNameForClaim(std::vector<unsigned char> claim, CClaimValue& value, std::string& name) const;
std::vector<CUint160> getActivatedClaims(int height); std::vector<uint160> getActivatedClaims(int height);
std::vector<CUint160> getClaimsWithActivatedSupports(int height); std::vector<uint160> getClaimsWithActivatedSupports(int height);
std::vector<CUint160> getExpiredClaims(int height); std::vector<uint160> getExpiredClaims(int height);
std::vector<CUint160> getClaimsWithExpiredSupports(int height); std::vector<uint160> getClaimsWithExpiredSupports(int height);
protected: protected:
int nNextHeight; // Height of the block that is being worked on, which is int nNextHeight; // Height of the block that is being worked on, which is
@ -115,10 +115,10 @@ protected:
mutable sqlite::database_binder claimHashQuery, childHashQuery, claimHashQueryLimit; mutable sqlite::database_binder claimHashQuery, childHashQuery, claimHashQueryLimit;
virtual CUint256 computeNodeHash(const std::string& name, int takeoverHeight); virtual uint256 computeNodeHash(const std::string& name, int takeoverHeight);
supportEntryType getSupportsForName(const std::string& name) const; supportEntryType getSupportsForName(const std::string& name) const;
virtual int getDelayForName(const std::string& name, const CUint160& claimId) const; virtual int getDelayForName(const std::string& name, const uint160& claimId) const;
bool deleteNodeIfPossible(const std::string& name, std::string& parent, int64_t& claims); bool deleteNodeIfPossible(const std::string& name, std::string& parent, int64_t& claims);
void ensureTreeStructureIsUpToDate(); void ensureTreeStructureIsUpToDate();

View file

@ -3,40 +3,40 @@
#include <sstream> #include <sstream>
CTxOutPoint::CTxOutPoint(CUint256 hashIn, uint32_t nIn) : hash(std::move(hashIn)), n(nIn) COutPoint::COutPoint(uint256 hashIn, uint32_t nIn) : hash(std::move(hashIn)), n(nIn)
{ {
} }
void CTxOutPoint::SetNull() void COutPoint::SetNull()
{ {
hash.SetNull(); hash.SetNull();
n = uint32_t(-1); n = uint32_t(-1);
} }
bool CTxOutPoint::IsNull() const bool COutPoint::IsNull() const
{ {
return hash.IsNull() && n == uint32_t(-1); return hash.IsNull() && n == uint32_t(-1);
} }
bool CTxOutPoint::operator<(const CTxOutPoint& b) const bool COutPoint::operator<(const COutPoint& b) const
{ {
int cmp = hash.Compare(b.hash); int cmp = hash.Compare(b.hash);
return cmp < 0 || (cmp == 0 && n < b.n); return cmp < 0 || (cmp == 0 && n < b.n);
} }
bool CTxOutPoint::operator==(const CTxOutPoint& b) const bool COutPoint::operator==(const COutPoint& b) const
{ {
return hash == b.hash && n == b.n; return hash == b.hash && n == b.n;
} }
bool CTxOutPoint::operator!=(const CTxOutPoint& b) const bool COutPoint::operator!=(const COutPoint& b) const
{ {
return !(*this == b); return !(*this == b);
} }
std::string CTxOutPoint::ToString() const std::string COutPoint::ToString() const
{ {
std::stringstream ss; std::stringstream ss;
ss << "CTxOutPoint(" << hash.ToString().substr(0, 10) << ", " << n << ')'; ss << "COutPoint(" << hash.ToString().substr(0, 10) << ", " << n << ')';
return ss.str(); return ss.str();
} }

View file

@ -11,26 +11,26 @@
#include <utility> #include <utility>
/** An outpoint - a combination of a transaction hash and an index n into its vout */ /** An outpoint - a combination of a transaction hash and an index n into its vout */
class CTxOutPoint class COutPoint
{ {
public: public:
CUint256 hash; uint256 hash;
uint32_t n = uint32_t(-1); uint32_t n = uint32_t(-1);
CTxOutPoint() = default; COutPoint() = default;
CTxOutPoint(CTxOutPoint&&) = default; COutPoint(COutPoint&&) = default;
CTxOutPoint(const CTxOutPoint&) = default; COutPoint(const COutPoint&) = default;
CTxOutPoint(CUint256 hashIn, uint32_t nIn); COutPoint(uint256 hashIn, uint32_t nIn);
CTxOutPoint& operator=(CTxOutPoint&&) = default; COutPoint& operator=(COutPoint&&) = default;
CTxOutPoint& operator=(const CTxOutPoint&) = default; COutPoint& operator=(const COutPoint&) = default;
void SetNull(); void SetNull();
bool IsNull() const; bool IsNull() const;
bool operator<(const CTxOutPoint& b) const; bool operator<(const COutPoint& b) const;
bool operator==(const CTxOutPoint& b) const; bool operator==(const COutPoint& b) const;
bool operator!=(const CTxOutPoint& b) const; bool operator!=(const COutPoint& b) const;
std::string ToString() const; std::string ToString() const;
}; };

View file

@ -1,173 +1,34 @@
#include <uints.h> #include <uints.h>
#include <algorithm> uint160::uint160(const std::vector<uint8_t>& vec) : CBaseBlob<160>(vec)
#include <cassert>
#include <cstring>
#include <iomanip>
#include <sstream>
/** Template base class for fixed-sized opaque blobs. */
template<uint32_t BITS>
CBaseBlob<BITS>::CBaseBlob() : data(std::make_unique<uint8_t[]>(WIDTH))
{ {
SetNull();
} }
template<uint32_t BITS> uint256::uint256(const std::vector<uint8_t>& vec) : CBaseBlob<256>(vec)
CBaseBlob<BITS>::CBaseBlob(const std::vector<uint8_t>& vec) : data(std::make_unique<uint8_t[]>(WIDTH))
{ {
assert(vec.size() == size());
std::copy(vec.begin(), vec.end(), begin());
} }
template<uint32_t BITS> uint160 uint160S(const char* str)
CBaseBlob<BITS>::CBaseBlob(const CBaseBlob& o) : data(std::make_unique<uint8_t[]>(WIDTH))
{ {
*this = o; uint160 s;
}
template<uint32_t BITS>
CBaseBlob<BITS>& CBaseBlob<BITS>::operator=(const CBaseBlob& o)
{
if (this != &o)
std::copy(o.begin(), o.end(), begin());
return *this;
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::IsNull() const
{
return std::all_of(begin(), end(), [](uint8_t e) { return e == 0; });
}
template<uint32_t BITS>
void CBaseBlob<BITS>::SetNull()
{
std::memset(begin(), 0, size());
}
template<uint32_t BITS>
int CBaseBlob<BITS>::Compare(const CBaseBlob& other) const
{
return std::memcmp(begin(), other.begin(), size());
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::operator==(const CBaseBlob& b) const
{
return Compare(b) == 0;
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::operator!=(const CBaseBlob& b) const
{
return Compare(b) != 0;
}
template<uint32_t BITS>
bool CBaseBlob<BITS>::operator<(const CBaseBlob& b) const
{
return Compare(b) < 0;
}
template<uint32_t BITS>
std::string CBaseBlob<BITS>::GetHex() const
{
std::stringstream ss;
ss << std::hex;
for (int i = WIDTH - 1; i >= 0; --i)
ss << std::setw(2) << std::setfill('0') << uint32_t(data[i]);
return ss.str();
}
template<uint32_t BITS>
void CBaseBlob<BITS>::SetHex(const char* psz)
{
SetNull();
// skip leading spaces
while (isspace(*psz))
psz++;
// skip 0x
if (psz[0] == '0' && tolower(psz[1]) == 'x')
psz += 2;
auto b = psz;
// advance to end
while (isxdigit(*psz))
psz++;
--psz;
char buf[3] = {};
auto it = begin();
while (psz >= b && it != end()) {
buf[1] = *psz--;
buf[0] = psz >= b ? *psz-- : '0';
*it++ = std::strtoul(buf, nullptr, 16);
}
}
template<uint32_t BITS>
void CBaseBlob<BITS>::SetHex(const std::string& str)
{
SetHex(str.c_str());
}
template<uint32_t BITS>
std::string CBaseBlob<BITS>::ToString() const
{
return GetHex();
}
template<uint32_t BITS>
uint8_t* CBaseBlob<BITS>::begin()
{
return data.get();
}
template<uint32_t BITS>
uint8_t* CBaseBlob<BITS>::end()
{
return begin() + WIDTH;
}
template<uint32_t BITS>
const uint8_t* CBaseBlob<BITS>::begin() const
{
return data.get();
}
template<uint32_t BITS>
const uint8_t* CBaseBlob<BITS>::end() const
{
return begin() + WIDTH;
}
CUint160 CUint160S(const char* str)
{
CUint160 s;
s.SetHex(str); s.SetHex(str);
return s; return s;
} }
CUint160 CUint160S(const std::string& s) uint160 uint160S(const std::string& s)
{ {
return CUint160S(s.c_str()); return uint160S(s.c_str());
} }
CUint256 CUint256S(const char* str) uint256 uint256S(const char* str)
{ {
CUint256 s; uint256 s;
s.SetHex(str); s.SetHex(str);
return s; return s;
} }
CUint256 CUint256S(const std::string& s) uint256 uint256S(const std::string& s)
{ {
return CUint256S(s.c_str()); return uint256S(s.c_str());
} }
template class CBaseBlob<160>;
template class CBaseBlob<256>;

View file

@ -2,59 +2,41 @@
#ifndef CLAIMTRIE_UINTS_H #ifndef CLAIMTRIE_UINTS_H
#define CLAIMTRIE_UINTS_H #define CLAIMTRIE_UINTS_H
#include <memory> #include <blob.h>
#include <string> #include <string>
#include <vector>
/** Template base class for fixed-sized opaque blobs. */ class uint160 : public CBaseBlob<160>
template<uint32_t BITS>
class CBaseBlob
{ {
protected:
static constexpr uint32_t WIDTH = BITS / 8;
std::unique_ptr<uint8_t[]> data;
public: public:
CBaseBlob(); uint160() = default;
explicit CBaseBlob(const std::vector<uint8_t>& vec); explicit uint160(const std::vector<uint8_t>& vec);
CBaseBlob(CBaseBlob&&) = default; uint160(uint160&&) = default;
CBaseBlob& operator=(CBaseBlob&&) = default; uint160& operator=(uint160&&) = default;
CBaseBlob(const CBaseBlob& o); uint160(const uint160&) = default;
CBaseBlob& operator=(const CBaseBlob& o); uint160& operator=(const uint160&) = default;
bool IsNull() const;
void SetNull();
int Compare(const CBaseBlob& other) const;
bool operator==(const CBaseBlob& b) const;
bool operator!=(const CBaseBlob& b) const;
bool operator<(const CBaseBlob& b) const;
std::string GetHex() const;
void SetHex(const char* psz);
void SetHex(const std::string& str);
std::string ToString() const;
uint8_t* begin();
uint8_t* end();
const uint8_t* begin() const;
const uint8_t* end() const;
static constexpr uint32_t size() { return WIDTH; }
}; };
typedef CBaseBlob<160> CUint160; class uint256 : public CBaseBlob<256>
typedef CBaseBlob<256> CUint256; {
public:
uint256() = default;
CUint160 CUint160S(const char* str); explicit uint256(const std::vector<uint8_t>& vec);
CUint160 CUint160S(const std::string& s);
CUint256 CUint256S(const char* str); uint256(uint256&&) = default;
CUint256 CUint256S(const std::string& s); uint256& operator=(uint256&&) = default;
uint256(const uint256&) = default;
uint256& operator=(const uint256&) = default;
};
uint160 uint160S(const char* str);
uint160 uint160S(const std::string& s);
uint256 uint256S(const char* str);
uint256 uint256S(const std::string& s);
#endif // CLAIMTRIE_UINTS_H #endif // CLAIMTRIE_UINTS_H

View file

@ -6,27 +6,39 @@
#include <claimtrie/txoutpoint.h> #include <claimtrie/txoutpoint.h>
#include <claimtrie/uints.h> #include <claimtrie/uints.h>
template<typename Stream, uint32_t BITS> template<typename Stream>
void Serialize(Stream& s, const CBaseBlob<BITS>& u) void Serialize(Stream& s, const uint160& u)
{ {
s.write((const char*)u.begin(), u.size()); s.write((const char*)u.begin(), u.size());
} }
template<typename Stream, uint32_t BITS> template<typename Stream>
void Unserialize(Stream& s, CBaseBlob<BITS>& u) void Serialize(Stream& s, const uint256& u)
{
s.write((const char*)u.begin(), u.size());
}
template<typename Stream>
void Unserialize(Stream& s, uint160& u)
{ {
s.read((char*)u.begin(), u.size()); s.read((char*)u.begin(), u.size());
} }
template<typename Stream> template<typename Stream>
void Serialize(Stream& s, const CTxOutPoint& u) void Unserialize(Stream& s, uint256& u)
{
s.read((char*)u.begin(), u.size());
}
template<typename Stream>
void Serialize(Stream& s, const COutPoint& u)
{ {
Serialize(s, u.hash); Serialize(s, u.hash);
Serialize(s, u.n); Serialize(s, u.n);
} }
template<typename Stream> template<typename Stream>
void Unserialize(Stream& s, CTxOutPoint& u) void Unserialize(Stream& s, COutPoint& u)
{ {
Unserialize(s, u.hash); Unserialize(s, u.hash);
Unserialize(s, u.n); Unserialize(s, u.n);

View file

@ -200,7 +200,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
{ {
CClaimTrieCache trieCache(pclaimTrie); CClaimTrieCache trieCache(pclaimTrie);
blockToCache(pblock, trieCache, nHeight); blockToCache(pblock, trieCache, nHeight);
pblock->hashClaimTrie = uint256(trieCache.getMerkleHash()); pblock->hashClaimTrie = trieCache.getMerkleHash();
} }
CValidationState state; CValidationState state;
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {

View file

@ -9,11 +9,6 @@
#include <tinyformat.h> #include <tinyformat.h>
#include <utilstrencodings.h> #include <utilstrencodings.h>
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn) CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
{ {
prevout = prevoutIn; prevout = prevoutIn;

View file

@ -15,52 +15,6 @@
static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000; static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
uint32_t n;
COutPoint(): n((uint32_t) -1) { }
explicit COutPoint(const CTxOutPoint& c) : hash(c.hash), n(c.n) { }
COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(hash);
READWRITE(n);
}
void SetNull() { hash.SetNull(); n = (uint32_t) -1; }
bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
int cmp = a.hash.Compare(b.hash);
return cmp < 0 || (cmp == 0 && a.n < b.n);
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const;
operator CTxOutPoint() const
{
return CTxOutPoint{hash, n};
}
};
/** An input of a transaction. It contains the location of the previous /** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the * transaction's output that it claims and a signature that matches the
* output's public key. * output's public key.

View file

@ -22,6 +22,18 @@ class CKeyID : public uint160
public: public:
CKeyID() : uint160() {} CKeyID() : uint160() {}
explicit CKeyID(const uint160& in) : uint160(in) {} explicit CKeyID(const uint160& in) : uint160(in) {}
template<typename Stream>
void Serialize(Stream& s) const
{
s.write((const char*)begin(), size());
}
template<typename Stream>
void Unserialize(Stream& s)
{
s.read((char*)begin(), size());
}
}; };
typedef uint256 ChainCode; typedef uint256 ChainCode;

View file

@ -132,7 +132,7 @@ std::vector<CClaimNsupports> seqSort(const std::vector<CClaimNsupports>& source)
return claimsNsupports; return claimsNsupports;
} }
std::size_t indexOf(const std::vector<CClaimNsupports>& source, const CUint160& claimId) std::size_t indexOf(const std::vector<CClaimNsupports>& source, const uint160& claimId)
{ {
auto it = std::find_if(source.begin(), source.end(), [&claimId](const CClaimNsupports& claimNsupports) { auto it = std::find_if(source.begin(), source.end(), [&claimId](const CClaimNsupports& claimNsupports) {
return claimNsupports.claim.claimId == claimId; return claimNsupports.claim.claimId == claimId;
@ -291,7 +291,7 @@ static UniValue getvalueforname(const JSONRPCRequest& request)
return ret; return ret;
auto& claimNsupports = auto& claimNsupports =
claimId.length() == claimIdHexLength ? csToName.find(CUint160S(claimId)) : claimId.length() == claimIdHexLength ? csToName.find(uint160S(claimId)) :
!claimId.empty() ? csToName.find(claimId) : csToName.claimsNsupports[0]; !claimId.empty() ? csToName.find(claimId) : csToName.claimsNsupports[0];
if (claimNsupports.IsNull()) if (claimNsupports.IsNull())
@ -541,11 +541,11 @@ UniValue getclaimsfortx(const JSONRPCRequest& request)
std::string sName(vvchParams[0].begin(), vvchParams[0].end()); std::string sName(vvchParams[0].begin(), vvchParams[0].end());
o.pushKV(T_NAME, escapeNonUtf8(sName)); o.pushKV(T_NAME, escapeNonUtf8(sName));
if (op == OP_CLAIM_NAME) { if (op == OP_CLAIM_NAME) {
CUint160 claimId = ClaimIdHash(hash, i); uint160 claimId = ClaimIdHash(hash, i);
o.pushKV(T_CLAIMID, claimId.GetHex()); o.pushKV(T_CLAIMID, claimId.GetHex());
o.pushKV(T_VALUE, HexStr(vvchParams[1].begin(), vvchParams[1].end())); o.pushKV(T_VALUE, HexStr(vvchParams[1].begin(), vvchParams[1].end()));
} else if (op == OP_UPDATE_CLAIM || op == OP_SUPPORT_CLAIM) { } else if (op == OP_UPDATE_CLAIM || op == OP_SUPPORT_CLAIM) {
CUint160 claimId(vvchParams[1]); uint160 claimId(vvchParams[1]);
o.pushKV(T_CLAIMID, claimId.GetHex()); o.pushKV(T_CLAIMID, claimId.GetHex());
if (vvchParams.size() > 2) if (vvchParams.size() > 2)
o.pushKV(T_VALUE, HexStr(vvchParams[2].begin(), vvchParams[2].end())); o.pushKV(T_VALUE, HexStr(vvchParams[2].begin(), vvchParams[2].end()));

View file

@ -10,7 +10,6 @@
#include <algorithm> #include <algorithm>
#include <assert.h> #include <assert.h>
#include <claimtrie_serial.h>
#include <ios> #include <ios>
#include <limits> #include <limits>
#include <map> #include <map>
@ -229,8 +228,7 @@ template<typename Stream> inline void Serialize(Stream& s, bool a) { char f=a
template<typename Stream> inline void Unserialize(Stream& s, bool& a) { char f=ser_readdata8(s); a=f; } template<typename Stream> inline void Unserialize(Stream& s, bool& a) { char f=ser_readdata8(s); a=f; }
#include <claimtrie_serial.h>
/** /**

View file

@ -34,7 +34,8 @@ public:
int RandomInt(int nMax) override int RandomInt(int nMax) override
{ {
state = (CHashWriter(SER_GETHASH, 0) << state).GetHash().GetCheapHash(); auto hash = (CHashWriter(SER_GETHASH, 0) << state).GetHash();
state = GetCheapHash(hash);
return (unsigned int)(state % nMax); return (unsigned int)(state % nMax);
} }

View file

@ -31,7 +31,7 @@ BOOST_AUTO_TEST_CASE(takeover_stability_test) {
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "@bass", "two", 2); CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "@bass", "two", 2);
fixture.IncrementBlocks(1); fixture.IncrementBlocks(1);
BOOST_CHECK(fixture.is_best_claim("@bass", tx2)); BOOST_CHECK(fixture.is_best_claim("@bass", tx2));
CUint160 id; int takeover; uint160 id; int takeover;
BOOST_REQUIRE(fixture.getLastTakeoverForName("@bass", id, takeover)); BOOST_REQUIRE(fixture.getLastTakeoverForName("@bass", id, takeover));
auto height = chainActive.Tip()->nHeight; auto height = chainActive.Tip()->nHeight;
BOOST_CHECK_EQUAL(takeover, height); BOOST_CHECK_EQUAL(takeover, height);
@ -427,7 +427,7 @@ BOOST_AUTO_TEST_CASE(claimtrie_update_takeover_test)
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 5); CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 5);
auto cid = ClaimIdHash(tx1.GetHash(), 0); auto cid = ClaimIdHash(tx1.GetHash(), 0);
fixture.IncrementBlocks(1); fixture.IncrementBlocks(1);
CUint160 cid2; uint160 cid2;
int takeover; int takeover;
int height = chainActive.Tip()->nHeight; int height = chainActive.Tip()->nHeight;
fixture.getLastTakeoverForName("test", cid2, takeover); fixture.getLastTakeoverForName("test", cid2, takeover);
@ -1921,7 +1921,7 @@ BOOST_AUTO_TEST_CASE(update_on_support2_test)
CMutableTransaction s2 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, name, 1); CMutableTransaction s2 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, name, 1);
fixture.IncrementBlocks(1); fixture.IncrementBlocks(1);
CUint160 claimId; uint160 claimId;
int lastTakeover; int lastTakeover;
BOOST_CHECK(fixture.getLastTakeoverForName(name, claimId, lastTakeover)); BOOST_CHECK(fixture.getLastTakeoverForName(name, claimId, lastTakeover));
BOOST_CHECK_EQUAL(lastTakeover, height + 1); BOOST_CHECK_EQUAL(lastTakeover, height + 1);

View file

@ -30,7 +30,7 @@ public:
return addClaim(key, p, c, value.nAmount, value.nHeight); return addClaim(key, p, c, value.nAmount, value.nHeight);
} }
bool removeClaimFromTrie(const std::string& key, const CTxOutPoint& outPoint) { bool removeClaimFromTrie(const std::string& key, const COutPoint& outPoint) {
int validHeight; int validHeight;
std::string nodeName; std::string nodeName;
@ -51,7 +51,7 @@ public:
return addSupport(key, p, value.supportedClaimId, value.nAmount, value.nHeight); return addSupport(key, p, value.supportedClaimId, value.nAmount, value.nHeight);
} }
bool removeSupportFromMap(const std::string& key, const CTxOutPoint& outPoint) { bool removeSupportFromMap(const std::string& key, const COutPoint& outPoint) {
int validHeight; int validHeight;
std::string nodeName; std::string nodeName;
@ -70,7 +70,7 @@ BOOST_FIXTURE_TEST_SUITE(claimtriecache_tests, RegTestingSetup)
BOOST_AUTO_TEST_CASE(merkle_hash_single_test) BOOST_AUTO_TEST_CASE(merkle_hash_single_test)
{ {
// check empty trie // check empty trie
auto one = CUint256S("0000000000000000000000000000000000000000000000000000000000000001"); auto one = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
CClaimTrieCacheTest cc(pclaimTrie); CClaimTrieCacheTest cc(pclaimTrie);
BOOST_CHECK_EQUAL(one, cc.getMerkleHash()); BOOST_CHECK_EQUAL(one, cc.getMerkleHash());
@ -82,30 +82,30 @@ BOOST_AUTO_TEST_CASE(merkle_hash_single_test)
BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test) BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
{ {
auto hash0 = uint256S("0000000000000000000000000000000000000000000000000000000000000001"); auto hash0 = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
CUint160 hash160; uint160 hash160;
CMutableTransaction tx1 = BuildTransaction(hash0); CMutableTransaction tx1 = BuildTransaction(hash0);
CTxOutPoint tx1OutPoint(tx1.GetHash(), 0); COutPoint tx1OutPoint(tx1.GetHash(), 0);
CMutableTransaction tx2 = BuildTransaction(tx1.GetHash()); CMutableTransaction tx2 = BuildTransaction(tx1.GetHash());
CTxOutPoint tx2OutPoint(tx2.GetHash(), 0); COutPoint tx2OutPoint(tx2.GetHash(), 0);
CMutableTransaction tx3 = BuildTransaction(tx2.GetHash()); CMutableTransaction tx3 = BuildTransaction(tx2.GetHash());
CTxOutPoint tx3OutPoint(tx3.GetHash(), 0); COutPoint tx3OutPoint(tx3.GetHash(), 0);
CMutableTransaction tx4 = BuildTransaction(tx3.GetHash()); CMutableTransaction tx4 = BuildTransaction(tx3.GetHash());
CTxOutPoint tx4OutPoint(tx4.GetHash(), 0); COutPoint tx4OutPoint(tx4.GetHash(), 0);
CMutableTransaction tx5 = BuildTransaction(tx4.GetHash()); CMutableTransaction tx5 = BuildTransaction(tx4.GetHash());
CTxOutPoint tx5OutPoint(tx5.GetHash(), 0); COutPoint tx5OutPoint(tx5.GetHash(), 0);
CMutableTransaction tx6 = BuildTransaction(tx5.GetHash()); CMutableTransaction tx6 = BuildTransaction(tx5.GetHash());
CTxOutPoint tx6OutPoint(tx6.GetHash(), 0); COutPoint tx6OutPoint(tx6.GetHash(), 0);
CUint256 hash1; uint256 hash1;
hash1.SetHex("71c7b8d35b9a3d7ad9a1272b68972979bbd18589f1efe6f27b0bf260a6ba78fa"); hash1.SetHex("71c7b8d35b9a3d7ad9a1272b68972979bbd18589f1efe6f27b0bf260a6ba78fa");
CUint256 hash2; uint256 hash2;
hash2.SetHex("c4fc0e2ad56562a636a0a237a96a5f250ef53495c2cb5edd531f087a8de83722"); hash2.SetHex("c4fc0e2ad56562a636a0a237a96a5f250ef53495c2cb5edd531f087a8de83722");
CUint256 hash3; uint256 hash3;
hash3.SetHex("baf52472bd7da19fe1e35116cfb3bd180d8770ffbe3ae9243df1fb58a14b0975"); hash3.SetHex("baf52472bd7da19fe1e35116cfb3bd180d8770ffbe3ae9243df1fb58a14b0975");
CUint256 hash4; uint256 hash4;
hash4.SetHex("c73232a755bf015f22eaa611b283ff38100f2a23fb6222e86eca363452ba0c51"); hash4.SetHex("c73232a755bf015f22eaa611b283ff38100f2a23fb6222e86eca363452ba0c51");
{ {
@ -215,8 +215,8 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test)
// create and insert claim // create and insert claim
auto hash0 = uint256S("0000000000000000000000000000000000000000000000000000000000000001"); auto hash0 = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
CMutableTransaction tx1 = BuildTransaction(hash0); CMutableTransaction tx1 = BuildTransaction(hash0);
CUint160 claimId = ClaimIdHash(tx1.GetHash(), 0); uint160 claimId = ClaimIdHash(tx1.GetHash(), 0);
CTxOutPoint claimOutPoint(tx1.GetHash(), 0); COutPoint claimOutPoint(tx1.GetHash(), 0);
CAmount amount(10); CAmount amount(10);
int height = 0; int height = 0;
int validHeight = 0; int validHeight = 0;
@ -239,7 +239,7 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test)
CAmount supportAmount(10); CAmount supportAmount(10);
auto hash1 = uint256S("0000000000000000000000000000000000000000000000000000000000000002"); auto hash1 = uint256S("0000000000000000000000000000000000000000000000000000000000000002");
CMutableTransaction tx2 = BuildTransaction(hash1); CMutableTransaction tx2 = BuildTransaction(hash1);
CTxOutPoint supportOutPoint(tx2.GetHash(), 0); COutPoint supportOutPoint(tx2.GetHash(), 0);
CSupportValue support(supportOutPoint, claimId, supportAmount, height, validHeight); CSupportValue support(supportOutPoint, claimId, supportAmount, height, validHeight);
ctc.insertSupportIntoMap("test", support); ctc.insertSupportIntoMap("test", support);
@ -257,7 +257,7 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test)
// CClaimTrieCacheTest cc(pclaimTrie); // CClaimTrieCacheTest cc(pclaimTrie);
// BOOST_CHECK_EQUAL(0, cc.getTotalClaimsInTrie()); // BOOST_CHECK_EQUAL(0, cc.getTotalClaimsInTrie());
// //
// CTxOutPoint outpoint; // COutPoint outpoint;
// uint160 claimId; // uint160 claimId;
// CAmount amount(20); // CAmount amount(20);
// int height = 0; // int height = 0;
@ -318,7 +318,7 @@ BOOST_AUTO_TEST_CASE(trie_stays_consistent_test)
for (auto& name: names) { for (auto& name: names) {
auto hash = Hash(name.begin(), name.end()); auto hash = Hash(name.begin(), name.end());
BOOST_CHECK(cache.removeClaimFromTrie(name, CTxOutPoint(hash, 0))); BOOST_CHECK(cache.removeClaimFromTrie(name, COutPoint(hash, 0)));
cache.flush(); cache.flush();
BOOST_CHECK(cache.checkConsistency()); BOOST_CHECK(cache.checkConsistency());
} }
@ -328,7 +328,7 @@ BOOST_AUTO_TEST_CASE(trie_stays_consistent_test)
BOOST_AUTO_TEST_CASE(verify_basic_serialization) BOOST_AUTO_TEST_CASE(verify_basic_serialization)
{ {
CClaimValue cv; CClaimValue cv;
cv.outPoint = CTxOutPoint(CUint256S("123"), 2); cv.outPoint = COutPoint(uint256S("123"), 2);
cv.nHeight = 3; cv.nHeight = 3;
cv.claimId.SetHex("4567"); cv.claimId.SetHex("4567");
cv.nEffectiveAmount = 4; cv.nEffectiveAmount = 4;

View file

@ -404,7 +404,7 @@ boost::test_tools::predicate_result ClaimTrieChainFixture::best_claim_effective_
return true; return true;
} }
bool ClaimTrieChainFixture::getClaimById(const CUint160 &claimId, std::string &name, CClaimValue &value) bool ClaimTrieChainFixture::getClaimById(const uint160 &claimId, std::string &name, CClaimValue &value)
{ {
auto query = db << "SELECT nodeName, claimID, txID, txN, amount, validHeight, blockHeight " auto query = db << "SELECT nodeName, claimID, txID, txN, amount, validHeight, blockHeight "
"FROM claim WHERE claimID = ?" << claimId; "FROM claim WHERE claimID = ?" << claimId;

View file

@ -103,7 +103,7 @@ struct ClaimTrieChainFixture: public CClaimTrieCache
int proportionalDelayFactor() const; int proportionalDelayFactor() const;
bool getClaimById(const CUint160& claimId, std::string& name, CClaimValue& value); bool getClaimById(const uint160& claimId, std::string& name, CClaimValue& value);
// is a claim in queue // is a claim in queue
boost::test_tools::predicate_result is_claim_in_queue(const std::string& name, const CTransaction &tx); boost::test_tools::predicate_result is_claim_in_queue(const std::string& name, const CTransaction &tx);

View file

@ -8,7 +8,7 @@
using namespace std; using namespace std;
void ValidatePairs(CClaimTrieCache& cache, const std::vector<std::pair<bool, CUint256>>& pairs, CUint256 claimHash) void ValidatePairs(CClaimTrieCache& cache, const std::vector<std::pair<bool, uint256>>& pairs, uint256 claimHash)
{ {
for (auto& pair : pairs) for (auto& pair : pairs)
if (pair.first) // we're on the right because we were an odd index number if (pair.first) // we're on the right because we were an odd index number
@ -179,9 +179,9 @@ BOOST_AUTO_TEST_CASE(hash_claims_children_fuzzer_test)
} }
} }
bool verify_proof(const CClaimTrieProof proof, CUint256 rootHash, const std::string& name) bool verify_proof(const CClaimTrieProof proof, uint256 rootHash, const std::string& name)
{ {
CUint256 previousComputedHash; uint256 previousComputedHash;
std::string computedReverseName; std::string computedReverseName;
bool verifiedValue = false; bool verifiedValue = false;
@ -190,7 +190,7 @@ bool verify_proof(const CClaimTrieProof proof, CUint256 rootHash, const std::str
std::vector<unsigned char> vchToHash; std::vector<unsigned char> vchToHash;
for (auto itChildren = itNodes->children.begin(); itChildren != itNodes->children.end(); ++itChildren) { for (auto itChildren = itNodes->children.begin(); itChildren != itNodes->children.end(); ++itChildren) {
vchToHash.push_back(itChildren->first); vchToHash.push_back(itChildren->first);
CUint256 childHash; uint256 childHash;
if (itChildren->second.IsNull()) { if (itChildren->second.IsNull()) {
if (previousComputedHash.IsNull()) { if (previousComputedHash.IsNull()) {
return false; return false;
@ -210,7 +210,7 @@ bool verify_proof(const CClaimTrieProof proof, CUint256 rootHash, const std::str
return false; return false;
} }
if (itNodes->hasValue) { if (itNodes->hasValue) {
CUint256 valHash; uint256 valHash;
if (itNodes->valHash.IsNull()) { if (itNodes->valHash.IsNull()) {
if (itNodes != proof.nodes.rbegin()) { if (itNodes != proof.nodes.rbegin()) {
return false; return false;
@ -233,7 +233,7 @@ bool verify_proof(const CClaimTrieProof proof, CUint256 rootHash, const std::str
std::vector<unsigned char> vchHash(hasher.OUTPUT_SIZE); std::vector<unsigned char> vchHash(hasher.OUTPUT_SIZE);
hasher.Write(vchToHash.data(), vchToHash.size()); hasher.Write(vchToHash.data(), vchToHash.size());
hasher.Finalize(&(vchHash[0])); hasher.Finalize(&(vchHash[0]));
CUint256 calculatedHash(vchHash); uint256 calculatedHash(vchHash);
previousComputedHash = calculatedHash; previousComputedHash = calculatedHash;
} }
if (previousComputedHash != rootHash) { if (previousComputedHash != rootHash) {

View file

@ -8,7 +8,7 @@
using namespace std; using namespace std;
extern void ValidatePairs(CClaimTrieCache& cache, const std::vector<std::pair<bool, CUint256>>& pairs, CUint256 claimHash); extern void ValidatePairs(CClaimTrieCache& cache, const std::vector<std::pair<bool, uint256>>& pairs, uint256 claimHash);
BOOST_FIXTURE_TEST_SUITE(claimtrierpc_tests, RegTestingSetup) BOOST_FIXTURE_TEST_SUITE(claimtrierpc_tests, RegTestingSetup)
@ -192,12 +192,12 @@ BOOST_AUTO_TEST_CASE(claim_rpcs_rollback3_test)
BOOST_CHECK_EQUAL(valueResults[T_AMOUNT].get_int(), 3); BOOST_CHECK_EQUAL(valueResults[T_AMOUNT].get_int(), 3);
} }
std::vector<std::pair<bool, CUint256>> jsonToPairs(const UniValue& jsonPair) std::vector<std::pair<bool, uint256>> jsonToPairs(const UniValue& jsonPair)
{ {
std::vector<std::pair<bool, CUint256>> pairs; std::vector<std::pair<bool, uint256>> pairs;
for (std::size_t i = 0; i < jsonPair.size(); ++i) { for (std::size_t i = 0; i < jsonPair.size(); ++i) {
auto& jpair = jsonPair[i]; auto& jpair = jsonPair[i];
pairs.emplace_back(jpair[T_ODD].get_bool(), CUint256S(jpair[T_HASH].get_str())); pairs.emplace_back(jpair[T_ODD].get_bool(), uint256S(jpair[T_HASH].get_str()));
} }
return pairs; return pairs;
} }

View file

@ -62,24 +62,6 @@ std::ostream& operator<<(std::ostream& os, const COutPoint& point)
return os; return os;
} }
std::ostream& operator<<(std::ostream& os, const CUint256& num)
{
os << num.ToString();
return os;
}
std::ostream& operator<<(std::ostream& os, const CUint160& num)
{
os << num.ToString();
return os;
}
std::ostream& operator<<(std::ostream& os, const CTxOutPoint& point)
{
os << point.ToString();
return os;
}
std::ostream& operator<<(std::ostream& os, const CClaimValue& claim) std::ostream& operator<<(std::ostream& os, const CClaimValue& claim)
{ {
os << claim.ToString(); os << claim.ToString();

View file

@ -134,10 +134,6 @@ std::ostream& operator<<(std::ostream& os, const uint160& num);
class COutPoint; class COutPoint;
std::ostream& operator<<(std::ostream& os, const COutPoint& point); std::ostream& operator<<(std::ostream& os, const COutPoint& point);
std::ostream& operator<<(std::ostream& os, const CUint256& num);
std::ostream& operator<<(std::ostream& os, const CUint160& num);
std::ostream& operator<<(std::ostream& os, const CTxOutPoint& point);
class CClaimValue; class CClaimValue;
class CSupportValue; class CSupportValue;
std::ostream& operator<<(std::ostream& os, const CClaimValue& claim); std::ostream& operator<<(std::ostream& os, const CClaimValue& claim);

View file

@ -26,16 +26,10 @@ namespace sqlite {
inline void store_result_in_db(sqlite3_context* db, const CScript& val) { inline void store_result_in_db(sqlite3_context* db, const CScript& val) {
sqlite3_result_blob(db, val.data(), int(val.size()), SQLITE_TRANSIENT); sqlite3_result_blob(db, val.data(), int(val.size()), SQLITE_TRANSIENT);
} }
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const uint256& val) {
return sqlite3_bind_blob(stmt, inx, val.begin(), int(val.size()), SQLITE_STATIC);
} }
inline void store_result_in_db(sqlite3_context* db, const uint256& val) {
sqlite3_result_blob(db, val.begin(), int(val.size()), SQLITE_TRANSIENT);
}
}
#include <sqlite.h> #include <sqlite.h>
namespace sqlite { namespace sqlite {
template<> template<>
struct has_sqlite_type<CScript, SQLITE_BLOB, void> : std::true_type {}; struct has_sqlite_type<CScript, SQLITE_BLOB, void> : std::true_type {};
@ -47,26 +41,6 @@ namespace sqlite {
assert(bytes >= 0); assert(bytes >= 0);
return CScript(ptr, ptr + bytes); return CScript(ptr, ptr + bytes);
} }
template<>
struct has_sqlite_type<uint256, SQLITE_BLOB, void> : std::true_type {};
inline uint256 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<uint256>) {
auto type = sqlite3_column_type(stmt, inx);
if (type == SQLITE_NULL)
return {};
if (type == SQLITE_INTEGER)
return ArithToUint256(arith_uint256(sqlite3_column_int64(stmt, inx)));
assert(type == SQLITE_BLOB);
auto ptr = sqlite3_column_blob(stmt, inx);
uint256 ret;
if (!ptr) return ret;
int bytes = sqlite3_column_bytes(stmt, inx);
assert(bytes > 0 && bytes <= int(ret.size()));
std::memcpy(ret.begin(), ptr, bytes);
return ret;
}
} }
class CBlockIndex; class CBlockIndex;

View file

@ -3,77 +3,10 @@
// Distributed under the MIT software license, see the accompanying // Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <crypto/common.h>
#include <uint256.h> #include <uint256.h>
#include <utilstrencodings.h> uint64_t GetCheapHash(const uint256& hash)
#include <stdio.h>
#include <string.h>
template <unsigned int BITS>
base_blob<BITS>::base_blob(const std::vector<unsigned char>& vch)
{ {
assert(vch.size() == sizeof(data)); return ReadLE64(hash.begin());
memcpy(data, vch.data(), sizeof(data));
} }
template <unsigned int BITS>
std::string base_blob<BITS>::GetHex() const
{
return HexStr(std::reverse_iterator<const uint8_t*>(data + sizeof(data)), std::reverse_iterator<const uint8_t*>(data));
}
template <unsigned int BITS>
void base_blob<BITS>::SetHex(const char* psz)
{
memset(data, 0, sizeof(data));
// skip leading spaces
while (isspace(*psz))
psz++;
// skip 0x
if (psz[0] == '0' && tolower(psz[1]) == 'x')
psz += 2;
// hex string to uint
const char* pbegin = psz;
while (::HexDigit(*psz) != -1)
psz++;
psz--;
unsigned char* p1 = (unsigned char*)data;
unsigned char* pend = p1 + WIDTH;
while (psz >= pbegin && p1 < pend) {
*p1 = ::HexDigit(*psz--);
if (psz >= pbegin) {
*p1 |= ((unsigned char)::HexDigit(*psz--) << 4);
p1++;
}
}
}
template <unsigned int BITS>
void base_blob<BITS>::SetHex(const std::string& str)
{
SetHex(str.c_str());
}
template <unsigned int BITS>
std::string base_blob<BITS>::ToString() const
{
return (GetHex());
}
// Explicit instantiations for base_blob<160>
template base_blob<160>::base_blob(const std::vector<unsigned char>&);
template std::string base_blob<160>::GetHex() const;
template std::string base_blob<160>::ToString() const;
template void base_blob<160>::SetHex(const char*);
template void base_blob<160>::SetHex(const std::string&);
// Explicit instantiations for base_blob<256>
template base_blob<256>::base_blob(const std::vector<unsigned char>&);
template std::string base_blob<256>::GetHex() const;
template std::string base_blob<256>::ToString() const;
template void base_blob<256>::SetHex(const char*);
template void base_blob<256>::SetHex(const std::string&);

View file

@ -6,166 +6,8 @@
#ifndef BITCOIN_UINT256_H #ifndef BITCOIN_UINT256_H
#define BITCOIN_UINT256_H #define BITCOIN_UINT256_H
#include <assert.h>
#include <cstring>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <vector>
#include <crypto/common.h>
#include <claimtrie/uints.h> #include <claimtrie/uints.h>
/** Template base class for fixed-sized opaque blobs. */ uint64_t GetCheapHash(const uint256& hash);
template<unsigned int BITS>
class base_blob
{
protected:
static constexpr int WIDTH = BITS / 8;
uint8_t data[WIDTH];
public:
base_blob()
{
memset(data, 0, sizeof(data));
}
explicit base_blob(const CBaseBlob<BITS>& b)
{
std::copy(b.begin(), b.end(), begin());
}
explicit base_blob(const std::vector<unsigned char>& vch);
bool IsNull() const
{
for (int i = 0; i < WIDTH; i++)
if (data[i] != 0)
return false;
return true;
}
void SetNull()
{
memset(data, 0, sizeof(data));
}
inline int Compare(const base_blob& other) const { return memcmp(data, other.data, sizeof(data)); }
friend inline bool operator==(const base_blob& a, const base_blob& b) { return a.Compare(b) == 0; }
friend inline bool operator!=(const base_blob& a, const base_blob& b) { return a.Compare(b) != 0; }
friend inline bool operator<(const base_blob& a, const base_blob& b) { return a.Compare(b) < 0; }
std::string GetHex() const;
void SetHex(const char* psz);
void SetHex(const std::string& str);
std::string ToString() const;
unsigned char* begin()
{
return &data[0];
}
unsigned char* end()
{
return &data[WIDTH];
}
const unsigned char* begin() const
{
return &data[0];
}
const unsigned char* end() const
{
return &data[WIDTH];
}
unsigned int size() const
{
return sizeof(data);
}
uint64_t GetUint64(int pos) const
{
const uint8_t* ptr = data + pos * 8;
return ((uint64_t)ptr[0]) | \
((uint64_t)ptr[1]) << 8 | \
((uint64_t)ptr[2]) << 16 | \
((uint64_t)ptr[3]) << 24 | \
((uint64_t)ptr[4]) << 32 | \
((uint64_t)ptr[5]) << 40 | \
((uint64_t)ptr[6]) << 48 | \
((uint64_t)ptr[7]) << 56;
}
template<typename Stream>
void Serialize(Stream& s) const
{
s.write((char*)data, sizeof(data));
}
template<typename Stream>
void Unserialize(Stream& s)
{
s.read((char*)data, sizeof(data));
}
operator CBaseBlob<BITS>() const
{
CBaseBlob<BITS> c;
std::copy(begin(), end(), c.begin());
return c;
}
};
/** 160-bit opaque blob.
* @note This type is called uint160 for historical reasons only. It is an opaque
* blob of 160 bits and has no integer operations.
*/
class uint160 : public base_blob<160> {
public:
using base_blob<160>::base_blob;
};
/** 256-bit opaque blob.
* @note This type is called uint256 for historical reasons only. It is an
* opaque blob of 256 bits and has no integer operations. Use arith_uint256 if
* those are required.
*/
class uint256 : public base_blob<256> {
public:
using base_blob<256>::base_blob;
/** A cheap hash function that just returns 64 bits from the result, it can be
* used when the contents are considered uniformly random. It is not appropriate
* when the value can easily be influenced from outside as e.g. a network adversary could
* provide values to trigger worst-case behavior.
*/
uint64_t GetCheapHash() const
{
return ReadLE64(data);
}
};
/* uint256 from const char *.
* This is a separate function because the constructor uint256(const char*) can result
* in dangerously catching uint256(0).
*/
inline uint256 uint256S(const char *str)
{
uint256 rv;
rv.SetHex(str);
return rv;
}
/* uint256 from std::string.
* This is a separate function because the constructor uint256(const std::string &str) can result
* in dangerously catching uint256(0) via std::string(const char*).
*/
inline uint256 uint256S(const std::string& str)
{
uint256 rv;
rv.SetHex(str);
return rv;
}
#endif // BITCOIN_UINT256_H #endif // BITCOIN_UINT256_H

View file

@ -1503,20 +1503,12 @@ int ApplyTxInUndo(unsigned int index, CTxUndo& txUndo, CCoinsViewCache& view, CC
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN; return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
} }
template <typename T1, typename T2>
inline bool equals(const T1& hash1, const T2& hash2)
{
static_assert((std::is_same<T1, uint256>::value && std::is_same<T2, CUint256>::value) ||
(std::is_same<T2, uint256>::value && std::is_same<T1, CUint256>::value), "Hash types are incompatible");
return std::equal(hash1.begin(), hash1.end(), hash2.begin());
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins. /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* When FAILED is returned, view is left in an indeterminate state. */ * When FAILED is returned, view is left in an indeterminate state. */
DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view, CClaimTrieCache& trieCache) DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view, CClaimTrieCache& trieCache)
{ {
assert(pindex->GetBlockHash() == view.GetBestBlock()); assert(pindex->GetBlockHash() == view.GetBestBlock());
if (!equals(pindex->hashClaimTrie, trieCache.getMerkleHash())) { if (pindex->hashClaimTrie != trieCache.getMerkleHash()) {
LogPrintf("%s: Indexed claim hash doesn't match current: %s vs %s\n", LogPrintf("%s: Indexed claim hash doesn't match current: %s vs %s\n",
__func__, pindex->hashClaimTrie.ToString(), trieCache.getMerkleHash().ToString()); __func__, pindex->hashClaimTrie.ToString(), trieCache.getMerkleHash().ToString());
assert(false); assert(false);
@ -1590,7 +1582,7 @@ DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockI
// move best block pointer to prevout block // move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash()); view.SetBestBlock(pindex->pprev->GetBlockHash());
assert(trieCache.finalizeDecrement()); assert(trieCache.finalizeDecrement());
if (!equals(trieCache.getMerkleHash(), pindex->pprev->hashClaimTrie)) { if (trieCache.getMerkleHash() != pindex->pprev->hashClaimTrie) {
LogPrintf("Hash comparison failure at block %d\n", pindex->nHeight); LogPrintf("Hash comparison failure at block %d\n", pindex->nHeight);
assert(false); assert(false);
} }
@ -1803,7 +1795,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
assert(hashPrevBlock == view.GetBestBlock()); assert(hashPrevBlock == view.GetBestBlock());
// also verify that the trie cache's current state corresponds to the previous block // also verify that the trie cache's current state corresponds to the previous block
if (pindex->pprev != nullptr && !equals(pindex->pprev->hashClaimTrie, trieCache.getMerkleHash())) { if (pindex->pprev != nullptr && pindex->pprev->hashClaimTrie != trieCache.getMerkleHash()) {
LogPrintf("%s: Previous block claim hash doesn't match current: %s vs %s\n", LogPrintf("%s: Previous block claim hash doesn't match current: %s vs %s\n",
__func__, pindex->pprev->hashClaimTrie.ToString(), trieCache.getMerkleHash().ToString()); __func__, pindex->pprev->hashClaimTrie.ToString(), trieCache.getMerkleHash().ToString());
assert(false); assert(false);
@ -2064,7 +2056,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
// TODO: if the "just check" flag is set, we should reduce the work done here. Incrementing blocks twice per mine is not efficient. // TODO: if the "just check" flag is set, we should reduce the work done here. Incrementing blocks twice per mine is not efficient.
assert(trieCache.incrementBlock()); assert(trieCache.incrementBlock());
if (!equals(trieCache.getMerkleHash(), block.hashClaimTrie)) { if (trieCache.getMerkleHash() != block.hashClaimTrie) {
return state.DoS(100, error("ConnectBlock() : the merkle root of the claim trie does not match " return state.DoS(100, error("ConnectBlock() : the merkle root of the claim trie does not match "
"(actual=%s vs block=%s on height=%d)", trieCache.getMerkleHash().GetHex(), "(actual=%s vs block=%s on height=%d)", trieCache.getMerkleHash().GetHex(),
block.hashClaimTrie.GetHex(), pindex->nHeight), REJECT_INVALID, "bad-claim-merkle-hash"); block.hashClaimTrie.GetHex(), pindex->nHeight), REJECT_INVALID, "bad-claim-merkle-hash");
@ -2356,7 +2348,7 @@ bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& cha
bool flushed = view.Flush(); bool flushed = view.Flush();
assert(flushed); assert(flushed);
assert(trieCache.flush()); assert(trieCache.flush());
assert(equals(pindexDelete->pprev->hashClaimTrie, trieCache.getMerkleHash())); assert(pindexDelete->pprev->hashClaimTrie == trieCache.getMerkleHash());
} }
LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI); LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
// Write the chain state to disk, if necessary. // Write the chain state to disk, if necessary.

View file

@ -141,7 +141,7 @@ static const int DEFAULT_STOPATHEIGHT = 0;
struct BlockHasher struct BlockHasher
{ {
size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); } size_t operator()(const uint256& hash) const { return GetCheapHash(hash); }
}; };
extern CScript COINBASE_FLAGS; extern CScript COINBASE_FLAGS;