diff --git a/src/Makefile.am b/src/Makefile.am index 445164227..447e48f52 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -411,6 +411,7 @@ claimtrie_libclaimtrie_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) claimtrie_libclaimtrie_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) claimtrie_libclaimtrie_a_CFLAGS = $(PIE_FLAGS) claimtrie_libclaimtrie_a_SOURCES = \ + claimtrie/blob.cpp \ claimtrie/data.cpp \ claimtrie/forks.cpp \ claimtrie/hashes.cpp \ diff --git a/src/addrman.cpp b/src/addrman.cpp index 093b263ab..beaaa5abf 100644 --- a/src/addrman.cpp +++ b/src/addrman.cpp @@ -11,23 +11,23 @@ int CAddrInfo::GetTriedBucket(const uint256& nKey) const { - uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash(); - uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash(); - return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; + auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash(); + auto hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (GetCheapHash(hash1) % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash(); + return GetCheapHash(hash2) % ADDRMAN_TRIED_BUCKET_COUNT; } int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const { std::vector vchSourceGroupKey = src.GetGroup(); - uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash(); - uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash(); - return hash2 % ADDRMAN_NEW_BUCKET_COUNT; + auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash(); + auto hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (GetCheapHash(hash1) % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash(); + return GetCheapHash(hash2) % ADDRMAN_NEW_BUCKET_COUNT; } 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(); - return hash1 % ADDRMAN_BUCKET_SIZE; + auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash(); + return GetCheapHash(hash1) % ADDRMAN_BUCKET_SIZE; } bool CAddrInfo::IsTerrible(int64_t nNow) const diff --git a/src/claimtrie/CMakeLists.txt b/src/claimtrie/CMakeLists.txt index 278abaec6..a6d9c8f0e 100644 --- a/src/claimtrie/CMakeLists.txt +++ b/src/claimtrie/CMakeLists.txt @@ -8,6 +8,7 @@ include(../../contrib/cmake/cmake/CPM.cmake) include(ExternalProject) set(CLAIMTRIE_SRC + blob.cpp data.cpp forks.cpp hashes.cpp diff --git a/src/claimtrie/blob.cpp b/src/claimtrie/blob.cpp new file mode 100644 index 000000000..9a86c2097 --- /dev/null +++ b/src/claimtrie/blob.cpp @@ -0,0 +1,166 @@ + +#include + +#include +#include +#include +#include +#include + +/** Template base class for fixed-sized opaque blobs. */ +template +CBaseBlob::CBaseBlob() +{ + SetNull(); +} + +template +CBaseBlob::CBaseBlob(const std::vector& vec) +{ + assert(vec.size() == size()); + std::copy(vec.begin(), vec.end(), begin()); +} + +template +CBaseBlob::CBaseBlob(const CBaseBlob& o) +{ + *this = o; +} + +template +CBaseBlob& CBaseBlob::operator=(const CBaseBlob& o) +{ + if (this != &o) + std::copy(o.begin(), o.end(), begin()); + return *this; +} + +template +int CBaseBlob::Compare(const CBaseBlob& b) const +{ + return std::memcmp(begin(), b.begin(), size()); +} + +template +bool CBaseBlob::operator<(const CBaseBlob& b) const +{ + return Compare(b) < 0; +} + +template +bool CBaseBlob::operator==(const CBaseBlob& b) const +{ + return Compare(b) == 0; +} + +template +bool CBaseBlob::operator!=(const CBaseBlob& b) const +{ + return !(*this == b); +} + +template +bool CBaseBlob::IsNull() const +{ + return std::all_of(begin(), end(), [](uint8_t e) { return e == 0; }); +} + +template +void CBaseBlob::SetNull() +{ + data.fill(0); +} + +template +std::string CBaseBlob::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 +void CBaseBlob::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 +uint64_t CBaseBlob::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 +void CBaseBlob::SetHex(const std::string& str) +{ + SetHex(str.c_str()); +} + +template +std::string CBaseBlob::ToString() const +{ + return GetHex(); +} + +template +uint8_t* CBaseBlob::begin() noexcept +{ + return data.begin(); +} + +template +const uint8_t* CBaseBlob::begin() const noexcept +{ + return data.begin(); +} + +template +uint8_t* CBaseBlob::end() noexcept +{ + return data.end(); +} + +template +const uint8_t* CBaseBlob::end() const noexcept +{ + return data.end(); +} + +template +std::size_t CBaseBlob::size() const +{ + return data.size(); +} + +template class CBaseBlob<160>; +template class CBaseBlob<256>; diff --git a/src/claimtrie/blob.h b/src/claimtrie/blob.h new file mode 100644 index 000000000..7e4ed47e0 --- /dev/null +++ b/src/claimtrie/blob.h @@ -0,0 +1,50 @@ + +#ifndef CLAIMTRIE_BLOB_H +#define CLAIMTRIE_BLOB_H + +#include +#include +#include + +/** Template base class for fixed-sized opaque blobs. */ +template +class CBaseBlob +{ + std::array data; +public: + CBaseBlob(); + + explicit CBaseBlob(const std::vector& 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 diff --git a/src/claimtrie/data.cpp b/src/claimtrie/data.cpp index aff3511fc..85cc1eac5 100644 --- a/src/claimtrie/data.cpp +++ b/src/claimtrie/data.cpp @@ -4,7 +4,7 @@ #include #include -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) { } @@ -44,7 +44,7 @@ std::string CClaimValue::ToString() const 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) { } @@ -70,7 +70,7 @@ std::string CSupportValue::ToString() const 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) { } @@ -92,7 +92,7 @@ CClaimSupportToName::CClaimSupportToName(std::string name, int nLastTakeoverHeig 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) { return claimId == value.claim.claimId; @@ -117,7 +117,7 @@ bool CClaimNsupports::operator<(const CClaimNsupports& other) const return claim < other.claim; } -CClaimTrieProofNode::CClaimTrieProofNode(std::vector> children, bool hasValue, CUint256 valHash) +CClaimTrieProofNode::CClaimTrieProofNode(std::vector> children, bool hasValue, uint256 valHash) : children(std::move(children)), hasValue(hasValue), valHash(std::move(valHash)) { } diff --git a/src/claimtrie/data.h b/src/claimtrie/data.h index ef5d8187b..4b1138980 100644 --- a/src/claimtrie/data.h +++ b/src/claimtrie/data.h @@ -11,15 +11,15 @@ struct CClaimValue { - CTxOutPoint outPoint; - CUint160 claimId; + COutPoint outPoint; + uint160 claimId; int64_t nAmount = 0; int64_t nEffectiveAmount = 0; int nHeight = 0; int nValidAtHeight = 0; 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(const CClaimValue&) = default; @@ -35,14 +35,14 @@ struct CClaimValue struct CSupportValue { - CTxOutPoint outPoint; - CUint160 supportedClaimId; + COutPoint outPoint; + uint160 supportedClaimId; int64_t nAmount = 0; int nHeight = 0; int nValidAtHeight = 0; 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(const CSupportValue&) = default; @@ -61,11 +61,11 @@ typedef std::vector supportEntryType; struct CNameOutPointHeightType { std::string name; - CTxOutPoint outPoint; + COutPoint outPoint; int nValidHeight = 0; CNameOutPointHeightType() = default; - CNameOutPointHeightType(std::string name, CTxOutPoint outPoint, int nValidHeight); + CNameOutPointHeightType(std::string name, COutPoint outPoint, int nValidHeight); }; struct CClaimNsupports @@ -91,7 +91,7 @@ struct CClaimSupportToName { CClaimSupportToName(std::string name, int nLastTakeoverHeight, std::vector claimsNsupports, std::vector unmatchedSupports); - const CClaimNsupports& find(const CUint160& claimId) const; + const CClaimNsupports& find(const uint160& claimId) const; const CClaimNsupports& find(const std::string& partialId) const; const std::string name; @@ -102,7 +102,7 @@ struct CClaimSupportToName struct CClaimTrieProofNode { - CClaimTrieProofNode(std::vector> children, bool hasValue, CUint256 valHash); + CClaimTrieProofNode(std::vector> children, bool hasValue, uint256 valHash); CClaimTrieProofNode() = default; CClaimTrieProofNode(CClaimTrieProofNode&&) = default; @@ -110,9 +110,9 @@ struct CClaimTrieProofNode CClaimTrieProofNode& operator=(CClaimTrieProofNode&&) = default; CClaimTrieProofNode& operator=(const CClaimTrieProofNode&) = default; - std::vector> children; + std::vector> children; bool hasValue; - CUint256 valHash; + uint256 valHash; }; struct CClaimTrieProof @@ -123,11 +123,11 @@ struct CClaimTrieProof CClaimTrieProof& operator=(CClaimTrieProof&&) = default; CClaimTrieProof& operator=(const CClaimTrieProof&) = default; - std::vector> pairs; + std::vector> pairs; std::vector nodes; int nHeightOfLastTakeover = 0; bool hasValue = false; - CTxOutPoint outPoint; + COutPoint outPoint; }; #endif // CLAIMTRIE_DATA_H diff --git a/src/claimtrie/forks.cpp b/src/claimtrie/forks.cpp index 86b3a6524..82fc18c17 100644 --- a/src/claimtrie/forks.cpp +++ b/src/claimtrie/forks.cpp @@ -198,7 +198,7 @@ bool CClaimTrieCacheNormalizationFork::decrementBlock() 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); } @@ -213,7 +213,7 @@ CClaimSupportToName CClaimTrieCacheNormalizationFork::getClaimsForName(const std 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); } @@ -227,10 +227,10 @@ CClaimTrieCacheHashFork::CClaimTrieCacheHashFork(CClaimTrie* base) : CClaimTrieC { } -static const auto leafHash = CUint256S("0000000000000000000000000000000000000000000000000000000000000002"); -static const auto emptyHash = CUint256S("0000000000000000000000000000000000000000000000000000000000000003"); +static const auto leafHash = uint256S("0000000000000000000000000000000000000000000000000000000000000002"); +static const auto emptyHash = uint256S("0000000000000000000000000000000000000000000000000000000000000003"); -CUint256 ComputeMerkleRoot(std::vector hashes) +uint256 ComputeMerkleRoot(std::vector hashes) { while (hashes.size() > 1) { if (hashes.size() & 1) @@ -242,23 +242,23 @@ CUint256 ComputeMerkleRoot(std::vector hashes) 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) return CClaimTrieCacheNormalizationFork::computeNodeHash(name, takeoverHeight); - std::vector childHashes; - childHashQuery << name >> [&childHashes](std::string, CUint256 hash) { + std::vector childHashes; + childHashQuery << name >> [&childHashes](std::string, uint256 hash) { childHashes.push_back(std::move(hash)); }; childHashQuery++; - std::vector claimHashes; + std::vector claimHashes; //if (takeoverHeight > 0) { - CTxOutPoint p; + COutPoint p; for (auto &&row: claimHashQuery << nNextHeight << name) { row >> p.hash >> p.n; 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()); } -std::vector ComputeMerklePath(const std::vector& hashes, uint32_t idx) +std::vector ComputeMerklePath(const std::vector& hashes, uint32_t idx) { uint32_t count = 0; int matchlevel = -1; bool matchh = false; - CUint256 inner[32], h; + uint256 inner[32], h; const uint32_t one = 1; - std::vector res; + std::vector res; const auto iterateInner = [&](int& level) { for (; !(count & (one << level)); level++) { @@ -329,12 +329,12 @@ std::vector ComputeMerklePath(const std::vector& hashes, uin 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) return CClaimTrieCacheNormalizationFork::getProofForName(name, claim, proof); - auto fillPairs = [&proof](const std::vector& hashes, uint32_t idx) { + auto fillPairs = [&proof](const std::vector& hashes, uint32_t idx) { auto partials = ComputeMerklePath(hashes, idx); for (int i = partials.size() - 1; i >= 0; --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; row >> key >> takeoverHeight; uint32_t nextCurrentIdx = 0; - std::vector childHashes; + std::vector childHashes; for (auto&& child : childHashQuery << key) { std::string childKey; - CUint256 childHash; + uint256 childHash; child >> childKey >> childHash; if (name.find(childKey) == 0) nextCurrentIdx = uint32_t(childHashes.size()); @@ -359,11 +359,11 @@ bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, const CUi } childHashQuery++; - std::vector claimHashes; + std::vector claimHashes; uint32_t claimIdx = 0; for (auto&& child: claimHashQuery << nNextHeight << key) { - CTxOutPoint childOutPoint; - CUint160 childClaimID; + COutPoint childOutPoint; + uint160 childClaimID; child >> childOutPoint.hash >> childOutPoint.n >> childClaimID; if (childClaimID == claim && key == name) { claimIdx = uint32_t(claimHashes.size()); @@ -417,4 +417,4 @@ bool CClaimTrieCacheHashFork::finalizeDecrement() bool CClaimTrieCacheHashFork::allowSupportMetadata() const { return nNextHeight >= base->nAllClaimsInMerkleForkHeight; -} \ No newline at end of file +} diff --git a/src/claimtrie/forks.h b/src/claimtrie/forks.h index b81424eaf..0e780bcc7 100644 --- a/src/claimtrie/forks.h +++ b/src/claimtrie/forks.h @@ -37,13 +37,13 @@ public: bool incrementBlock() 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; CClaimSupportToName getClaimsForName(const std::string& name) const override; std::string adjustNameForValidHeight(const std::string& name, int validHeight) const override; protected: - int getDelayForName(const std::string& name, const CUint160& claimId) const override; + int getDelayForName(const std::string& name, const uint160& claimId) const override; private: bool normalizeAllNamesInTrieIfNecessary(); @@ -55,14 +55,14 @@ class CClaimTrieCacheHashFork : public CClaimTrieCacheNormalizationFork public: 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; bool finalizeDecrement() override; bool allowSupportMetadata() const; protected: - CUint256 computeNodeHash(const std::string& name, int takeoverHeight) override; + uint256 computeNodeHash(const std::string& name, int takeoverHeight) override; }; typedef CClaimTrieCacheHashFork CClaimTrieCache; diff --git a/src/claimtrie/hashes.cpp b/src/claimtrie/hashes.cpp index 1debebdbe..e0a2f293f 100644 --- a/src/claimtrie/hashes.cpp +++ b/src/claimtrie/hashes.cpp @@ -2,9 +2,9 @@ #include // Bitcoin doubles hash -CUint256 CalcHash(SHA256_CTX* sha) +uint256 CalcHash(SHA256_CTX* sha) { - CUint256 result; + uint256 result; SHA256_Final(result.begin(), sha); SHA256_Init(sha); SHA256_Update(sha, result.begin(), result.size()); diff --git a/src/claimtrie/hashes.h b/src/claimtrie/hashes.h index 39a5894f1..10709377d 100644 --- a/src/claimtrie/hashes.h +++ b/src/claimtrie/hashes.h @@ -6,10 +6,10 @@ #include -CUint256 CalcHash(SHA256_CTX* sha); +uint256 CalcHash(SHA256_CTX* sha); template -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; 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 -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"); SHA256_CTX sha; diff --git a/src/claimtrie/libclaimtrie.i b/src/claimtrie/libclaimtrie.i index 654185451..a02bc2c51 100644 --- a/src/claimtrie/libclaimtrie.i +++ b/src/claimtrie/libclaimtrie.i @@ -1,6 +1,7 @@ %module(directors="1") libclaimtrie %{ +#include "blob.h" #include "uints.h" #include "txoutpoint.h" #include "data.h" @@ -13,6 +14,7 @@ %include stl.i %include stdint.i +%include std_array.i %include std_pair.i %apply int& OUTPUT { int& nValidAtHeight }; @@ -22,8 +24,15 @@ %ignore CClaimTrieProof(CClaimTrieProof &&); %ignore CClaimTrieProofNode(CClaimTrieProofNode &&); %ignore CClaimValue(CClaimValue &&); +%ignore COutPoint(COutPoint &&); %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 "txoutpoint.h" @@ -34,20 +43,16 @@ %include "trie.h" %include "forks.h" -%template(CUint160) CBaseBlob<160>; -%template(CUint256) CBaseBlob<256>; -%template(uint8vec) std::vector; - %template(claimEntryType) std::vector; %template(supportEntryType) std::vector; %template(claimsNsupports) std::vector; -%template(proofPair) std::pair; -%template(proofNodePair) std::pair; +%template(proofPair) std::pair; +%template(proofNodePair) std::pair; %template(proofNodes) std::vector; -%template(proofPairs) std::vector>; -%template(proofNodeChildren) std::vector>; +%template(proofPairs) std::vector>; +%template(proofNodeChildren) std::vector>; %inline %{ struct CIterateCallback { diff --git a/src/claimtrie/libclaimtrie_test.py b/src/claimtrie/libclaimtrie_test.py index 63c901492..bbc483ced 100644 --- a/src/claimtrie/libclaimtrie_test.py +++ b/src/claimtrie/libclaimtrie_test.py @@ -13,9 +13,9 @@ class CacheIterateCallback(CIterateCallback): class TestClaimTrieTypes(unittest.TestCase): def setUp(self): self.uint256s = "1234567890987654321012345678909876543210123456789098765432101234" - self.uint160 = CUint160S("1234567890987654321012345678909876543210") - self.uint = CUint256S(self.uint256s) - self.txp = CTxOutPoint(self.uint, 1) + self.uint160 = uint160S("1234567890987654321012345678909876543210") + self.uint = uint256S(self.uint256s) + self.txp = COutPoint(self.uint, 1) def assertClaimEqual(self, claim, txo, cid, amount, effe, height, validHeight, msg): self.assertEqual(claim.outPoint, txo, msg) @@ -34,14 +34,14 @@ class TestClaimTrieTypes(unittest.TestCase): def test_uint256(self): 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(), uint.ToString(), "incorrect CBaseBlob::ToString") self.assertEqual(uint.size(), 32, "incorrect CBaseBlob::size") - copy = CUint256() + copy = uint256() self.assertNotEqual(copy, uint, "incorrect CBaseBlob::operator!=") self.assertTrue(copy.IsNull(), "incorrect CBaseBlob::IsNull") - copy = CUint256(uint) + copy = uint256(uint) self.assertEqual(copy, uint, "incorrect CBaseBlob::operator==") copy.SetNull() self.assertTrue(copy.IsNull()), "incorrect CBaseBlob::SetNull" @@ -49,14 +49,14 @@ class TestClaimTrieTypes(unittest.TestCase): def test_txoupoint(self): txp = self.txp uint = self.uint - self.assertEqual(txp.hash, uint, "incorrect CTxOutPoint::CTxOutPoint") - self.assertEqual(txp.n, 1, "incorrect CTxOutPoint::CTxOutPoint") - self.assertFalse(txp.IsNull(), "incorrect CTxOutPoint::IsNull") - pcopy = CTxOutPoint() - self.assertTrue(pcopy.IsNull(), "incorrect CTxOutPoint::IsNull") - self.assertEqual(pcopy.hash, CUint256(), "incorrect CTxOutPoint::CTxOutPoint") - self.assertNotEqual(pcopy, txp, "incorrect CTxOutPoint::operator!=") - self.assertIn(uint.ToString()[:10], txp.ToString(), "incorrect CTxOutPoint::ToString") + self.assertEqual(txp.hash, uint, "incorrect COutPoint::COutPoint") + self.assertEqual(txp.n, 1, "incorrect COutPoint::COutPoint") + self.assertFalse(txp.IsNull(), "incorrect COutPoint::IsNull") + pcopy = COutPoint() + self.assertTrue(pcopy.IsNull(), "incorrect COutPoint::IsNull") + self.assertEqual(pcopy.hash, uint256(), "incorrect COutPoint::COutPoint") + self.assertNotEqual(pcopy, txp, "incorrect COutPoint::operator!=") + self.assertIn(uint.ToString()[:10], txp.ToString(), "incorrect COutPoint::ToString") def test_claim(self): txp = self.txp @@ -88,7 +88,7 @@ class TestClaimTrieTypes(unittest.TestCase): nValidAtHeight = -1 # add second claim txp.n = 2 - uint1601 = CUint160S("1234567890987654321012345678909876543211") + uint1601 = uint160S("1234567890987654321012345678909876543211") self.assertTrue(cache.addClaim("test", txp, uint1601, 20, 1, 1), "incorrect CClaimtrieCache::addClaim") result, nValidAtHeight = cache.haveClaimInQueue("test", txp) self.assertTrue(result, "incorrect CClaimTrieCache::haveClaimInQueue") diff --git a/src/claimtrie/sqlite.h b/src/claimtrie/sqlite.h index 74af4f733..3a5014a2f 100644 --- a/src/claimtrie/sqlite.h +++ b/src/claimtrie/sqlite.h @@ -10,19 +10,19 @@ 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); } - 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); } - 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); } - 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); } } @@ -31,11 +31,14 @@ namespace sqlite { + template<> + struct has_sqlite_type : std::true_type {}; template<> - struct has_sqlite_type : std::true_type {}; - inline CUint160 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type) { - CUint160 ret; + struct has_sqlite_type : std::true_type {}; + + inline uint160 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type) { + uint160 ret; auto ptr = sqlite3_column_blob(stmt, inx); if (!ptr) return ret; int bytes = sqlite3_column_bytes(stmt, inx); @@ -44,10 +47,8 @@ namespace sqlite return ret; } - template<> - struct has_sqlite_type : std::true_type {}; - inline CUint256 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type) { - CUint256 ret; + inline uint256 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type) { + uint256 ret; auto ptr = sqlite3_column_blob(stmt, inx); if (!ptr) return ret; int bytes = sqlite3_column_bytes(stmt, inx); diff --git a/src/claimtrie/trie.cpp b/src/claimtrie/trie.cpp index 6fe09a347..26e9d1816 100644 --- a/src/claimtrie/trie.cpp +++ b/src/claimtrie/trie.cpp @@ -10,7 +10,7 @@ #define logPrint CLogPrint::global() -static const auto one = CUint256S("0000000000000000000000000000000000000000000000000000000000000001"); +static const auto one = uint256S("0000000000000000000000000000000000000000000000000000000000000001"); std::vector heightToVch(int n) { @@ -22,7 +22,7 @@ std::vector heightToVch(int n) 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 snOut = std::to_string(outPoint.n); @@ -134,7 +134,7 @@ bool CClaimTrie::empty() 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 " "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(); } -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 " "AND activationHeight < ?4 AND expirationHeight >= ?4 LIMIT 1" @@ -165,7 +165,7 @@ supportEntryType CClaimTrieCacheBase::getSupportsForName(const std::string& name 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 = ? " "AND activationHeight >= ? AND expirationHeight >= activationHeight LIMIT 1" @@ -177,7 +177,7 @@ bool CClaimTrieCacheBase::haveClaimInQueue(const std::string& name, const CTxOut 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 = ? " "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 { - CUint160 claimId; + uint160 claimId; int nLastTakeoverHeight = 0; getLastTakeoverForName(name, claimId, nLastTakeoverHeight); @@ -399,18 +399,18 @@ CClaimSupportToName CClaimTrieCacheBase::getClaimsForName(const std::string& nam 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) 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(); std::vector vchToHash; // 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); vchToHash.push_back(name[pos]); 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"; for (auto&& row: query) { std::string name; - CUint256 hash; + uint256 hash; int takeoverHeight; row >> name >> hash >> takeoverHeight; auto computedHash = computeNodeHash(name, takeoverHeight); @@ -445,7 +445,7 @@ bool CClaimTrieCacheBase::checkConsistency() return true; } -bool CClaimTrieCacheBase::validateDb(int height, const CUint256& rootHash) +bool CClaimTrieCacheBase::validateDb(int height, const uint256& rootHash) { base->nNextHeight = nNextHeight = height + 1; @@ -523,12 +523,12 @@ int CClaimTrieCacheBase::expirationTime() const return base->nOriginalClaimExpirationTime; } -CUint256 CClaimTrieCacheBase::getMerkleHash() +uint256 CClaimTrieCacheBase::getMerkleHash() { ensureTreeStructureIsUpToDate(); - CUint256 hash; + uint256 hash; db << "SELECT hash FROM node WHERE name = x''" - >> [&hash](std::unique_ptr rootHash) { + >> [&hash](std::unique_ptr rootHash) { if (rootHash) hash = std::move(*rootHash); }; @@ -547,13 +547,13 @@ CUint256 CClaimTrieCacheBase::getMerkleHash() 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 " "WHERE t.name = ?1 ORDER BY t.height DESC LIMIT 1" << name; auto it = query.begin(); if (it != query.end()) { - std::unique_ptr claimIdOrNull; + std::unique_ptr claimIdOrNull; *it >> takeoverHeight >> claimIdOrNull; if (claimIdOrNull) { claimId = *claimIdOrNull; @@ -563,7 +563,7 @@ bool CClaimTrieCacheBase::getLastTakeoverForName(const std::string& name, CUint1 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) { ensureTransacting(); @@ -595,7 +595,7 @@ bool CClaimTrieCacheBase::addClaim(const std::string& name, const CTxOutPoint& o 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) { ensureTransacting(); @@ -616,7 +616,7 @@ bool CClaimTrieCacheBase::addSupport(const std::string& name, const CTxOutPoint& 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(); @@ -668,7 +668,7 @@ bool CClaimTrieCacheBase::removeClaim(const CUint160& claimId, const CTxOutPoint 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(); @@ -715,7 +715,7 @@ bool CClaimTrieCacheBase::incrementBlock() CClaimValue candidateValue; auto hasCandidate = getInfoForName(nameWithTakeover, candidateValue, 1); // now that they're all in get the winner: - CUint160 existingID; + uint160 existingID; int existingHeight = 0; auto hasCurrentWinner = getLastTakeoverForName(nameWithTakeover, existingID, existingHeight); // 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; } -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; auto hasCurrentWinner = getLastTakeoverForName(name, winningClaimId, winningTakeoverHeight); if (hasCurrentWinner && winningClaimId == claimId) { @@ -824,7 +824,7 @@ std::string CClaimTrieCacheBase::adjustNameForValidHeight(const std::string& nam 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 getMerkleHash(); @@ -835,25 +835,25 @@ bool CClaimTrieCacheBase::getProofForName(const std::string& name, const CUint16 int takeoverHeight; row >> key >> takeoverHeight; bool fNodeHasValue = getInfoForName(key, claim); - CUint256 valueHash; + uint256 valueHash; if (fNodeHasValue) valueHash = getValueHash(claim.outPoint, takeoverHeight); const auto pos = key.size(); - std::vector> children; + std::vector> children; for (auto&& child : childHashQuery << key) { std::string childKey; - CUint256 hash; + uint256 hash; child >> childKey >> hash; if (name.find(childKey) == 0) { 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); children.clear(); valueHash.SetNull(); fNodeHasValue = false; } - children.emplace_back(childKey.back(), CUint256{}); + children.emplace_back(childKey.back(), uint256{}); continue; } completeHash(hash, childKey, pos); @@ -897,8 +897,8 @@ void CClaimTrieCacheBase::getNamesInTrie(std::function }; } -std::vector CClaimTrieCacheBase::getActivatedClaims(int height) { - std::vector ret; +std::vector CClaimTrieCacheBase::getActivatedClaims(int height) { + std::vector ret; auto query = db << "SELECT DISTINCT claimID FROM claim WHERE activationHeight = ?1 AND blockHeight < ?1" << height; for (auto&& row: query) { ret.emplace_back(); @@ -906,8 +906,8 @@ std::vector CClaimTrieCacheBase::getActivatedClaims(int height) { } return ret; } -std::vector CClaimTrieCacheBase::getClaimsWithActivatedSupports(int height) { - std::vector ret; +std::vector CClaimTrieCacheBase::getClaimsWithActivatedSupports(int height) { + std::vector ret; auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE activationHeight = ?1 AND blockHeight < ?1" << height; for (auto&& row: query) { ret.emplace_back(); @@ -915,8 +915,8 @@ std::vector CClaimTrieCacheBase::getClaimsWithActivatedSupports(int he } return ret; } -std::vector CClaimTrieCacheBase::getExpiredClaims(int height) { - std::vector ret; +std::vector CClaimTrieCacheBase::getExpiredClaims(int height) { + std::vector ret; auto query = db << "SELECT DISTINCT claimID FROM claim WHERE expirationHeight = ?1 AND blockHeight < ?1" << height; for (auto&& row: query) { ret.emplace_back(); @@ -924,12 +924,12 @@ std::vector CClaimTrieCacheBase::getExpiredClaims(int height) { } return ret; } -std::vector CClaimTrieCacheBase::getClaimsWithExpiredSupports(int height) { - std::vector ret; +std::vector CClaimTrieCacheBase::getClaimsWithExpiredSupports(int height) { + std::vector ret; auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE expirationHeight = ?1 AND blockHeight < ?1" << height; for (auto&& row: query) { ret.emplace_back(); row >> ret.back(); } return ret; -} \ No newline at end of file +} diff --git a/src/claimtrie/trie.h b/src/claimtrie/trie.h index e5ff1bb15..5358678b4 100644 --- a/src/claimtrie/trie.h +++ b/src/claimtrie/trie.h @@ -13,7 +13,7 @@ #include #include -CUint256 getValueHash(const CTxOutPoint& outPoint, int nHeightOfLastTakeover); +uint256 getValueHash(const COutPoint& outPoint, int nHeightOfLastTakeover); class CClaimTrie { @@ -64,27 +64,27 @@ public: bool flush(); bool checkConsistency(); - CUint256 getMerkleHash(); - bool validateDb(int height, const CUint256& rootHash); + uint256 getMerkleHash(); + bool validateDb(int height, const uint256& rootHash); std::size_t getTotalNamesInTrie() const; std::size_t getTotalClaimsInTrie() const; int64_t getTotalValueOfClaimsInTrie(bool fControllingOnly) const; - bool haveClaim(const std::string& name, const CTxOutPoint& outPoint) const; - bool haveClaimInQueue(const std::string& name, const CTxOutPoint& outPoint, int& nValidAtHeight) const; + bool haveClaim(const std::string& name, const COutPoint& outPoint) const; + bool haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const; - bool haveSupport(const std::string& name, const CTxOutPoint& outPoint) const; - bool haveSupportInQueue(const std::string& name, const CTxOutPoint& outPoint, int& nValidAtHeight) const; + bool haveSupport(const std::string& name, const COutPoint& outPoint) 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); - 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); - bool removeClaim(const CUint160& claimId, const CTxOutPoint& outPoint, std::string& nodeName, int& validHeight); - bool removeSupport(const CTxOutPoint& outPoint, std::string& nodeName, int& validHeight); + bool removeClaim(const uint160& claimId, const COutPoint& outPoint, std::string& nodeName, int& validHeight); + bool removeSupport(const COutPoint& outPoint, std::string& nodeName, int& validHeight); virtual bool incrementBlock(); virtual bool decrementBlock(); @@ -92,20 +92,20 @@ public: 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 CClaimSupportToName getClaimsForName(const std::string& name) const; virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const; void getNamesInTrie(std::function 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 claim, CClaimValue& value, std::string& name) const; - std::vector getActivatedClaims(int height); - std::vector getClaimsWithActivatedSupports(int height); - std::vector getExpiredClaims(int height); - std::vector getClaimsWithExpiredSupports(int height); + std::vector getActivatedClaims(int height); + std::vector getClaimsWithActivatedSupports(int height); + std::vector getExpiredClaims(int height); + std::vector getClaimsWithExpiredSupports(int height); protected: 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; - 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; - 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); void ensureTreeStructureIsUpToDate(); diff --git a/src/claimtrie/txoutpoint.cpp b/src/claimtrie/txoutpoint.cpp index 2a514845c..1a16b1c49 100644 --- a/src/claimtrie/txoutpoint.cpp +++ b/src/claimtrie/txoutpoint.cpp @@ -3,40 +3,40 @@ #include -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(); n = uint32_t(-1); } -bool CTxOutPoint::IsNull() const +bool COutPoint::IsNull() const { 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); 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; } -bool CTxOutPoint::operator!=(const CTxOutPoint& b) const +bool COutPoint::operator!=(const COutPoint& b) const { return !(*this == b); } -std::string CTxOutPoint::ToString() const +std::string COutPoint::ToString() const { std::stringstream ss; - ss << "CTxOutPoint(" << hash.ToString().substr(0, 10) << ", " << n << ')'; + ss << "COutPoint(" << hash.ToString().substr(0, 10) << ", " << n << ')'; return ss.str(); } diff --git a/src/claimtrie/txoutpoint.h b/src/claimtrie/txoutpoint.h index 3a3755472..2398c97dc 100644 --- a/src/claimtrie/txoutpoint.h +++ b/src/claimtrie/txoutpoint.h @@ -11,26 +11,26 @@ #include /** An outpoint - a combination of a transaction hash and an index n into its vout */ -class CTxOutPoint +class COutPoint { public: - CUint256 hash; + uint256 hash; uint32_t n = uint32_t(-1); - CTxOutPoint() = default; - CTxOutPoint(CTxOutPoint&&) = default; - CTxOutPoint(const CTxOutPoint&) = default; - CTxOutPoint(CUint256 hashIn, uint32_t nIn); + COutPoint() = default; + COutPoint(COutPoint&&) = default; + COutPoint(const COutPoint&) = default; + COutPoint(uint256 hashIn, uint32_t nIn); - CTxOutPoint& operator=(CTxOutPoint&&) = default; - CTxOutPoint& operator=(const CTxOutPoint&) = default; + COutPoint& operator=(COutPoint&&) = default; + COutPoint& operator=(const COutPoint&) = default; void SetNull(); bool IsNull() const; - bool operator<(const CTxOutPoint& b) const; - bool operator==(const CTxOutPoint& b) const; - bool operator!=(const CTxOutPoint& b) const; + bool operator<(const COutPoint& b) const; + bool operator==(const COutPoint& b) const; + bool operator!=(const COutPoint& b) const; std::string ToString() const; }; diff --git a/src/claimtrie/uints.cpp b/src/claimtrie/uints.cpp index 016b1cf2e..169cc726f 100644 --- a/src/claimtrie/uints.cpp +++ b/src/claimtrie/uints.cpp @@ -1,173 +1,34 @@ #include -#include -#include -#include -#include -#include - -/** Template base class for fixed-sized opaque blobs. */ -template -CBaseBlob::CBaseBlob() : data(std::make_unique(WIDTH)) +uint160::uint160(const std::vector& vec) : CBaseBlob<160>(vec) { - SetNull(); } -template -CBaseBlob::CBaseBlob(const std::vector& vec) : data(std::make_unique(WIDTH)) +uint256::uint256(const std::vector& vec) : CBaseBlob<256>(vec) { - assert(vec.size() == size()); - std::copy(vec.begin(), vec.end(), begin()); } -template -CBaseBlob::CBaseBlob(const CBaseBlob& o) : data(std::make_unique(WIDTH)) +uint160 uint160S(const char* str) { - *this = o; -} - -template -CBaseBlob& CBaseBlob::operator=(const CBaseBlob& o) -{ - if (this != &o) - std::copy(o.begin(), o.end(), begin()); - return *this; -} - -template -bool CBaseBlob::IsNull() const -{ - return std::all_of(begin(), end(), [](uint8_t e) { return e == 0; }); -} - -template -void CBaseBlob::SetNull() -{ - std::memset(begin(), 0, size()); -} - -template -int CBaseBlob::Compare(const CBaseBlob& other) const -{ - return std::memcmp(begin(), other.begin(), size()); -} - -template -bool CBaseBlob::operator==(const CBaseBlob& b) const -{ - return Compare(b) == 0; -} - -template -bool CBaseBlob::operator!=(const CBaseBlob& b) const -{ - return Compare(b) != 0; -} - -template -bool CBaseBlob::operator<(const CBaseBlob& b) const -{ - return Compare(b) < 0; -} - -template -std::string CBaseBlob::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 -void CBaseBlob::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 -void CBaseBlob::SetHex(const std::string& str) -{ - SetHex(str.c_str()); -} - -template -std::string CBaseBlob::ToString() const -{ - return GetHex(); -} - -template -uint8_t* CBaseBlob::begin() -{ - return data.get(); -} - -template -uint8_t* CBaseBlob::end() -{ - return begin() + WIDTH; -} - -template -const uint8_t* CBaseBlob::begin() const -{ - return data.get(); -} - -template -const uint8_t* CBaseBlob::end() const -{ - return begin() + WIDTH; -} - -CUint160 CUint160S(const char* str) -{ - CUint160 s; + uint160 s; s.SetHex(str); 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); 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>; diff --git a/src/claimtrie/uints.h b/src/claimtrie/uints.h index 525d8c8d5..5edf1d052 100644 --- a/src/claimtrie/uints.h +++ b/src/claimtrie/uints.h @@ -2,59 +2,41 @@ #ifndef CLAIMTRIE_UINTS_H #define CLAIMTRIE_UINTS_H -#include +#include #include -#include -/** Template base class for fixed-sized opaque blobs. */ -template -class CBaseBlob +class uint160 : public CBaseBlob<160> { -protected: - static constexpr uint32_t WIDTH = BITS / 8; - std::unique_ptr data; public: - CBaseBlob(); + uint160() = default; - explicit CBaseBlob(const std::vector& vec); + explicit uint160(const std::vector& vec); - CBaseBlob(CBaseBlob&&) = default; - CBaseBlob& operator=(CBaseBlob&&) = default; + uint160(uint160&&) = default; + uint160& operator=(uint160&&) = default; - CBaseBlob(const CBaseBlob& o); - CBaseBlob& operator=(const CBaseBlob& o); - - 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; } + uint160(const uint160&) = default; + uint160& operator=(const uint160&) = default; }; -typedef CBaseBlob<160> CUint160; -typedef CBaseBlob<256> CUint256; +class uint256 : public CBaseBlob<256> +{ +public: + uint256() = default; -CUint160 CUint160S(const char* str); -CUint160 CUint160S(const std::string& s); + explicit uint256(const std::vector& vec); -CUint256 CUint256S(const char* str); -CUint256 CUint256S(const std::string& s); + uint256(uint256&&) = default; + 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 diff --git a/src/claimtrie_serial.h b/src/claimtrie_serial.h index 60599f167..638bdb7e4 100644 --- a/src/claimtrie_serial.h +++ b/src/claimtrie_serial.h @@ -6,27 +6,39 @@ #include #include -template -void Serialize(Stream& s, const CBaseBlob& u) +template +void Serialize(Stream& s, const uint160& u) { s.write((const char*)u.begin(), u.size()); } -template -void Unserialize(Stream& s, CBaseBlob& u) +template +void Serialize(Stream& s, const uint256& u) +{ + s.write((const char*)u.begin(), u.size()); +} + +template +void Unserialize(Stream& s, uint160& u) { s.read((char*)u.begin(), u.size()); } template -void Serialize(Stream& s, const CTxOutPoint& u) +void Unserialize(Stream& s, uint256& u) +{ + s.read((char*)u.begin(), u.size()); +} + +template +void Serialize(Stream& s, const COutPoint& u) { Serialize(s, u.hash); Serialize(s, u.n); } template -void Unserialize(Stream& s, CTxOutPoint& u) +void Unserialize(Stream& s, COutPoint& u) { Unserialize(s, u.hash); Unserialize(s, u.n); diff --git a/src/miner.cpp b/src/miner.cpp index 8b802ce72..3e2e9bcaf 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -200,7 +200,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc { CClaimTrieCache trieCache(pclaimTrie); blockToCache(pblock, trieCache, nHeight); - pblock->hashClaimTrie = uint256(trieCache.getMerkleHash()); + pblock->hashClaimTrie = trieCache.getMerkleHash(); } CValidationState state; if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp index 59865a5ea..ab08006d9 100644 --- a/src/primitives/transaction.cpp +++ b/src/primitives/transaction.cpp @@ -9,11 +9,6 @@ #include #include -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) { prevout = prevoutIn; diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h index 90b868161..23deab954 100644 --- a/src/primitives/transaction.h +++ b/src/primitives/transaction.h @@ -15,52 +15,6 @@ 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 - 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 * transaction's output that it claims and a signature that matches the * output's public key. diff --git a/src/pubkey.h b/src/pubkey.h index 089324ffd..2f36507fe 100644 --- a/src/pubkey.h +++ b/src/pubkey.h @@ -22,6 +22,18 @@ class CKeyID : public uint160 public: CKeyID() : uint160() {} explicit CKeyID(const uint160& in) : uint160(in) {} + + template + void Serialize(Stream& s) const + { + s.write((const char*)begin(), size()); + } + + template + void Unserialize(Stream& s) + { + s.read((char*)begin(), size()); + } }; typedef uint256 ChainCode; diff --git a/src/rpc/claimtrie.cpp b/src/rpc/claimtrie.cpp index 7edfe0fa7..9034dbfdb 100644 --- a/src/rpc/claimtrie.cpp +++ b/src/rpc/claimtrie.cpp @@ -132,7 +132,7 @@ std::vector seqSort(const std::vector& source) return claimsNsupports; } -std::size_t indexOf(const std::vector& source, const CUint160& claimId) +std::size_t indexOf(const std::vector& source, const uint160& claimId) { auto it = std::find_if(source.begin(), source.end(), [&claimId](const CClaimNsupports& claimNsupports) { return claimNsupports.claim.claimId == claimId; @@ -291,7 +291,7 @@ static UniValue getvalueforname(const JSONRPCRequest& request) return ret; auto& claimNsupports = - claimId.length() == claimIdHexLength ? csToName.find(CUint160S(claimId)) : + claimId.length() == claimIdHexLength ? csToName.find(uint160S(claimId)) : !claimId.empty() ? csToName.find(claimId) : csToName.claimsNsupports[0]; if (claimNsupports.IsNull()) @@ -541,11 +541,11 @@ UniValue getclaimsfortx(const JSONRPCRequest& request) std::string sName(vvchParams[0].begin(), vvchParams[0].end()); o.pushKV(T_NAME, escapeNonUtf8(sName)); if (op == OP_CLAIM_NAME) { - CUint160 claimId = ClaimIdHash(hash, i); + uint160 claimId = ClaimIdHash(hash, i); o.pushKV(T_CLAIMID, claimId.GetHex()); o.pushKV(T_VALUE, HexStr(vvchParams[1].begin(), vvchParams[1].end())); } else if (op == OP_UPDATE_CLAIM || op == OP_SUPPORT_CLAIM) { - CUint160 claimId(vvchParams[1]); + uint160 claimId(vvchParams[1]); o.pushKV(T_CLAIMID, claimId.GetHex()); if (vvchParams.size() > 2) o.pushKV(T_VALUE, HexStr(vvchParams[2].begin(), vvchParams[2].end())); diff --git a/src/serialize.h b/src/serialize.h index 848a7b6c2..393fd3981 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -10,7 +10,6 @@ #include #include -#include #include #include #include @@ -229,8 +228,7 @@ template inline void Serialize(Stream& s, bool a) { char f=a template inline void Unserialize(Stream& s, bool& a) { char f=ser_readdata8(s); a=f; } - - +#include /** diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp index f57d0c6d7..81cd481a4 100644 --- a/src/test/addrman_tests.cpp +++ b/src/test/addrman_tests.cpp @@ -34,7 +34,8 @@ public: 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); } diff --git a/src/test/claimtriebranching_tests.cpp b/src/test/claimtriebranching_tests.cpp index e69a2ac03..29cbb40da 100644 --- a/src/test/claimtriebranching_tests.cpp +++ b/src/test/claimtriebranching_tests.cpp @@ -31,7 +31,7 @@ BOOST_AUTO_TEST_CASE(takeover_stability_test) { CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "@bass", "two", 2); fixture.IncrementBlocks(1); BOOST_CHECK(fixture.is_best_claim("@bass", tx2)); - CUint160 id; int takeover; + uint160 id; int takeover; BOOST_REQUIRE(fixture.getLastTakeoverForName("@bass", id, takeover)); auto height = chainActive.Tip()->nHeight; 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); auto cid = ClaimIdHash(tx1.GetHash(), 0); fixture.IncrementBlocks(1); - CUint160 cid2; + uint160 cid2; int takeover; int height = chainActive.Tip()->nHeight; 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); fixture.IncrementBlocks(1); - CUint160 claimId; + uint160 claimId; int lastTakeover; BOOST_CHECK(fixture.getLastTakeoverForName(name, claimId, lastTakeover)); BOOST_CHECK_EQUAL(lastTakeover, height + 1); diff --git a/src/test/claimtriecache_tests.cpp b/src/test/claimtriecache_tests.cpp index 299bfd026..30305e1c2 100644 --- a/src/test/claimtriecache_tests.cpp +++ b/src/test/claimtriecache_tests.cpp @@ -30,7 +30,7 @@ public: 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; std::string nodeName; @@ -51,7 +51,7 @@ public: 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; std::string nodeName; @@ -70,7 +70,7 @@ BOOST_FIXTURE_TEST_SUITE(claimtriecache_tests, RegTestingSetup) BOOST_AUTO_TEST_CASE(merkle_hash_single_test) { // check empty trie - auto one = CUint256S("0000000000000000000000000000000000000000000000000000000000000001"); + auto one = uint256S("0000000000000000000000000000000000000000000000000000000000000001"); CClaimTrieCacheTest cc(pclaimTrie); 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) { auto hash0 = uint256S("0000000000000000000000000000000000000000000000000000000000000001"); - CUint160 hash160; + uint160 hash160; CMutableTransaction tx1 = BuildTransaction(hash0); - CTxOutPoint tx1OutPoint(tx1.GetHash(), 0); + COutPoint tx1OutPoint(tx1.GetHash(), 0); CMutableTransaction tx2 = BuildTransaction(tx1.GetHash()); - CTxOutPoint tx2OutPoint(tx2.GetHash(), 0); + COutPoint tx2OutPoint(tx2.GetHash(), 0); CMutableTransaction tx3 = BuildTransaction(tx2.GetHash()); - CTxOutPoint tx3OutPoint(tx3.GetHash(), 0); + COutPoint tx3OutPoint(tx3.GetHash(), 0); CMutableTransaction tx4 = BuildTransaction(tx3.GetHash()); - CTxOutPoint tx4OutPoint(tx4.GetHash(), 0); + COutPoint tx4OutPoint(tx4.GetHash(), 0); CMutableTransaction tx5 = BuildTransaction(tx4.GetHash()); - CTxOutPoint tx5OutPoint(tx5.GetHash(), 0); + COutPoint tx5OutPoint(tx5.GetHash(), 0); CMutableTransaction tx6 = BuildTransaction(tx5.GetHash()); - CTxOutPoint tx6OutPoint(tx6.GetHash(), 0); + COutPoint tx6OutPoint(tx6.GetHash(), 0); - CUint256 hash1; + uint256 hash1; hash1.SetHex("71c7b8d35b9a3d7ad9a1272b68972979bbd18589f1efe6f27b0bf260a6ba78fa"); - CUint256 hash2; + uint256 hash2; hash2.SetHex("c4fc0e2ad56562a636a0a237a96a5f250ef53495c2cb5edd531f087a8de83722"); - CUint256 hash3; + uint256 hash3; hash3.SetHex("baf52472bd7da19fe1e35116cfb3bd180d8770ffbe3ae9243df1fb58a14b0975"); - CUint256 hash4; + uint256 hash4; hash4.SetHex("c73232a755bf015f22eaa611b283ff38100f2a23fb6222e86eca363452ba0c51"); { @@ -215,8 +215,8 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test) // create and insert claim auto hash0 = uint256S("0000000000000000000000000000000000000000000000000000000000000001"); CMutableTransaction tx1 = BuildTransaction(hash0); - CUint160 claimId = ClaimIdHash(tx1.GetHash(), 0); - CTxOutPoint claimOutPoint(tx1.GetHash(), 0); + uint160 claimId = ClaimIdHash(tx1.GetHash(), 0); + COutPoint claimOutPoint(tx1.GetHash(), 0); CAmount amount(10); int height = 0; int validHeight = 0; @@ -239,7 +239,7 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test) CAmount supportAmount(10); auto hash1 = uint256S("0000000000000000000000000000000000000000000000000000000000000002"); CMutableTransaction tx2 = BuildTransaction(hash1); - CTxOutPoint supportOutPoint(tx2.GetHash(), 0); + COutPoint supportOutPoint(tx2.GetHash(), 0); CSupportValue support(supportOutPoint, claimId, supportAmount, height, validHeight); ctc.insertSupportIntoMap("test", support); @@ -257,7 +257,7 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test) // CClaimTrieCacheTest cc(pclaimTrie); // BOOST_CHECK_EQUAL(0, cc.getTotalClaimsInTrie()); // -// CTxOutPoint outpoint; +// COutPoint outpoint; // uint160 claimId; // CAmount amount(20); // int height = 0; @@ -318,7 +318,7 @@ BOOST_AUTO_TEST_CASE(trie_stays_consistent_test) for (auto& name: names) { 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(); BOOST_CHECK(cache.checkConsistency()); } @@ -328,7 +328,7 @@ BOOST_AUTO_TEST_CASE(trie_stays_consistent_test) BOOST_AUTO_TEST_CASE(verify_basic_serialization) { CClaimValue cv; - cv.outPoint = CTxOutPoint(CUint256S("123"), 2); + cv.outPoint = COutPoint(uint256S("123"), 2); cv.nHeight = 3; cv.claimId.SetHex("4567"); cv.nEffectiveAmount = 4; diff --git a/src/test/claimtriefixture.cpp b/src/test/claimtriefixture.cpp index b61117add..b7aa05794 100644 --- a/src/test/claimtriefixture.cpp +++ b/src/test/claimtriefixture.cpp @@ -404,7 +404,7 @@ boost::test_tools::predicate_result ClaimTrieChainFixture::best_claim_effective_ 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 " "FROM claim WHERE claimID = ?" << claimId; diff --git a/src/test/claimtriefixture.h b/src/test/claimtriefixture.h index dd010ee82..61274c3cb 100644 --- a/src/test/claimtriefixture.h +++ b/src/test/claimtriefixture.h @@ -103,7 +103,7 @@ struct ClaimTrieChainFixture: public CClaimTrieCache 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 boost::test_tools::predicate_result is_claim_in_queue(const std::string& name, const CTransaction &tx); diff --git a/src/test/claimtriehashfork_tests.cpp b/src/test/claimtriehashfork_tests.cpp index d37628a24..3be8d78d5 100644 --- a/src/test/claimtriehashfork_tests.cpp +++ b/src/test/claimtriehashfork_tests.cpp @@ -8,7 +8,7 @@ using namespace std; -void ValidatePairs(CClaimTrieCache& cache, const std::vector>& pairs, CUint256 claimHash) +void ValidatePairs(CClaimTrieCache& cache, const std::vector>& pairs, uint256 claimHash) { for (auto& pair : pairs) 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; bool verifiedValue = false; @@ -190,7 +190,7 @@ bool verify_proof(const CClaimTrieProof proof, CUint256 rootHash, const std::str std::vector vchToHash; for (auto itChildren = itNodes->children.begin(); itChildren != itNodes->children.end(); ++itChildren) { vchToHash.push_back(itChildren->first); - CUint256 childHash; + uint256 childHash; if (itChildren->second.IsNull()) { if (previousComputedHash.IsNull()) { return false; @@ -210,7 +210,7 @@ bool verify_proof(const CClaimTrieProof proof, CUint256 rootHash, const std::str return false; } if (itNodes->hasValue) { - CUint256 valHash; + uint256 valHash; if (itNodes->valHash.IsNull()) { if (itNodes != proof.nodes.rbegin()) { return false; @@ -233,7 +233,7 @@ bool verify_proof(const CClaimTrieProof proof, CUint256 rootHash, const std::str std::vector vchHash(hasher.OUTPUT_SIZE); hasher.Write(vchToHash.data(), vchToHash.size()); hasher.Finalize(&(vchHash[0])); - CUint256 calculatedHash(vchHash); + uint256 calculatedHash(vchHash); previousComputedHash = calculatedHash; } if (previousComputedHash != rootHash) { diff --git a/src/test/claimtrierpc_tests.cpp b/src/test/claimtrierpc_tests.cpp index 67a5d67c2..6fd149565 100644 --- a/src/test/claimtrierpc_tests.cpp +++ b/src/test/claimtrierpc_tests.cpp @@ -8,7 +8,7 @@ using namespace std; -extern void ValidatePairs(CClaimTrieCache& cache, const std::vector>& pairs, CUint256 claimHash); +extern void ValidatePairs(CClaimTrieCache& cache, const std::vector>& pairs, uint256 claimHash); 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); } -std::vector> jsonToPairs(const UniValue& jsonPair) +std::vector> jsonToPairs(const UniValue& jsonPair) { - std::vector> pairs; + std::vector> pairs; for (std::size_t i = 0; i < jsonPair.size(); ++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; } diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp index 2504231e7..4afc43ae3 100644 --- a/src/test/test_bitcoin.cpp +++ b/src/test/test_bitcoin.cpp @@ -62,24 +62,6 @@ std::ostream& operator<<(std::ostream& os, const COutPoint& point) 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) { os << claim.ToString(); diff --git a/src/test/test_bitcoin.h b/src/test/test_bitcoin.h index 2e4238fa7..3d74dd3e6 100644 --- a/src/test/test_bitcoin.h +++ b/src/test/test_bitcoin.h @@ -134,10 +134,6 @@ std::ostream& operator<<(std::ostream& os, const uint160& num); class COutPoint; 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 CSupportValue; std::ostream& operator<<(std::ostream& os, const CClaimValue& claim); diff --git a/src/txdb.h b/src/txdb.h index a70ab9155..1a770c588 100644 --- a/src/txdb.h +++ b/src/txdb.h @@ -26,16 +26,10 @@ namespace sqlite { inline void store_result_in_db(sqlite3_context* db, const CScript& val) { 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 + namespace sqlite { template<> struct has_sqlite_type : std::true_type {}; @@ -47,26 +41,6 @@ namespace sqlite { assert(bytes >= 0); return CScript(ptr, ptr + bytes); } - - template<> - struct has_sqlite_type : std::true_type {}; - - inline uint256 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type) { - 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; diff --git a/src/uint256.cpp b/src/uint256.cpp index e513dc1de..98bb128dd 100644 --- a/src/uint256.cpp +++ b/src/uint256.cpp @@ -3,77 +3,10 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include #include -#include - -#include -#include - -template -base_blob::base_blob(const std::vector& vch) +uint64_t GetCheapHash(const uint256& hash) { - assert(vch.size() == sizeof(data)); - memcpy(data, vch.data(), sizeof(data)); + return ReadLE64(hash.begin()); } - -template -std::string base_blob::GetHex() const -{ - return HexStr(std::reverse_iterator(data + sizeof(data)), std::reverse_iterator(data)); -} - -template -void base_blob::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 -void base_blob::SetHex(const std::string& str) -{ - SetHex(str.c_str()); -} - -template -std::string base_blob::ToString() const -{ - return (GetHex()); -} - -// Explicit instantiations for base_blob<160> -template base_blob<160>::base_blob(const std::vector&); -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&); -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&); diff --git a/src/uint256.h b/src/uint256.h index 6cb77e632..b878bcdda 100644 --- a/src/uint256.h +++ b/src/uint256.h @@ -6,166 +6,8 @@ #ifndef BITCOIN_UINT256_H #define BITCOIN_UINT256_H -#include -#include -#include -#include -#include -#include -#include - #include -/** Template base class for fixed-sized opaque blobs. */ -template -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& b) - { - std::copy(b.begin(), b.end(), begin()); - } - - explicit base_blob(const std::vector& 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 - void Serialize(Stream& s) const - { - s.write((char*)data, sizeof(data)); - } - - template - void Unserialize(Stream& s) - { - s.read((char*)data, sizeof(data)); - } - - operator CBaseBlob() const - { - CBaseBlob 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; -} +uint64_t GetCheapHash(const uint256& hash); #endif // BITCOIN_UINT256_H diff --git a/src/validation.cpp b/src/validation.cpp index 2803e573f..dd9e1b698 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -1503,20 +1503,12 @@ int ApplyTxInUndo(unsigned int index, CTxUndo& txUndo, CCoinsViewCache& view, CC return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN; } -template -inline bool equals(const T1& hash1, const T2& hash2) -{ - static_assert((std::is_same::value && std::is_same::value) || - (std::is_same::value && std::is_same::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. * When FAILED is returned, view is left in an indeterminate state. */ DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view, CClaimTrieCache& trieCache) { 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", __func__, pindex->hashClaimTrie.ToString(), trieCache.getMerkleHash().ToString()); assert(false); @@ -1590,7 +1582,7 @@ DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockI // move best block pointer to prevout block view.SetBestBlock(pindex->pprev->GetBlockHash()); 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); assert(false); } @@ -1803,7 +1795,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl assert(hashPrevBlock == view.GetBestBlock()); // 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", __func__, pindex->pprev->hashClaimTrie.ToString(), trieCache.getMerkleHash().ToString()); 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. 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 " "(actual=%s vs block=%s on height=%d)", trieCache.getMerkleHash().GetHex(), 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(); assert(flushed); 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); // Write the chain state to disk, if necessary. diff --git a/src/validation.h b/src/validation.h index 8d87b738f..d1369c048 100644 --- a/src/validation.h +++ b/src/validation.h @@ -141,7 +141,7 @@ static const int DEFAULT_STOPATHEIGHT = 0; 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;