Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9e83ba216 | ||
|
|
c309f811c1 | ||
|
|
fbf7de9fb2 | ||
|
|
1583082acc | ||
|
|
f71d6a4263 | ||
|
|
d2b78a7fc3 | ||
|
|
a98288aa80 | ||
|
|
3a0b4232a5 | ||
|
|
5bdbc9e0d6 | ||
|
|
9d4ef899a6 | ||
|
|
d0e8374636 | ||
|
|
d2b26da3e8 | ||
|
|
59faea9815 | ||
|
|
ce6be620a5 | ||
|
|
580f6e20eb | ||
|
|
7d93edf776 | ||
|
|
b3c5b1e88d | ||
|
|
a84c196916 | ||
|
|
b52f47f273 | ||
|
|
e9d37a8c81 | ||
|
|
d96253cd40 | ||
|
|
4a5d310fd3 | ||
|
|
c6e267e970 | ||
|
|
7b5ae24bea | ||
|
|
92037d786a | ||
|
|
494c48875d | ||
|
|
fc0da99894 | ||
|
|
20e96d1233 |
No files matched your search
+2
-2
@@ -68,7 +68,7 @@ jobs:
|
||||
- mkdir -p testrun && cd testrun
|
||||
- curl http://build.lbry.io/lbrycrd/${TRAVIS_BRANCH}/lbrycrd-${NAME}-test.zip -o temp.zip
|
||||
- unzip temp.zip
|
||||
script: ./test_lbrycrd
|
||||
script: TRIEHASH_FUZZER_BLOCKS=1000 ./test_lbrycrd
|
||||
|
||||
- <<: *test-template
|
||||
# os: windows # doesn't support secrets at the moment
|
||||
@@ -79,7 +79,7 @@ jobs:
|
||||
- docker
|
||||
script:
|
||||
- docker pull $DOCKER_WINE_IMAGE
|
||||
- docker run -v "$(pwd):/test" -e "WINEDEBUG=-all" -it $DOCKER_WINE_IMAGE wine "/test/test_lbrycrd.exe"
|
||||
- docker run -v "$(pwd):/test" -e "WINEDEBUG=-all" -e "TRIEHASH_FUZZER_BLOCKS=1000" -it $DOCKER_WINE_IMAGE wine "/test/test_lbrycrd.exe"
|
||||
|
||||
- <<: *test-template
|
||||
os: osx
|
||||
|
||||
@@ -155,6 +155,7 @@ BITCOIN_CORE_H = \
|
||||
reverse_iterator.h \
|
||||
reverselock.h \
|
||||
rpc/blockchain.h \
|
||||
rpc/claimrpchelp.h \
|
||||
rpc/client.h \
|
||||
rpc/mining.h \
|
||||
rpc/protocol.h \
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <bloom.h>
|
||||
#include <nameclaim.h>
|
||||
|
||||
#include <primitives/transaction.h>
|
||||
#include <hash.h>
|
||||
|
||||
+12
-7
@@ -144,7 +144,9 @@ public:
|
||||
consensus.nAllowMinDiffMaxHeight = -1;
|
||||
consensus.nNormalizedNameForkHeight = 539940; // targeting 21 March 2019
|
||||
consensus.nMinTakeoverWorkaroundHeight = 496850;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 10000000;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 654400; // targeting 30 Oct 2019
|
||||
consensus.nWitnessForkHeight = 676900; // targeting 11 Dec 2019
|
||||
consensus.nAllClaimsInMerkleForkHeight = 654400; // targeting 30 Oct 2019
|
||||
consensus.fPowAllowMinDifficultyBlocks = false;
|
||||
consensus.fPowNoRetargeting = false;
|
||||
consensus.nRuleChangeActivationThreshold = 1916; // 95% of a half week
|
||||
@@ -158,17 +160,16 @@ public:
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1462060800; // May 1st, 2016
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017
|
||||
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147)
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147) -- Unused (see nWitnessForkHeight).
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1547942400; // Jan 20, 2019
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1548288000; // Jan 24, 2019
|
||||
|
||||
// The best chain should have at least this much work.
|
||||
consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000000000607ca7e806c4c1e9"); //400000
|
||||
consensus.nMinimumChainWork = uint256S("00000000000000000000000000000000000000000000024108e3204a44a57a5a"); //621000
|
||||
|
||||
// By default assume that the signatures in ancestors of this block are valid.
|
||||
//consensus.defaultAssumeValid = uint256S("0xf0e56e70782af63ccb49c76e852540688755869ba59ec68cac9c04a6b4d9f5ca"); //400000
|
||||
consensus.defaultAssumeValid = uint256S("0xa6bbb48f5343eb9b0287c22f3ea8b29f36cf10794a37f8a925a894d6f4519913"); //4000
|
||||
consensus.defaultAssumeValid = uint256S("7899464514d0d8854919e87eb234fd5f0c35d06418bd5fd3c1a8f7092b2a9317"); //620000
|
||||
|
||||
/**
|
||||
* The message start string is designed to be unlikely to occur in normal data.
|
||||
@@ -261,7 +262,9 @@ public:
|
||||
consensus.nAllowMinDiffMaxHeight = 1100000;
|
||||
consensus.nNormalizedNameForkHeight = 993380; // targeting, 21 Feb 2019
|
||||
consensus.nMinTakeoverWorkaroundHeight = 99;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 10000000;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 1181920; // targeting 29 Sep 2019
|
||||
consensus.nWitnessForkHeight = 1181950;
|
||||
consensus.nAllClaimsInMerkleForkHeight = 1181920; // targeting 29 Sep 2019
|
||||
consensus.fPowAllowMinDifficultyBlocks = true;
|
||||
consensus.fPowNoRetargeting = false;
|
||||
consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
|
||||
@@ -275,7 +278,7 @@ public:
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017
|
||||
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147)
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147) -- Unused (see nWitnessForkHeight).
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1462060800; // May 1st 2016
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1493596800; // May 1st 2017
|
||||
@@ -367,6 +370,8 @@ public:
|
||||
consensus.nNormalizedNameForkHeight = 250; // SDK depends upon this number
|
||||
consensus.nMinTakeoverWorkaroundHeight = -1;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = -1;
|
||||
consensus.nWitnessForkHeight = 150;
|
||||
consensus.nAllClaimsInMerkleForkHeight = 350;
|
||||
consensus.fPowAllowMinDifficultyBlocks = false;
|
||||
consensus.fPowNoRetargeting = false;
|
||||
consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
|
||||
|
||||
+12
-12
@@ -59,17 +59,17 @@ public:
|
||||
*/
|
||||
CClaimScriptAddOp(const COutPoint& point, CAmount nValue, int nHeight);
|
||||
/**
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
@@ -100,17 +100,17 @@ public:
|
||||
*/
|
||||
CClaimScriptUndoAddOp(const COutPoint& point, int nHeight);
|
||||
/**
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
@@ -141,17 +141,17 @@ public:
|
||||
*/
|
||||
CClaimScriptSpendOp(const COutPoint& point, int nHeight, int& nValidHeight);
|
||||
/**
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
@@ -184,17 +184,17 @@ public:
|
||||
*/
|
||||
CClaimScriptUndoSpendOp(const COutPoint& point, CAmount nValue, int nHeight, int nValidHeight);
|
||||
/**
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
|
||||
+497
-328
File diff suppressed because it is too large.
Load diff
+242
-84
@@ -18,11 +18,13 @@
|
||||
#include <unordered_set>
|
||||
|
||||
// leveldb keys
|
||||
#define TRIE_NODE 'n'
|
||||
#define TRIE_NODE 'n' // deprecated
|
||||
#define TRIE_NODE_CHILDREN 'b'
|
||||
#define TRIE_NODE_CLAIMS 'c'
|
||||
#define CLAIM_BY_ID 'i'
|
||||
#define CLAIM_QUEUE_ROW 'r'
|
||||
#define CLAIM_QUEUE_NAME_ROW 'm'
|
||||
#define EXP_QUEUE_ROW 'e'
|
||||
#define CLAIM_EXP_QUEUE_ROW 'e'
|
||||
#define SUPPORT 's'
|
||||
#define SUPPORT_QUEUE_ROW 'u'
|
||||
#define SUPPORT_QUEUE_NAME_ROW 'p'
|
||||
@@ -34,10 +36,10 @@ struct CClaimValue
|
||||
{
|
||||
COutPoint outPoint;
|
||||
uint160 claimId;
|
||||
CAmount nAmount;
|
||||
CAmount nEffectiveAmount;
|
||||
int nHeight;
|
||||
int nValidAtHeight;
|
||||
CAmount nAmount = 0;
|
||||
CAmount nEffectiveAmount = 0;
|
||||
int nHeight = 0;
|
||||
int nValidAtHeight = 0;
|
||||
|
||||
CClaimValue() = default;
|
||||
|
||||
@@ -61,6 +63,7 @@ struct CClaimValue
|
||||
READWRITE(nAmount);
|
||||
READWRITE(nHeight);
|
||||
READWRITE(nValidAtHeight);
|
||||
READWRITE(nEffectiveAmount);
|
||||
}
|
||||
|
||||
bool operator<(const CClaimValue& other) const
|
||||
@@ -91,9 +94,9 @@ struct CSupportValue
|
||||
{
|
||||
COutPoint outPoint;
|
||||
uint160 supportedClaimId;
|
||||
CAmount nAmount;
|
||||
int nHeight;
|
||||
int nValidAtHeight;
|
||||
CAmount nAmount = 0;
|
||||
int nHeight = 0;
|
||||
int nValidAtHeight = 0;
|
||||
|
||||
CSupportValue() = default;
|
||||
|
||||
@@ -133,12 +136,21 @@ struct CSupportValue
|
||||
typedef std::vector<CClaimValue> claimEntryType;
|
||||
typedef std::vector<CSupportValue> supportEntryType;
|
||||
|
||||
enum CClaimTrieDataFlags: uint32_t {
|
||||
HASH_DIRTY = 1U,
|
||||
CLAIMS_DIRTY = 2U,
|
||||
CAME_FROM_NODE_CACHE = 4U,
|
||||
};
|
||||
|
||||
struct CClaimTrieData
|
||||
{
|
||||
uint256 hash;
|
||||
claimEntryType claims;
|
||||
int nHeightOfLastTakeover = 0;
|
||||
|
||||
// non-serialized data:
|
||||
uint32_t flags = 0;
|
||||
uint256 hash;
|
||||
|
||||
CClaimTrieData() = default;
|
||||
CClaimTrieData(CClaimTrieData&&) = default;
|
||||
CClaimTrieData(const CClaimTrieData&) = default;
|
||||
@@ -156,25 +168,13 @@ struct CClaimTrieData
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action)
|
||||
{
|
||||
READWRITE(hash);
|
||||
|
||||
if (ser_action.ForRead()) {
|
||||
if (s.eof()) {
|
||||
claims.clear();
|
||||
nHeightOfLastTakeover = 0;
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (claims.empty())
|
||||
return;
|
||||
|
||||
READWRITE(claims);
|
||||
READWRITE(nHeightOfLastTakeover);
|
||||
}
|
||||
|
||||
bool operator==(const CClaimTrieData& other) const
|
||||
{
|
||||
return hash == other.hash && nHeightOfLastTakeover == other.nHeightOfLastTakeover && claims == other.claims;
|
||||
return nHeightOfLastTakeover == other.nHeightOfLastTakeover && claims == other.claims;
|
||||
}
|
||||
|
||||
bool operator!=(const CClaimTrieData& other) const
|
||||
@@ -188,10 +188,33 @@ struct CClaimTrieData
|
||||
}
|
||||
};
|
||||
|
||||
struct CClaimTrieDataNode
|
||||
{
|
||||
uint256 hash;
|
||||
// we're using a vector to avoid RAM thrashing and for faster serialization ops.
|
||||
// We're assuming its data is inserted in order and never modified.
|
||||
std::vector<std::string> children;
|
||||
|
||||
CClaimTrieDataNode() = default;
|
||||
CClaimTrieDataNode(CClaimTrieDataNode&&) = default;
|
||||
CClaimTrieDataNode(const CClaimTrieDataNode&) = default;
|
||||
CClaimTrieDataNode& operator=(CClaimTrieDataNode&&) = default;
|
||||
CClaimTrieDataNode& operator=(const CClaimTrieDataNode& d) = default;
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action)
|
||||
{
|
||||
READWRITE(hash);
|
||||
READWRITE(children);
|
||||
}
|
||||
};
|
||||
|
||||
struct COutPointHeightType
|
||||
{
|
||||
COutPoint outPoint;
|
||||
int nHeight;
|
||||
int nHeight = 0;
|
||||
|
||||
COutPointHeightType() = default;
|
||||
|
||||
@@ -214,7 +237,7 @@ struct CNameOutPointHeightType
|
||||
{
|
||||
std::string name;
|
||||
COutPoint outPoint;
|
||||
int nHeight;
|
||||
int nHeight = 0;
|
||||
|
||||
CNameOutPointHeightType() = default;
|
||||
|
||||
@@ -283,35 +306,75 @@ struct CClaimIndexElement
|
||||
CClaimValue claim;
|
||||
};
|
||||
|
||||
struct CClaimsForNameType
|
||||
struct CClaimNsupports
|
||||
{
|
||||
claimEntryType claims;
|
||||
supportEntryType supports;
|
||||
int nLastTakeoverHeight;
|
||||
std::string name;
|
||||
CClaimNsupports() = default;
|
||||
CClaimNsupports(CClaimNsupports&&) = default;
|
||||
CClaimNsupports(const CClaimNsupports&) = default;
|
||||
|
||||
CClaimsForNameType(claimEntryType claims, supportEntryType supports, int nLastTakeoverHeight, std::string name)
|
||||
: claims(std::move(claims)), supports(std::move(supports)), nLastTakeoverHeight(nLastTakeoverHeight), name(std::move(name))
|
||||
CClaimNsupports& operator=(CClaimNsupports&&) = default;
|
||||
CClaimNsupports& operator=(const CClaimNsupports&) = default;
|
||||
|
||||
CClaimNsupports(const CClaimValue& claim, CAmount effectiveAmount, const std::vector<CSupportValue>& supports = {})
|
||||
: claim(claim), effectiveAmount(effectiveAmount), supports(supports)
|
||||
{
|
||||
}
|
||||
|
||||
CClaimsForNameType(CClaimsForNameType&&) = default;
|
||||
CClaimsForNameType(const CClaimsForNameType&) = default;
|
||||
CClaimsForNameType& operator=(CClaimsForNameType&&) = default;
|
||||
CClaimsForNameType& operator=(const CClaimsForNameType&) = default;
|
||||
bool IsNull() const
|
||||
{
|
||||
return claim.claimId.IsNull();
|
||||
}
|
||||
|
||||
CClaimValue claim;
|
||||
CAmount effectiveAmount = 0;
|
||||
std::vector<CSupportValue> supports;
|
||||
};
|
||||
|
||||
class CClaimTrie : public CPrefixTrie<std::string, CClaimTrieData>
|
||||
{
|
||||
int nNextHeight = 0;
|
||||
int nProportionalDelayFactor = 0;
|
||||
std::unique_ptr<CDBWrapper> db;
|
||||
static const CClaimNsupports invalid;
|
||||
|
||||
struct CClaimSupportToName
|
||||
{
|
||||
CClaimSupportToName(const std::string& name, int nLastTakeoverHeight, std::vector<CClaimNsupports> claimsNsupports, std::vector<CSupportValue> unmatchedSupports)
|
||||
: name(name), nLastTakeoverHeight(nLastTakeoverHeight), claimsNsupports(std::move(claimsNsupports)), unmatchedSupports(std::move(unmatchedSupports))
|
||||
{
|
||||
}
|
||||
|
||||
const CClaimNsupports& find(const uint160& claimId) const
|
||||
{
|
||||
auto it = std::find_if(claimsNsupports.begin(), claimsNsupports.end(), [&claimId](const CClaimNsupports& value) {
|
||||
return claimId == value.claim.claimId;
|
||||
});
|
||||
return it != claimsNsupports.end() ? *it : invalid;
|
||||
}
|
||||
|
||||
const CClaimNsupports& find(const std::string& partialId) const
|
||||
{
|
||||
std::string lowered(partialId);
|
||||
for (auto& c: lowered)
|
||||
c = std::tolower(c);
|
||||
|
||||
auto it = std::find_if(claimsNsupports.begin(), claimsNsupports.end(), [&lowered](const CClaimNsupports& value) {
|
||||
return value.claim.claimId.GetHex().find(lowered) == 0;
|
||||
});
|
||||
return it != claimsNsupports.end() ? *it : invalid;
|
||||
}
|
||||
|
||||
const std::string name;
|
||||
const int nLastTakeoverHeight;
|
||||
const std::vector<CClaimNsupports> claimsNsupports;
|
||||
const std::vector<CSupportValue> unmatchedSupports;
|
||||
};
|
||||
|
||||
typedef CPrefixTrie<std::string, CClaimTrieData> CClaimPrefixTrie;
|
||||
|
||||
class CClaimTrie
|
||||
{
|
||||
public:
|
||||
CClaimTrie() = default;
|
||||
virtual ~CClaimTrie() = default;
|
||||
CClaimTrie(CClaimTrie&&) = delete;
|
||||
CClaimTrie(const CClaimTrie&) = delete;
|
||||
CClaimTrie(bool fMemory, bool fWipe, int proportionalDelayFactor = 32);
|
||||
CClaimTrie(bool fMemory, bool fWipe, int proportionalDelayFactor = 32, std::size_t cacheMB=200);
|
||||
|
||||
CClaimTrie& operator=(CClaimTrie&&) = delete;
|
||||
CClaimTrie& operator=(const CClaimTrie&) = delete;
|
||||
@@ -322,6 +385,29 @@ public:
|
||||
friend struct ClaimTrieChainFixture;
|
||||
friend class CClaimTrieCacheExpirationFork;
|
||||
friend class CClaimTrieCacheNormalizationFork;
|
||||
friend bool getClaimById(const uint160&, std::string&, CClaimValue*);
|
||||
friend bool getClaimById(const std::string&, std::string&, CClaimValue*);
|
||||
|
||||
std::size_t getTotalNamesInTrie() const;
|
||||
std::size_t getTotalClaimsInTrie() const;
|
||||
virtual bool checkConsistency(const uint256& rootHash) const;
|
||||
CAmount getTotalValueOfClaimsInTrie(bool fControllingOnly) const;
|
||||
|
||||
bool contains(const std::string& key) const;
|
||||
bool empty() const;
|
||||
bool find(const std::string& key, CClaimTrieDataNode& node) const;
|
||||
bool find(const std::string& key, CClaimTrieData& claims) const;
|
||||
|
||||
std::vector<std::pair<std::string, CClaimTrieDataNode>> nodes(const std::string& key) const;
|
||||
|
||||
protected:
|
||||
int nNextHeight = 0;
|
||||
int nProportionalDelayFactor = 0;
|
||||
std::unique_ptr<CDBWrapper> db;
|
||||
|
||||
CClaimPrefixTrie cacheNodes;
|
||||
using recurseNodesCB = void(const std::string&, const CClaimTrieData&, const std::vector<std::string>&);
|
||||
void recurseNodes(const std::string& name, const CClaimTrieDataNode& current, std::function<recurseNodesCB> function) const;
|
||||
};
|
||||
|
||||
struct CClaimTrieProofNode
|
||||
@@ -344,21 +430,66 @@ struct CClaimTrieProofNode
|
||||
struct CClaimTrieProof
|
||||
{
|
||||
CClaimTrieProof() = default;
|
||||
|
||||
CClaimTrieProof(std::vector<CClaimTrieProofNode> nodes, bool hasValue, const COutPoint& outPoint, int nHeightOfLastTakeover)
|
||||
: nodes(std::move(nodes)), hasValue(hasValue), outPoint(outPoint), nHeightOfLastTakeover(nHeightOfLastTakeover)
|
||||
{
|
||||
}
|
||||
|
||||
CClaimTrieProof(CClaimTrieProof&&) = default;
|
||||
CClaimTrieProof(const CClaimTrieProof&) = default;
|
||||
CClaimTrieProof& operator=(CClaimTrieProof&&) = default;
|
||||
CClaimTrieProof& operator=(const CClaimTrieProof&) = default;
|
||||
|
||||
std::vector<std::pair<bool, uint256>> pairs;
|
||||
std::vector<CClaimTrieProofNode> nodes;
|
||||
bool hasValue;
|
||||
int nHeightOfLastTakeover = 0;
|
||||
bool hasValue = false;
|
||||
COutPoint outPoint;
|
||||
int nHeightOfLastTakeover;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class COptional
|
||||
{
|
||||
bool own;
|
||||
T* value;
|
||||
public:
|
||||
COptional(T* value = nullptr) : own(false), value(value) {}
|
||||
COptional(COptional&& o)
|
||||
{
|
||||
own = o.own;
|
||||
value = o.value;
|
||||
o.own = false;
|
||||
o.value = nullptr;
|
||||
}
|
||||
COptional(T&& o) : own(true)
|
||||
{
|
||||
value = new T(std::move(o));
|
||||
}
|
||||
~COptional()
|
||||
{
|
||||
if (own)
|
||||
delete value;
|
||||
}
|
||||
COptional& operator=(COptional&&) = delete;
|
||||
bool unique() const
|
||||
{
|
||||
return own;
|
||||
}
|
||||
operator bool() const
|
||||
{
|
||||
return value;
|
||||
}
|
||||
operator T*() const
|
||||
{
|
||||
return value;
|
||||
}
|
||||
T* operator->() const
|
||||
{
|
||||
return value;
|
||||
}
|
||||
operator T&() const
|
||||
{
|
||||
return *value;
|
||||
}
|
||||
T& operator*() const
|
||||
{
|
||||
return *value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
@@ -388,23 +519,16 @@ public:
|
||||
virtual ~CClaimTrieCacheBase() = default;
|
||||
|
||||
uint256 getMerkleHash();
|
||||
bool checkConsistency() const;
|
||||
|
||||
bool getClaimById(const uint160& claimId, std::string& name, CClaimValue& claim) const;
|
||||
|
||||
bool flush();
|
||||
bool empty() const;
|
||||
bool ReadFromDisk(const CBlockIndex* tip);
|
||||
|
||||
bool haveClaim(const std::string& name, const COutPoint& outPoint) const;
|
||||
bool haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight);
|
||||
bool haveClaimInQueue(const std::string& name, const COutPoint& 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);
|
||||
|
||||
std::size_t getTotalNamesInTrie() const;
|
||||
std::size_t getTotalClaimsInTrie() const;
|
||||
CAmount getTotalValueOfClaimsInTrie(bool fControllingOnly) const;
|
||||
bool haveSupportInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const;
|
||||
|
||||
bool addClaim(const std::string& name, const COutPoint& outPoint, const uint160& claimId, CAmount nAmount, int nHeight);
|
||||
bool undoAddClaim(const std::string& name, const COutPoint& outPoint, int nHeight);
|
||||
@@ -434,25 +558,25 @@ public:
|
||||
|
||||
virtual int expirationTime() const;
|
||||
|
||||
bool finalizeDecrement(std::vector<std::pair<std::string, int>>& takeoverHeightUndo);
|
||||
virtual bool finalizeDecrement(std::vector<std::pair<std::string, int>>& takeoverHeightUndo);
|
||||
|
||||
virtual CClaimsForNameType getClaimsForName(const std::string& name) const;
|
||||
virtual CClaimSupportToName getClaimsForName(const std::string& name) const;
|
||||
|
||||
CAmount getEffectiveAmountForClaim(const std::string& name, const uint160& claimId, std::vector<CSupportValue>* supports = nullptr) const;
|
||||
CAmount getEffectiveAmountForClaim(const CClaimsForNameType& claims, const uint160& claimId, std::vector<CSupportValue>* supports = nullptr) const;
|
||||
CClaimPrefixTrie::const_iterator begin() const;
|
||||
CClaimPrefixTrie::const_iterator end() const;
|
||||
|
||||
CClaimTrie::const_iterator begin() const;
|
||||
CClaimTrie::const_iterator end() const;
|
||||
CClaimTrie::const_iterator find(const std::string& name) const;
|
||||
void dumpToLog(CClaimPrefixTrie::const_iterator it, bool diffFromBase = true) const;
|
||||
virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const;
|
||||
|
||||
void dumpToLog(CClaimTrie::const_iterator it, bool diffFromBase = true) const;
|
||||
void recurseNodes(const std::string& name, std::function<void(const std::string&, const CClaimTrieData&)> function) const;
|
||||
|
||||
protected:
|
||||
protected:
|
||||
CClaimTrie* base;
|
||||
CClaimTrie nodesToAddOrUpdate; // nodes pulled in from base (and possibly modified thereafter), written to base on flush
|
||||
CClaimPrefixTrie nodesToAddOrUpdate; // nodes pulled in from base (and possibly modified thereafter), written to base on flush
|
||||
std::unordered_set<std::string> nodesAlreadyCached; // set of nodes already pulled into cache from base
|
||||
std::unordered_set<std::string> namesToCheckForTakeover; // takeover numbers are updated on increment
|
||||
|
||||
uint256 recursiveComputeMerkleHash(CClaimTrie::iterator& it);
|
||||
virtual uint256 recursiveComputeMerkleHash(CClaimPrefixTrie::iterator& it);
|
||||
|
||||
virtual bool insertClaimIntoTrie(const std::string& name, const CClaimValue& claim, bool fCheckTakeover);
|
||||
virtual bool removeClaimFromTrie(const std::string& name, const COutPoint& outPoint, CClaimValue& claim, bool fCheckTakeover);
|
||||
@@ -460,14 +584,12 @@ protected:
|
||||
virtual bool insertSupportIntoMap(const std::string& name, const CSupportValue& support, bool fCheckTakeover);
|
||||
virtual bool removeSupportFromMap(const std::string& name, const COutPoint& outPoint, CSupportValue& support, bool fCheckTakeover);
|
||||
|
||||
virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const;
|
||||
|
||||
supportEntryType getSupportsForName(const std::string& name) const;
|
||||
|
||||
int getDelayForName(const std::string& name) const;
|
||||
virtual int getDelayForName(const std::string& name, const uint160& claimId) const;
|
||||
|
||||
CClaimTrie::iterator cacheData(const std::string& name, bool create = true);
|
||||
CClaimPrefixTrie::iterator cacheData(const std::string& name, bool create = true);
|
||||
|
||||
bool getLastTakeoverForName(const std::string& name, uint160& claimId, int& takeoverHeight) const;
|
||||
|
||||
@@ -496,9 +618,9 @@ private:
|
||||
|
||||
std::unordered_map<std::string, supportEntryType> supportCache; // to be added/updated to base (and disk) on flush
|
||||
std::unordered_set<std::string> nodesToDelete; // to be removed from base (and disk) on flush
|
||||
std::unordered_set<std::string> nodesAlreadyCached; // set of nodes already pulled into cache from base
|
||||
std::unordered_map<std::string, bool> takeoverWorkaround;
|
||||
std::unordered_set<std::string> removalWorkaround;
|
||||
std::unordered_set<std::string> forDeleteFromBase;
|
||||
|
||||
bool shouldUseTakeoverWorkaround(const std::string& key) const;
|
||||
void addTakeoverWorkaroundPotential(const std::string& key);
|
||||
@@ -510,17 +632,28 @@ private:
|
||||
bool removeSupport(const std::string& name, const COutPoint& outPoint, int nHeight, int& nValidAtHeight, bool fCheckTakeover);
|
||||
bool removeClaim(const std::string& name, const COutPoint& outPoint, int nHeight, int& nValidAtHeight, bool fCheckTakeover);
|
||||
|
||||
template <typename T>
|
||||
std::pair<const int, std::vector<queueEntryType<T>>>* getQueueCacheRow(int nHeight, bool createIfNotExists = false);
|
||||
bool validateTrieConsistency(const CBlockIndex* tip);
|
||||
|
||||
template <typename T>
|
||||
typename queueNameType::value_type* getQueueCacheNameRow(const std::string& name, bool createIfNotExists = false);
|
||||
void insertRowsFromQueue(std::vector<T>& result, const std::string& name) const;
|
||||
|
||||
template <typename T>
|
||||
typename expirationQueueType::value_type* getExpirationQueueCacheRow(int nHeight, bool createIfNotExists = false);
|
||||
std::vector<queueEntryType<T>>* getQueueCacheRow(int nHeight, bool createIfNotExists);
|
||||
|
||||
template <typename T>
|
||||
bool haveInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight);
|
||||
COptional<const std::vector<queueEntryType<T>>> getQueueCacheRow(int nHeight) const;
|
||||
|
||||
template <typename T>
|
||||
queueNameRowType* getQueueCacheNameRow(const std::string& name, bool createIfNotExists);
|
||||
|
||||
template <typename T>
|
||||
COptional<const queueNameRowType> getQueueCacheNameRow(const std::string& name) const;
|
||||
|
||||
template <typename T>
|
||||
expirationQueueRowType* getExpirationQueueCacheRow(int nHeight, bool createIfNotExists);
|
||||
|
||||
template <typename T>
|
||||
bool haveInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const;
|
||||
|
||||
template <typename T>
|
||||
T add(const std::string& name, const COutPoint& outPoint, const uint160& claimId, CAmount nAmount, int nHeight);
|
||||
@@ -568,7 +701,8 @@ public:
|
||||
void setExpirationTime(int time);
|
||||
int expirationTime() const override;
|
||||
|
||||
void expirationForkActive(int height, bool increment);
|
||||
virtual void initializeIncrement();
|
||||
bool finalizeDecrement(std::vector<std::pair<std::string, int>>& takeoverHeightUndo) override;
|
||||
|
||||
bool incrementBlock(insertUndoType& insertUndo,
|
||||
claimQueueRowType& expireUndo,
|
||||
@@ -613,7 +747,8 @@ public:
|
||||
|
||||
bool getProofForName(const std::string& name, CClaimTrieProof& proof) override;
|
||||
bool getInfoForName(const std::string& name, CClaimValue& claim) const override;
|
||||
CClaimsForNameType 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;
|
||||
|
||||
protected:
|
||||
bool insertClaimIntoTrie(const std::string& name, const CClaimValue& claim, bool fCheckTakeover) override;
|
||||
@@ -624,8 +759,6 @@ protected:
|
||||
|
||||
int getDelayForName(const std::string& name, const uint160& claimId) const override;
|
||||
|
||||
std::string adjustNameForValidHeight(const std::string& name, int validHeight) const override;
|
||||
|
||||
private:
|
||||
bool overrideInsertNormalization;
|
||||
bool overrideRemoveNormalization;
|
||||
@@ -637,6 +770,31 @@ private:
|
||||
std::vector<std::pair<std::string, int>>& takeoverHeightUndo);
|
||||
};
|
||||
|
||||
typedef CClaimTrieCacheNormalizationFork CClaimTrieCache;
|
||||
class CClaimTrieCacheHashFork : public CClaimTrieCacheNormalizationFork
|
||||
{
|
||||
public:
|
||||
explicit CClaimTrieCacheHashFork(CClaimTrie* base);
|
||||
|
||||
bool getProofForName(const std::string& name, CClaimTrieProof& proof) override;
|
||||
bool getProofForName(const std::string& name, CClaimTrieProof& proof, const std::function<bool(const CClaimValue&)>& comp);
|
||||
void initializeIncrement() override;
|
||||
bool finalizeDecrement(std::vector<std::pair<std::string, int>>& takeoverHeightUndo) override;
|
||||
|
||||
protected:
|
||||
uint256 recursiveComputeMerkleHash(CClaimPrefixTrie::iterator& it) override;
|
||||
|
||||
private:
|
||||
void copyAllBaseToCache();
|
||||
};
|
||||
|
||||
class CClaimTrieHashFork : public CClaimTrie
|
||||
{
|
||||
public:
|
||||
using CClaimTrie::CClaimTrie;
|
||||
protected:
|
||||
bool checkConsistency(const uint256& rootHash) const override;
|
||||
};
|
||||
|
||||
typedef CClaimTrieCacheHashFork CClaimTrieCache;
|
||||
|
||||
#endif // BITCOIN_CLAIMTRIE_H
|
||||
+279
-18
@@ -1,6 +1,8 @@
|
||||
|
||||
#include <consensus/merkle.h>
|
||||
#include <chainparams.h>
|
||||
#include <claimtrie.h>
|
||||
#include <hash.h>
|
||||
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <boost/foreach.hpp>
|
||||
@@ -8,6 +10,7 @@
|
||||
#include <boost/locale/conversion.hpp>
|
||||
#include <boost/locale/localization_backend.hpp>
|
||||
#include <boost/scope_exit.hpp>
|
||||
#include <boost/scoped_ptr.hpp>
|
||||
|
||||
CClaimTrieCacheExpirationFork::CClaimTrieCacheExpirationFork(CClaimTrie* base)
|
||||
: CClaimTrieCacheBase(base)
|
||||
@@ -43,10 +46,21 @@ bool CClaimTrieCacheExpirationFork::decrementBlock(insertUndoType& insertUndo, c
|
||||
return false;
|
||||
}
|
||||
|
||||
void CClaimTrieCacheExpirationFork::expirationForkActive(int nHeight, bool increment)
|
||||
void CClaimTrieCacheExpirationFork::initializeIncrement()
|
||||
{
|
||||
if (nHeight == Params().GetConsensus().nExtendedClaimExpirationForkHeight)
|
||||
forkForExpirationChange(increment);
|
||||
// we could do this in the constructor, but that would not allow for multiple increments in a row (as done in unit tests)
|
||||
if (nNextHeight != Params().GetConsensus().nExtendedClaimExpirationForkHeight)
|
||||
return;
|
||||
|
||||
forkForExpirationChange(true);
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheExpirationFork::finalizeDecrement(std::vector<std::pair<std::string, int>>& takeoverHeightUndo)
|
||||
{
|
||||
auto ret = CClaimTrieCacheBase::finalizeDecrement(takeoverHeightUndo);
|
||||
if (ret && nNextHeight == Params().GetConsensus().nExtendedClaimExpirationForkHeight)
|
||||
forkForExpirationChange(false);
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheExpirationFork::forkForExpirationChange(bool increment)
|
||||
@@ -66,7 +80,7 @@ bool CClaimTrieCacheExpirationFork::forkForExpirationChange(bool increment)
|
||||
if (!pcursor->GetKey(key))
|
||||
continue;
|
||||
int height = key.second;
|
||||
if (key.first == EXP_QUEUE_ROW) {
|
||||
if (key.first == CLAIM_EXP_QUEUE_ROW) {
|
||||
expirationQueueRowType row;
|
||||
if (pcursor->GetValue(row)) {
|
||||
reactivateClaim(row, height, increment);
|
||||
@@ -160,40 +174,48 @@ bool CClaimTrieCacheNormalizationFork::normalizeAllNamesInTrieIfNecessary(insert
|
||||
// run the one-time upgrade of all names that need to change
|
||||
// it modifies the (cache) trie as it goes, so we need to grab everything to be modified first
|
||||
|
||||
for (auto it = base->begin(); it != base->end(); ++it) {
|
||||
const std::string normalized = normalizeClaimName(it.key(), true);
|
||||
if (normalized == it.key())
|
||||
boost::scoped_ptr<CDBIterator> pcursor(base->db->NewIterator());
|
||||
for (pcursor->SeekToFirst(); pcursor->Valid(); pcursor->Next()) {
|
||||
std::pair<uint8_t, std::string> key;
|
||||
if (!pcursor->GetKey(key) || key.first != TRIE_NODE_CHILDREN)
|
||||
continue;
|
||||
|
||||
auto supports = getSupportsForName(it.key());
|
||||
const auto& name = key.second;
|
||||
const std::string normalized = normalizeClaimName(name, true);
|
||||
if (normalized == key.second)
|
||||
continue;
|
||||
|
||||
auto supports = getSupportsForName(name);
|
||||
for (auto support : supports) {
|
||||
// if it's already going to expire just skip it
|
||||
if (support.nHeight + expirationTime() <= nNextHeight)
|
||||
continue;
|
||||
|
||||
assert(removeSupportFromMap(it.key(), support.outPoint, support, false));
|
||||
expireSupportUndo.emplace_back(it.key(), support);
|
||||
assert(removeSupportFromMap(name, support.outPoint, support, false));
|
||||
expireSupportUndo.emplace_back(name, support);
|
||||
assert(insertSupportIntoMap(normalized, support, false));
|
||||
insertSupportUndo.emplace_back(it.key(), support.outPoint, -1);
|
||||
insertSupportUndo.emplace_back(name, support.outPoint, -1);
|
||||
}
|
||||
|
||||
namesToCheckForTakeover.insert(normalized);
|
||||
|
||||
auto cached = cacheData(it.key(), false);
|
||||
auto cached = cacheData(name, false);
|
||||
if (!cached || cached->empty())
|
||||
continue;
|
||||
|
||||
for (auto claim : it->claims) {
|
||||
auto claimsCopy = cached->claims;
|
||||
auto takeoverHeightCopy = cached->nHeightOfLastTakeover;
|
||||
for (auto claim : claimsCopy) {
|
||||
if (claim.nHeight + expirationTime() <= nNextHeight)
|
||||
continue;
|
||||
|
||||
assert(removeClaimFromTrie(it.key(), claim.outPoint, claim, false));
|
||||
removeUndo.emplace_back(it.key(), claim);
|
||||
assert(removeClaimFromTrie(name, claim.outPoint, claim, false));
|
||||
removeUndo.emplace_back(name, claim);
|
||||
assert(insertClaimIntoTrie(normalized, claim, true));
|
||||
insertUndo.emplace_back(it.key(), claim.outPoint, -1);
|
||||
insertUndo.emplace_back(name, claim.outPoint, -1);
|
||||
}
|
||||
|
||||
takeoverHeightUndo.emplace_back(it.key(), it->nHeightOfLastTakeover);
|
||||
takeoverHeightUndo.emplace_back(name, takeoverHeightCopy);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -224,7 +246,7 @@ bool CClaimTrieCacheNormalizationFork::getInfoForName(const std::string& name, C
|
||||
return CClaimTrieCacheExpirationFork::getInfoForName(normalizeClaimName(name), claim);
|
||||
}
|
||||
|
||||
CClaimsForNameType CClaimTrieCacheNormalizationFork::getClaimsForName(const std::string& name) const
|
||||
CClaimSupportToName CClaimTrieCacheNormalizationFork::getClaimsForName(const std::string& name) const
|
||||
{
|
||||
return CClaimTrieCacheExpirationFork::getClaimsForName(normalizeClaimName(name));
|
||||
}
|
||||
@@ -238,3 +260,242 @@ std::string CClaimTrieCacheNormalizationFork::adjustNameForValidHeight(const std
|
||||
{
|
||||
return normalizeClaimName(name, validHeight > Params().GetConsensus().nNormalizedNameForkHeight);
|
||||
}
|
||||
|
||||
CClaimTrieCacheHashFork::CClaimTrieCacheHashFork(CClaimTrie* base) : CClaimTrieCacheNormalizationFork(base)
|
||||
{
|
||||
}
|
||||
|
||||
static const uint256 leafHash = uint256S("0000000000000000000000000000000000000000000000000000000000000002");
|
||||
static const uint256 emptyHash = uint256S("0000000000000000000000000000000000000000000000000000000000000003");
|
||||
|
||||
std::vector<uint256> getClaimHashes(const CClaimTrieData& data)
|
||||
{
|
||||
std::vector<uint256> hashes;
|
||||
for (auto& claim : data.claims)
|
||||
hashes.push_back(getValueHash(claim.outPoint, data.nHeightOfLastTakeover));
|
||||
return hashes;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
using iCbType = std::function<uint256(T&)>;
|
||||
|
||||
template <typename T>
|
||||
using decay = typename std::decay<T>::type;
|
||||
|
||||
template <typename Vector, typename T>
|
||||
uint256 recursiveMerkleHash(const CClaimTrieData& data, Vector&& children, const iCbType<T>& childHash)
|
||||
{
|
||||
static_assert(std::is_same<decay<Vector>, std::vector<decay<T>>>::value, "Vector should be std vector");
|
||||
static_assert(std::is_same<decltype(children[0]), T&>::value, "Vector element type should match callback type");
|
||||
|
||||
std::vector<uint256> childHashes;
|
||||
for (auto& child : children)
|
||||
childHashes.emplace_back(childHash(child));
|
||||
|
||||
std::vector<uint256> claimHashes;
|
||||
if (!data.empty())
|
||||
claimHashes = getClaimHashes(data);
|
||||
else if (children.empty())
|
||||
return {};
|
||||
|
||||
auto left = childHashes.empty() ? leafHash : ComputeMerkleRoot(childHashes);
|
||||
auto right = claimHashes.empty() ? emptyHash : ComputeMerkleRoot(claimHashes);
|
||||
|
||||
return Hash(left.begin(), left.end(), right.begin(), right.end());
|
||||
}
|
||||
|
||||
extern const uint256 one;
|
||||
|
||||
bool CClaimTrieHashFork::checkConsistency(const uint256& rootHash) const
|
||||
{
|
||||
if (nNextHeight < Params().GetConsensus().nAllClaimsInMerkleForkHeight)
|
||||
return CClaimTrie::checkConsistency(rootHash);
|
||||
|
||||
CClaimTrieDataNode node;
|
||||
if (!find({}, node) || node.hash != rootHash) {
|
||||
if (rootHash == one)
|
||||
return true;
|
||||
|
||||
return error("Mismatched root claim trie hashes. This may happen when there is not a clean process shutdown. Please run with -reindex.");
|
||||
}
|
||||
|
||||
bool success = true;
|
||||
recurseNodes({}, node, [&success, this](const std::string& name, const CClaimTrieData& data, const std::vector<std::string>& children) {
|
||||
if (!success) return;
|
||||
|
||||
iCbType<const std::string> callback = [&success, &name, this](const std::string& child) -> uint256 {
|
||||
auto key = name + child;
|
||||
CClaimTrieDataNode node;
|
||||
success &= find(key, node);
|
||||
return node.hash;
|
||||
};
|
||||
|
||||
success &= !data.hash.IsNull();
|
||||
success &= data.hash == recursiveMerkleHash(data, children, callback);
|
||||
});
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
uint256 CClaimTrieCacheHashFork::recursiveComputeMerkleHash(CClaimPrefixTrie::iterator& it)
|
||||
{
|
||||
if (nNextHeight < Params().GetConsensus().nAllClaimsInMerkleForkHeight)
|
||||
return CClaimTrieCacheNormalizationFork::recursiveComputeMerkleHash(it);
|
||||
|
||||
using iterator = CClaimPrefixTrie::iterator;
|
||||
iCbType<iterator> process = [&process](iterator& it) -> uint256 {
|
||||
if (it->hash.IsNull())
|
||||
it->hash = recursiveMerkleHash(it.data(), it.children(), process);
|
||||
return it->hash;
|
||||
};
|
||||
return process(it);
|
||||
}
|
||||
|
||||
std::vector<uint256> ComputeMerklePath(const std::vector<uint256>& hashes, uint32_t idx)
|
||||
{
|
||||
uint32_t count = 0;
|
||||
int matchlevel = -1;
|
||||
bool matchh = false;
|
||||
uint256 inner[32], h;
|
||||
const uint32_t one = 1;
|
||||
std::vector<uint256> res;
|
||||
|
||||
const auto iterateInner = [&](int& level) {
|
||||
for (; !(count & (one << level)); level++) {
|
||||
const auto& ihash = inner[level];
|
||||
if (matchh) {
|
||||
res.push_back(ihash);
|
||||
} else if (matchlevel == level) {
|
||||
res.push_back(h);
|
||||
matchh = true;
|
||||
}
|
||||
h = Hash(ihash.begin(), ihash.end(), h.begin(), h.end());
|
||||
}
|
||||
};
|
||||
|
||||
while (count < hashes.size()) {
|
||||
h = hashes[count];
|
||||
matchh = count == idx;
|
||||
count++;
|
||||
int level = 0;
|
||||
iterateInner(level);
|
||||
// Store the resulting hash at inner position level.
|
||||
inner[level] = h;
|
||||
if (matchh)
|
||||
matchlevel = level;
|
||||
}
|
||||
|
||||
int level = 0;
|
||||
while (!(count & (one << level)))
|
||||
level++;
|
||||
|
||||
h = inner[level];
|
||||
matchh = matchlevel == level;
|
||||
|
||||
while (count != (one << level)) {
|
||||
// If we reach this point, h is an inner value that is not the top.
|
||||
if (matchh)
|
||||
res.push_back(h);
|
||||
|
||||
h = Hash(h.begin(), h.end(), h.begin(), h.end());
|
||||
// Increment count to the value it would have if two entries at this
|
||||
count += (one << level);
|
||||
level++;
|
||||
iterateInner(level);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, CClaimTrieProof& proof)
|
||||
{
|
||||
return getProofForName(name, proof, nullptr);
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, CClaimTrieProof& proof, const std::function<bool(const CClaimValue&)>& comp)
|
||||
{
|
||||
if (nNextHeight < Params().GetConsensus().nAllClaimsInMerkleForkHeight)
|
||||
return CClaimTrieCacheNormalizationFork::getProofForName(name, proof);
|
||||
|
||||
auto fillPairs = [&proof](const std::vector<uint256>& 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]);
|
||||
};
|
||||
|
||||
// cache the parent nodes
|
||||
cacheData(name, false);
|
||||
getMerkleHash();
|
||||
proof = CClaimTrieProof();
|
||||
for (auto& it : static_cast<const CClaimPrefixTrie&>(nodesToAddOrUpdate).nodes(name)) {
|
||||
std::vector<uint256> childHashes;
|
||||
uint32_t nextCurrentIdx = 0;
|
||||
for (auto& child : it.children()) {
|
||||
if (name.find(child.key()) == 0)
|
||||
nextCurrentIdx = uint32_t(childHashes.size());
|
||||
childHashes.push_back(child->hash);
|
||||
}
|
||||
|
||||
std::vector<uint256> claimHashes;
|
||||
if (!it->empty())
|
||||
claimHashes = getClaimHashes(it.data());
|
||||
|
||||
// I am on a node; I need a hash(children, claims)
|
||||
// if I am the last node on the list, it will be hash(children, x)
|
||||
// else it will be hash(x, claims)
|
||||
if (it.key() == name) {
|
||||
uint32_t nClaimIndex = 0;
|
||||
auto& claims = it->claims;
|
||||
auto itClaim = !comp ? claims.begin() : std::find_if(claims.begin(), claims.end(), comp);
|
||||
if (itClaim != claims.end()) {
|
||||
proof.hasValue = true;
|
||||
proof.outPoint = itClaim->outPoint;
|
||||
proof.nHeightOfLastTakeover = it->nHeightOfLastTakeover;
|
||||
nClaimIndex = std::distance(claims.begin(), itClaim);
|
||||
}
|
||||
auto hash = childHashes.empty() ? leafHash : ComputeMerkleRoot(childHashes);
|
||||
proof.pairs.emplace_back(true, hash);
|
||||
if (!claimHashes.empty())
|
||||
fillPairs(claimHashes, nClaimIndex);
|
||||
} else {
|
||||
auto hash = claimHashes.empty() ? emptyHash : ComputeMerkleRoot(claimHashes);
|
||||
proof.pairs.emplace_back(false, hash);
|
||||
if (!childHashes.empty())
|
||||
fillPairs(childHashes, nextCurrentIdx);
|
||||
}
|
||||
}
|
||||
std::reverse(proof.pairs.begin(), proof.pairs.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
void CClaimTrieCacheHashFork::copyAllBaseToCache()
|
||||
{
|
||||
recurseNodes({}, [this](const std::string& name, const CClaimTrieData& data) {
|
||||
if (nodesAlreadyCached.insert(name).second)
|
||||
nodesToAddOrUpdate.insert(name, data);
|
||||
});
|
||||
|
||||
for (auto it = nodesToAddOrUpdate.begin(); it != nodesToAddOrUpdate.end(); ++it) {
|
||||
it->hash.SetNull();
|
||||
it->flags |= CClaimTrieDataFlags::HASH_DIRTY;
|
||||
}
|
||||
}
|
||||
|
||||
void CClaimTrieCacheHashFork::initializeIncrement()
|
||||
{
|
||||
CClaimTrieCacheNormalizationFork::initializeIncrement();
|
||||
// we could do this in the constructor, but that would not allow for multiple increments in a row (as done in unit tests)
|
||||
if (nNextHeight != Params().GetConsensus().nAllClaimsInMerkleForkHeight - 1)
|
||||
return;
|
||||
|
||||
// if we are forking, we load the entire base trie into the cache trie
|
||||
// we reset its hash computation so it can be recomputed completely
|
||||
copyAllBaseToCache();
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheHashFork::finalizeDecrement(std::vector<std::pair<std::string, int>>& takeoverHeightUndo)
|
||||
{
|
||||
auto ret = CClaimTrieCacheNormalizationFork::finalizeDecrement(takeoverHeightUndo);
|
||||
if (ret && nNextHeight == Params().GetConsensus().nAllClaimsInMerkleForkHeight - 1)
|
||||
copyAllBaseToCache();
|
||||
return ret;
|
||||
}
|
||||
@@ -81,6 +81,8 @@ struct Params {
|
||||
int nMinTakeoverWorkaroundHeight;
|
||||
int nMaxTakeoverWorkaroundHeight;
|
||||
|
||||
int nWitnessForkHeight;
|
||||
|
||||
int64_t nPowTargetSpacing;
|
||||
int64_t nPowTargetTimespan;
|
||||
/** how long it took claims to expire before the hard fork */
|
||||
@@ -94,6 +96,8 @@ struct Params {
|
||||
nOriginalClaimExpirationTime :
|
||||
nExtendedClaimExpirationTime;
|
||||
}
|
||||
/** blocks before the hard fork that adds all claims into the merkle hash */
|
||||
int64_t nAllClaimsInMerkleForkHeight;
|
||||
int64_t DifficultyAdjustmentInterval() const { return nPowTargetTimespan / nPowTargetSpacing; }
|
||||
uint256 nMinimumChainWork;
|
||||
uint256 defaultAssumeValid;
|
||||
|
||||
@@ -154,7 +154,8 @@ int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& i
|
||||
const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
|
||||
assert(!coin.IsSpent());
|
||||
const CTxOut &prevout = coin.out;
|
||||
nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
|
||||
const CScript& scriptPubKey = StripClaimScriptPrefix(prevout.scriptPubKey);
|
||||
nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, scriptPubKey, &tx.vin[i].scriptWitness, flags);
|
||||
}
|
||||
return nSigOps;
|
||||
}
|
||||
|
||||
+11
-6
@@ -80,14 +80,14 @@ static void SetMaxOpenFiles(leveldb::Options *options) {
|
||||
// implementation that does not use extra file descriptors (the fds are
|
||||
// closed after being mmaped).
|
||||
//
|
||||
// Increasing the value beyond the default is dangerous because LevelDB will
|
||||
// fall back to a non-mmap implementation when the file count is too large.
|
||||
// Increasing the value beyond the nmap count is dangerous because LevelDB will
|
||||
// fall back to a non-mmap implementation when the file count is too large (thus contending select()).
|
||||
// On 32-bit Unix host we should decrease the value because the handles use
|
||||
// up real fds, and we want to avoid fd exhaustion issues.
|
||||
//
|
||||
// See PR #12495 for further discussion.
|
||||
|
||||
int default_open_files = options->max_open_files;
|
||||
int default_open_files = 400;
|
||||
#ifndef WIN32
|
||||
if (sizeof(void*) < 8) {
|
||||
options->max_open_files = 64;
|
||||
@@ -100,10 +100,10 @@ static void SetMaxOpenFiles(leveldb::Options *options) {
|
||||
static leveldb::Options GetOptions(size_t nCacheSize)
|
||||
{
|
||||
leveldb::Options options;
|
||||
auto write_cache = std::min(nCacheSize / 4, size_t(16) << 20U); // cap write_cache at 16MB (4x default)
|
||||
auto write_cache = std::min(nCacheSize / 4, size_t(32 * 1024 * 1024)); // cap write_cache
|
||||
options.block_cache = leveldb::NewLRUCache(nCacheSize - write_cache * 2);
|
||||
options.write_buffer_size = write_cache; // up to two write buffers may be held in memory simultaneously
|
||||
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
|
||||
options.filter_policy = leveldb::NewBloomFilterPolicy(12);
|
||||
options.compression = leveldb::kNoCompression;
|
||||
options.info_log = new CBitcoinLevelDBLogger();
|
||||
if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
|
||||
@@ -116,7 +116,7 @@ static leveldb::Options GetOptions(size_t nCacheSize)
|
||||
}
|
||||
|
||||
CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate)
|
||||
: m_name(fs::basename(path))
|
||||
: m_name(fs::basename(path)), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION)
|
||||
{
|
||||
penv = nullptr;
|
||||
readoptions.verify_checksums = true;
|
||||
@@ -181,6 +181,11 @@ CDBWrapper::~CDBWrapper()
|
||||
options.env = nullptr;
|
||||
}
|
||||
|
||||
bool CDBWrapper::Sync() {
|
||||
CDBBatch batch(*this);
|
||||
return WriteBatch(batch, true);
|
||||
}
|
||||
|
||||
bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
|
||||
{
|
||||
const bool log_memory = LogAcceptCategory(BCLog::LEVELDB);
|
||||
|
||||
+100
-103
@@ -16,9 +16,6 @@
|
||||
#include <leveldb/db.h>
|
||||
#include <leveldb/write_batch.h>
|
||||
|
||||
static const size_t DBWRAPPER_PREALLOC_KEY_SIZE = 64;
|
||||
static const size_t DBWRAPPER_PREALLOC_VALUE_SIZE = 1024;
|
||||
|
||||
class dbwrapper_error : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
@@ -33,87 +30,16 @@ namespace dbwrapper_private {
|
||||
|
||||
/** Handle database error by throwing dbwrapper_error exception.
|
||||
*/
|
||||
void HandleError(const leveldb::Status& status);
|
||||
void HandleError(const leveldb::Status& status);
|
||||
|
||||
/** Work around circular dependency, as well as for testing in dbwrapper_tests.
|
||||
* Database obfuscation should be considered an implementation detail of the
|
||||
* specific database.
|
||||
*/
|
||||
const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w);
|
||||
const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w);
|
||||
|
||||
};
|
||||
|
||||
/** Batch of changes queued to be written to a CDBWrapper */
|
||||
class CDBBatch
|
||||
{
|
||||
friend class CDBWrapper;
|
||||
|
||||
private:
|
||||
const CDBWrapper &parent;
|
||||
leveldb::WriteBatch batch;
|
||||
|
||||
CDataStream ssKey;
|
||||
CDataStream ssValue;
|
||||
|
||||
size_t size_estimate;
|
||||
|
||||
public:
|
||||
/**
|
||||
* @param[in] _parent CDBWrapper that this batch is to be submitted to
|
||||
*/
|
||||
explicit CDBBatch(const CDBWrapper &_parent) : parent(_parent), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION), size_estimate(0) { };
|
||||
|
||||
void Clear()
|
||||
{
|
||||
batch.Clear();
|
||||
size_estimate = 0;
|
||||
}
|
||||
|
||||
template <typename K, typename V>
|
||||
void Write(const K& key, const V& value)
|
||||
{
|
||||
ssKey.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(ssKey.data(), ssKey.size());
|
||||
|
||||
ssValue.reserve(DBWRAPPER_PREALLOC_VALUE_SIZE);
|
||||
ssValue << value;
|
||||
ssValue.Xor(dbwrapper_private::GetObfuscateKey(parent));
|
||||
leveldb::Slice slValue(ssValue.data(), ssValue.size());
|
||||
|
||||
batch.Put(slKey, slValue);
|
||||
// LevelDB serializes writes as:
|
||||
// - byte: header
|
||||
// - varint: key length (1 byte up to 127B, 2 bytes up to 16383B, ...)
|
||||
// - byte[]: key
|
||||
// - varint: value length
|
||||
// - byte[]: value
|
||||
// The formula below assumes the key and value are both less than 16k.
|
||||
size_estimate += 3 + (slKey.size() > 127) + slKey.size() + (slValue.size() > 127) + slValue.size();
|
||||
ssKey.clear();
|
||||
ssValue.clear();
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
void Erase(const K& key)
|
||||
{
|
||||
ssKey.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(ssKey.data(), ssKey.size());
|
||||
|
||||
batch.Delete(slKey);
|
||||
// LevelDB serializes erases as:
|
||||
// - byte: header
|
||||
// - varint: key length
|
||||
// - byte[]: key
|
||||
// The formula below assumes the key is less than 16kB.
|
||||
size_estimate += 2 + (slKey.size() > 127) + slKey.size();
|
||||
ssKey.clear();
|
||||
}
|
||||
|
||||
size_t SizeEstimate() const { return size_estimate; }
|
||||
};
|
||||
|
||||
class CDBIterator
|
||||
{
|
||||
private:
|
||||
@@ -127,7 +53,7 @@ public:
|
||||
* @param[in] _piter The original leveldb iterator.
|
||||
*/
|
||||
CDBIterator(const CDBWrapper &_parent, leveldb::Iterator *_piter) :
|
||||
parent(_parent), piter(_piter) { };
|
||||
parent(_parent), piter(_piter) { };
|
||||
~CDBIterator();
|
||||
|
||||
bool Valid() const;
|
||||
@@ -136,7 +62,6 @@ public:
|
||||
|
||||
template<typename K> void Seek(const K& key) {
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(ssKey.data(), ssKey.size());
|
||||
piter->Seek(slKey);
|
||||
@@ -173,6 +98,8 @@ public:
|
||||
|
||||
};
|
||||
|
||||
class CDBBatch;
|
||||
|
||||
class CDBWrapper
|
||||
{
|
||||
friend const std::vector<unsigned char>& dbwrapper_private::GetObfuscateKey(const CDBWrapper &w);
|
||||
@@ -213,6 +140,8 @@ private:
|
||||
std::vector<unsigned char> CreateObfuscateKey() const;
|
||||
|
||||
public:
|
||||
mutable CDataStream ssKey, ssValue;
|
||||
|
||||
/**
|
||||
* @param[in] path Location in the filesystem where leveldb data will be stored.
|
||||
* @param[in] nCacheSize Configures various leveldb cache settings.
|
||||
@@ -230,13 +159,12 @@ public:
|
||||
template <typename K, typename V>
|
||||
bool Read(const K& key, V& value) const
|
||||
{
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(ssKey.data(), ssKey.size());
|
||||
|
||||
std::string strValue;
|
||||
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
|
||||
ssKey.clear();
|
||||
if (!status.ok()) {
|
||||
if (status.IsNotFound())
|
||||
return false;
|
||||
@@ -254,23 +182,17 @@ public:
|
||||
}
|
||||
|
||||
template <typename K, typename V>
|
||||
bool Write(const K& key, const V& value, bool fSync = false)
|
||||
{
|
||||
CDBBatch batch(*this);
|
||||
batch.Write(key, value);
|
||||
return WriteBatch(batch, fSync);
|
||||
}
|
||||
bool Write(const K& key, const V& value, bool fSync = false);
|
||||
|
||||
template <typename K>
|
||||
bool Exists(const K& key) const
|
||||
{
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(ssKey.data(), ssKey.size());
|
||||
|
||||
std::string strValue;
|
||||
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
|
||||
ssKey.clear();
|
||||
if (!status.ok()) {
|
||||
if (status.IsNotFound())
|
||||
return false;
|
||||
@@ -281,12 +203,7 @@ public:
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
bool Erase(const K& key, bool fSync = false)
|
||||
{
|
||||
CDBBatch batch(*this);
|
||||
batch.Erase(key);
|
||||
return WriteBatch(batch, fSync);
|
||||
}
|
||||
bool Erase(const K& key, bool fSync = false);
|
||||
|
||||
bool WriteBatch(CDBBatch& batch, bool fSync = false);
|
||||
|
||||
@@ -299,11 +216,7 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Sync()
|
||||
{
|
||||
CDBBatch batch(*this);
|
||||
return WriteBatch(batch, true);
|
||||
}
|
||||
bool Sync();
|
||||
|
||||
CDBIterator *NewIterator()
|
||||
{
|
||||
@@ -319,8 +232,8 @@ public:
|
||||
size_t EstimateSize(const K& key_begin, const K& key_end) const
|
||||
{
|
||||
CDataStream ssKey1(SER_DISK, CLIENT_VERSION), ssKey2(SER_DISK, CLIENT_VERSION);
|
||||
ssKey1.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey2.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey1.reserve(ssKey.capacity());
|
||||
ssKey2.reserve(ssKey.capacity());
|
||||
ssKey1 << key_begin;
|
||||
ssKey2 << key_end;
|
||||
leveldb::Slice slKey1(ssKey1.data(), ssKey1.size());
|
||||
@@ -338,8 +251,8 @@ public:
|
||||
void CompactRange(const K& key_begin, const K& key_end) const
|
||||
{
|
||||
CDataStream ssKey1(SER_DISK, CLIENT_VERSION), ssKey2(SER_DISK, CLIENT_VERSION);
|
||||
ssKey1.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey2.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
|
||||
ssKey1.reserve(ssKey.capacity());
|
||||
ssKey2.reserve(ssKey.capacity());
|
||||
ssKey1 << key_begin;
|
||||
ssKey2 << key_end;
|
||||
leveldb::Slice slKey1(ssKey1.data(), ssKey1.size());
|
||||
@@ -349,4 +262,88 @@ public:
|
||||
|
||||
};
|
||||
|
||||
/** Batch of changes queued to be written to a CDBWrapper */
|
||||
class CDBBatch
|
||||
{
|
||||
friend class CDBWrapper;
|
||||
const CDBWrapper &parent;
|
||||
leveldb::WriteBatch batch;
|
||||
|
||||
size_t size_estimate;
|
||||
CDataStream ssKey, ssValue;
|
||||
|
||||
public:
|
||||
/**
|
||||
* @param[in] _parent CDBWrapper that this batch is to be submitted to
|
||||
*/
|
||||
explicit CDBBatch(const CDBWrapper &_parent) : parent(_parent), size_estimate(0),
|
||||
ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION) {
|
||||
ssKey.reserve(parent.ssKey.capacity());
|
||||
ssValue.reserve(parent.ssValue.capacity());
|
||||
};
|
||||
|
||||
void Clear()
|
||||
{
|
||||
batch.Clear();
|
||||
size_estimate = 0;
|
||||
}
|
||||
|
||||
template <typename K, typename V>
|
||||
void Write(const K& key, const V& value)
|
||||
{
|
||||
assert(ssKey.empty());
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(ssKey.data(), ssKey.size());
|
||||
|
||||
assert(ssValue.empty());
|
||||
ssValue << value;
|
||||
ssValue.Xor(dbwrapper_private::GetObfuscateKey(parent));
|
||||
leveldb::Slice slValue(ssValue.data(), ssValue.size());
|
||||
|
||||
batch.Put(slKey, slValue);
|
||||
// LevelDB serializes writes as:
|
||||
// - byte: header
|
||||
// - varint: key length (1 byte up to 127B, 2 bytes up to 16383B, ...)
|
||||
// - byte[]: key
|
||||
// - varint: value length
|
||||
// - byte[]: value
|
||||
// The formula below assumes the key and value are both less than 16k.
|
||||
size_estimate += 3 + (slKey.size() > 127) + slKey.size() + (slValue.size() > 127) + slValue.size();
|
||||
ssKey.clear();
|
||||
ssValue.clear();
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
void Erase(const K& key)
|
||||
{
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(ssKey.data(), ssKey.size());
|
||||
|
||||
batch.Delete(slKey);
|
||||
// LevelDB serializes erases as:
|
||||
// - byte: header
|
||||
// - varint: key length
|
||||
// - byte[]: key
|
||||
// The formula below assumes the key is less than 16kB.
|
||||
size_estimate += 2 + (slKey.size() > 127) + slKey.size();
|
||||
ssKey.clear();
|
||||
}
|
||||
|
||||
size_t SizeEstimate() const { return size_estimate; }
|
||||
};
|
||||
|
||||
template<typename K>
|
||||
bool CDBWrapper::Erase(const K &key, bool fSync) {
|
||||
CDBBatch batch(*this);
|
||||
batch.Erase(key);
|
||||
return WriteBatch(batch, fSync);
|
||||
}
|
||||
|
||||
template<typename K, typename V>
|
||||
bool CDBWrapper::Write(const K &key, const V &value, bool fSync) {
|
||||
CDBBatch batch(*this);
|
||||
batch.Write(key, value);
|
||||
return WriteBatch(batch, fSync);
|
||||
}
|
||||
|
||||
#endif // BITCOIN_DBWRAPPER_H
|
||||
+5
-1
@@ -370,6 +370,7 @@ void SetupServerArgs()
|
||||
gArgs.AddArg("-datadir=<dir>", "Specify data directory", false, OptionsCategory::OPTIONS);
|
||||
gArgs.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), true, OptionsCategory::OPTIONS);
|
||||
gArgs.AddArg("-dbcache=<n>", strprintf("Set database cache size in megabytes (%d to %d, default: %d)", nMinDbCache, nMaxDbCache, nDefaultDbCache), false, OptionsCategory::OPTIONS);
|
||||
gArgs.AddArg("-claimtriecache=<n>", strprintf("Set claim trie cache size in megabytes (%d to %d, default: %d)", nMinDbCache, nMaxDbCache, nDefaultDbCache), false, OptionsCategory::OPTIONS);
|
||||
gArgs.AddArg("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), false, OptionsCategory::OPTIONS);
|
||||
gArgs.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), true, OptionsCategory::OPTIONS);
|
||||
gArgs.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", false, OptionsCategory::OPTIONS);
|
||||
@@ -1461,7 +1462,10 @@ bool AppInitMain()
|
||||
pblocktree.reset();
|
||||
pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
|
||||
delete pclaimTrie;
|
||||
pclaimTrie = new CClaimTrie(false, fReindex);
|
||||
int64_t trieCacheMB = gArgs.GetArg("-claimtriecache", nDefaultDbCache);
|
||||
trieCacheMB = std::min(trieCacheMB, nMaxDbCache);
|
||||
trieCacheMB = std::max(trieCacheMB, nMinDbCache);
|
||||
pclaimTrie = new CClaimTrieHashFork(false, fReindex || fReindexChainState, 32, trieCacheMB);
|
||||
|
||||
if (fReset) {
|
||||
pblocktree->WriteReindexing(true);
|
||||
|
||||
@@ -221,6 +221,9 @@ class RandomAccessFile {
|
||||
// Get a name for the file, only for error reporting
|
||||
virtual std::string GetName() const = 0;
|
||||
|
||||
virtual char* AllocateScratch(std::size_t size) const { return new char[size]; };
|
||||
virtual void DeallocateScratch(char* pointer) const { delete[] pointer; };
|
||||
|
||||
private:
|
||||
// No copying allowed
|
||||
RandomAccessFile(const RandomAccessFile&);
|
||||
|
||||
@@ -73,15 +73,15 @@ Status ReadBlock(RandomAccessFile* file,
|
||||
// Read the block contents as well as the type/crc footer.
|
||||
// See table_builder.cc for the code that built this structure.
|
||||
size_t n = static_cast<size_t>(handle.size());
|
||||
char* buf = new char[n + kBlockTrailerSize];
|
||||
char* buf = file->AllocateScratch(n + kBlockTrailerSize);
|
||||
Slice contents;
|
||||
Status s = file->Read(handle.offset(), n + kBlockTrailerSize, &contents, buf);
|
||||
if (!s.ok()) {
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
return s;
|
||||
}
|
||||
if (contents.size() != n + kBlockTrailerSize) {
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
return Status::Corruption("truncated block read", file->GetName());
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ Status ReadBlock(RandomAccessFile* file,
|
||||
const uint32_t crc = crc32c::Unmask(DecodeFixed32(data + n + 1));
|
||||
const uint32_t actual = crc32c::Value(data, n + 1);
|
||||
if (actual != crc) {
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
s = Status::Corruption("block checksum mismatch", file->GetName());
|
||||
return s;
|
||||
}
|
||||
@@ -103,7 +103,7 @@ Status ReadBlock(RandomAccessFile* file,
|
||||
// File implementation gave us pointer to some other data.
|
||||
// Use it directly under the assumption that it will be live
|
||||
// while the file is open.
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
result->data = Slice(data, n);
|
||||
result->heap_allocated = false;
|
||||
result->cachable = false; // Do not double-cache
|
||||
@@ -118,23 +118,23 @@ Status ReadBlock(RandomAccessFile* file,
|
||||
case kSnappyCompression: {
|
||||
size_t ulength = 0;
|
||||
if (!port::Snappy_GetUncompressedLength(data, n, &ulength)) {
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
return Status::Corruption("corrupted compressed block contents", file->GetName());
|
||||
}
|
||||
char* ubuf = new char[ulength];
|
||||
if (!port::Snappy_Uncompress(data, n, ubuf)) {
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
delete[] ubuf;
|
||||
return Status::Corruption("corrupted compressed block contents", file->GetName());
|
||||
}
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
result->data = Slice(ubuf, ulength);
|
||||
result->heap_allocated = true;
|
||||
result->cachable = true;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
delete[] buf;
|
||||
file->DeallocateScratch(buf);
|
||||
return Status::Corruption("bad block type", file->GetName());
|
||||
}
|
||||
|
||||
|
||||
@@ -162,6 +162,7 @@ class PosixRandomAccessFile: public RandomAccessFile {
|
||||
}
|
||||
|
||||
Status s;
|
||||
assert(scratch);
|
||||
ssize_t r = pread(fd, scratch, n, static_cast<off_t>(offset));
|
||||
*result = Slice(scratch, (r < 0) ? 0 : r);
|
||||
if (r < 0) {
|
||||
@@ -188,19 +189,19 @@ class PosixMmapReadableFile: public RandomAccessFile {
|
||||
|
||||
public:
|
||||
// base[0,length-1] contains the mmapped contents of the file.
|
||||
PosixMmapReadableFile(const std::string& fname, void* base, size_t length,
|
||||
PosixMmapReadableFile(std::string fname, void* base, size_t length,
|
||||
Limiter* limiter)
|
||||
: filename_(fname), mmapped_region_(base), length_(length),
|
||||
: filename_(std::move(fname)), mmapped_region_(base), length_(length),
|
||||
limiter_(limiter) {
|
||||
}
|
||||
|
||||
virtual ~PosixMmapReadableFile() {
|
||||
~PosixMmapReadableFile() override {
|
||||
munmap(mmapped_region_, length_);
|
||||
limiter_->Release();
|
||||
}
|
||||
|
||||
virtual Status Read(uint64_t offset, size_t n, Slice* result,
|
||||
char* scratch) const {
|
||||
Status Read(uint64_t offset, size_t n, Slice* result,
|
||||
char* scratch) const override {
|
||||
Status s;
|
||||
if (offset + n > length_) {
|
||||
*result = Slice();
|
||||
@@ -211,7 +212,10 @@ class PosixMmapReadableFile: public RandomAccessFile {
|
||||
return s;
|
||||
}
|
||||
|
||||
virtual std::string GetName() const { return filename_; }
|
||||
std::string GetName() const override { return filename_; }
|
||||
|
||||
char* AllocateScratch(std::size_t size) const override { return nullptr; }
|
||||
void DeallocateScratch(char* pointer) const override { assert(pointer == nullptr); }
|
||||
};
|
||||
|
||||
class PosixWritableFile : public WritableFile {
|
||||
@@ -585,8 +589,8 @@ static int MaxMmaps() {
|
||||
if (mmap_limit >= 0) {
|
||||
return mmap_limit;
|
||||
}
|
||||
// Up to 4096 mmaps for 64-bit binaries; none for smaller pointer sizes.
|
||||
mmap_limit = sizeof(void*) >= 8 ? 4096 : 0;
|
||||
// Up to 400 mmaps for 64-bit binaries (800MB); none for smaller pointer sizes.
|
||||
mmap_limit = sizeof(void*) >= 8 ? 400 : 0;
|
||||
return mmap_limit;
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -71,7 +71,7 @@ void blockToCache(const CBlock* pblock, CClaimTrieCache& trieCache, int nHeight)
|
||||
.claimUndoHeights = {}
|
||||
};
|
||||
|
||||
trieCache.expirationForkActive(nHeight, true);
|
||||
trieCache.initializeIncrement();
|
||||
|
||||
CCoinsViewCache view(pcoinsTip.get());
|
||||
|
||||
@@ -207,7 +207,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
|
||||
|
||||
CValidationState state;
|
||||
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
|
||||
if (!trieCache.empty() && trieCache.checkConsistency())
|
||||
if (!trieCache.empty())
|
||||
trieCache.dumpToLog(trieCache.begin());
|
||||
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
|
||||
}
|
||||
|
||||
+8
-4
@@ -28,18 +28,22 @@ uint32_t vch_to_uint32_t(std::vector<unsigned char>& vchN)
|
||||
return n;
|
||||
}
|
||||
|
||||
CScript ClaimNameScript(std::string name, std::string value)
|
||||
CScript ClaimNameScript(std::string name, std::string value, bool fakeSuffix)
|
||||
{
|
||||
std::vector<unsigned char> vchName(name.begin(), name.end());
|
||||
std::vector<unsigned char> vchValue(value.begin(), value.end());
|
||||
return CScript() << OP_CLAIM_NAME << vchName << vchValue << OP_2DROP << OP_DROP << OP_TRUE;
|
||||
auto ret = CScript() << OP_CLAIM_NAME << vchName << vchValue << OP_2DROP << OP_DROP;
|
||||
if (fakeSuffix) ret.push_back(OP_TRUE);
|
||||
return ret;
|
||||
}
|
||||
|
||||
CScript SupportClaimScript(std::string name, uint160 claimId)
|
||||
CScript SupportClaimScript(std::string name, uint160 claimId, bool fakeSuffix)
|
||||
{
|
||||
std::vector<unsigned char> vchName(name.begin(), name.end());
|
||||
std::vector<unsigned char> vchClaimId(claimId.begin(), claimId.end());
|
||||
return CScript() << OP_SUPPORT_CLAIM << vchName << vchClaimId << OP_2DROP << OP_DROP << OP_TRUE;
|
||||
auto ret = CScript() << OP_SUPPORT_CLAIM << vchName << vchClaimId << OP_2DROP << OP_DROP;
|
||||
if (fakeSuffix) ret.push_back(OP_TRUE);
|
||||
return ret;
|
||||
}
|
||||
|
||||
CScript UpdateClaimScript(std::string name, uint160 claimId, std::string value)
|
||||
|
||||
+2
-2
@@ -25,8 +25,8 @@
|
||||
// Scripts exceeding this size are rejected in CheckTransaction in main.cpp
|
||||
#define MAX_CLAIM_NAME_SIZE 255
|
||||
|
||||
CScript ClaimNameScript(std::string name, std::string value);
|
||||
CScript SupportClaimScript(std::string name, uint160 claimId);
|
||||
CScript ClaimNameScript(std::string name, std::string value, bool fakeSuffix=true);
|
||||
CScript SupportClaimScript(std::string name, uint160 claimId, bool fakeSuffix=true);
|
||||
CScript UpdateClaimScript(std::string name, uint160 claimId, std::string value);
|
||||
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams);
|
||||
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams, CScript::const_iterator& pc);
|
||||
|
||||
@@ -10,11 +10,9 @@
|
||||
#include <consensus/validation.h>
|
||||
#include <validation.h>
|
||||
#include <coins.h>
|
||||
#include <tinyformat.h>
|
||||
#include <util.h>
|
||||
#include <utilstrencodings.h>
|
||||
|
||||
#include "nameclaim.h"
|
||||
#include <nameclaim.h>
|
||||
|
||||
|
||||
CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
|
||||
@@ -117,8 +115,7 @@ bool IsStandardTx(const CTransaction& tx, std::string& reason)
|
||||
unsigned int nDataOut = 0;
|
||||
txnouttype whichType;
|
||||
for (const CTxOut& txout : tx.vout) {
|
||||
const CScript& scriptPubKey = StripClaimScriptPrefix(txout.scriptPubKey);
|
||||
if (!::IsStandard(scriptPubKey, whichType)) {
|
||||
if (!::IsStandard(txout.scriptPubKey, whichType)) {
|
||||
reason = "scriptpubkey";
|
||||
return false;
|
||||
}
|
||||
@@ -171,8 +168,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
|
||||
std::vector<std::vector<unsigned char> > vSolutions;
|
||||
txnouttype whichType;
|
||||
// get the scriptPubKey corresponding to this input:
|
||||
const CScript& prevScript = StripClaimScriptPrefix(prev.scriptPubKey);
|
||||
if (!Solver(prevScript, whichType, vSolutions))
|
||||
if (!Solver(prev.scriptPubKey, whichType, vSolutions))
|
||||
return false;
|
||||
|
||||
if (whichType == TX_SCRIPTHASH)
|
||||
@@ -208,7 +204,7 @@ bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
|
||||
const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
|
||||
|
||||
// get the scriptPubKey corresponding to this input:
|
||||
CScript prevScript = prev.scriptPubKey;
|
||||
CScript prevScript = StripClaimScriptPrefix(prev.scriptPubKey);
|
||||
|
||||
if (prevScript.IsPayToScriptHash()) {
|
||||
std::vector <std::vector<unsigned char> > stack;
|
||||
|
||||
+54
-50
@@ -108,16 +108,18 @@ template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::reference CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator*() const
|
||||
{
|
||||
assert(!node.expired());
|
||||
return TPair(name, *(node.lock()->data));
|
||||
auto shared = node.lock();
|
||||
assert(shared);
|
||||
return TPair(name, *(shared->data));
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::pointer CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator->() const
|
||||
{
|
||||
assert(!node.expired());
|
||||
return node.lock()->data.get();
|
||||
auto shared = node.lock();
|
||||
assert(shared);
|
||||
return shared->data.get();
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -129,18 +131,20 @@ const TKey& CPrefixTrie<TKey, TData>::Iterator<IsConst>::key() const
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
TData& CPrefixTrie<TKey, TData>::Iterator<IsConst>::data()
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::TDataRef CPrefixTrie<TKey, TData>::Iterator<IsConst>::data()
|
||||
{
|
||||
assert(!node.expired());
|
||||
return *(node.lock()->data);
|
||||
auto shared = node.lock();
|
||||
assert(shared);
|
||||
return *(shared->data);
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
const TData& CPrefixTrie<TKey, TData>::Iterator<IsConst>::data() const
|
||||
{
|
||||
assert(!node.expired());
|
||||
return *(node.lock()->data);
|
||||
auto shared = node.lock();
|
||||
assert(shared);
|
||||
return *(shared->data);
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -174,21 +178,6 @@ std::vector<typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>> CPref
|
||||
return ret;
|
||||
}
|
||||
|
||||
template <typename TKey>
|
||||
static std::size_t match(const TKey& a, const TKey& b)
|
||||
{
|
||||
std::size_t count = 0;
|
||||
auto ait = a.cbegin(), aend = a.cend();
|
||||
auto bit = b.cbegin(), bend = b.cend();
|
||||
while (ait != aend && bit != bend) {
|
||||
if (*ait != *bit) break;
|
||||
++count;
|
||||
++ait;
|
||||
++bit;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <typename TIterator, typename TNode>
|
||||
TIterator CPrefixTrie<TKey, TData>::find(const TKey& key, TNode node, TIterator end)
|
||||
@@ -220,6 +209,24 @@ bool CPrefixTrie<TKey, TData>::find(const TKey& key, TNode node, const callback<
|
||||
return find(TKey(key.begin() + count, key.end()), it->second, cb);
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <typename TIterator, typename TNode>
|
||||
std::vector<TIterator> CPrefixTrie<TKey, TData>::nodes(const TKey& key, TNode root)
|
||||
{
|
||||
std::vector<TIterator> ret;
|
||||
ret.reserve(1 + key.size());
|
||||
ret.emplace_back(TKey{}, root);
|
||||
if (key.empty()) return ret;
|
||||
TKey name;
|
||||
using CBType = callback<TNode>;
|
||||
CBType cb = [&name, &ret](const TKey& key, TNode node) {
|
||||
name.insert(name.end(), key.begin(), key.end());
|
||||
ret.emplace_back(name, node);
|
||||
};
|
||||
find(key, root, cb);
|
||||
return ret;
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
std::shared_ptr<typename CPrefixTrie<TKey, TData>::Node>& CPrefixTrie<TKey, TData>::insert(const TKey& key, std::shared_ptr<typename CPrefixTrie<TKey, TData>::Node>& node)
|
||||
{
|
||||
@@ -238,20 +245,19 @@ std::shared_ptr<typename CPrefixTrie<TKey, TData>::Node>& CPrefixTrie<TKey, TDat
|
||||
if (count == 0) {
|
||||
++size;
|
||||
it = children.emplace(key, std::make_shared<Node>()).first;
|
||||
it->second->data = std::make_shared<TData>();
|
||||
return it->second;
|
||||
}
|
||||
if (count < it->first.size()) {
|
||||
const TKey prefix(key.begin(), key.begin() + count);
|
||||
const TKey postfix(it->first.begin() + count, it->first.end());
|
||||
TKey prefix(key.begin(), key.begin() + count);
|
||||
TKey postfix(it->first.begin() + count, it->first.end());
|
||||
auto nodes = std::move(it->second);
|
||||
children.erase(it);
|
||||
++size;
|
||||
it = children.emplace(prefix, std::make_shared<Node>()).first;
|
||||
it->second->children.emplace(postfix, std::move(nodes));
|
||||
it->second->data = std::make_shared<TData>();
|
||||
it = children.emplace(std::move(prefix), std::make_shared<Node>()).first;
|
||||
it->second->children.emplace(std::move(postfix), std::move(nodes));
|
||||
if (key.size() == count)
|
||||
return it->second;
|
||||
it->second->data = std::make_shared<TData>();
|
||||
}
|
||||
return insert(TKey(key.begin() + count, key.end()), it->second);
|
||||
}
|
||||
@@ -281,7 +287,7 @@ void CPrefixTrie<TKey, TData>::erase(const TKey& key, std::shared_ptr<Node>& nod
|
||||
auto& postfix = child->first;
|
||||
newKey.insert(newKey.end(), postfix.begin(), postfix.end());
|
||||
auto& pNode = nodes[nodes.size() - 2].second;
|
||||
pNode->children.emplace(newKey, std::move(child->second));
|
||||
pNode->children.emplace(std::move(newKey), std::move(child->second));
|
||||
pNode->children.erase(prefix);
|
||||
--size;
|
||||
continue;
|
||||
@@ -314,12 +320,14 @@ typename CPrefixTrie<TKey, TData>::iterator CPrefixTrie<TKey, TData>::insert(con
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
typename CPrefixTrie<TKey, TData>::iterator CPrefixTrie<TKey, TData>::copy(CPrefixTrie<TKey, TData>::const_iterator it)
|
||||
typename CPrefixTrie<TKey, TData>::iterator CPrefixTrie<TKey, TData>::copy(CPrefixTrie<TKey, TData>::const_iterator it, bool wipeChildren)
|
||||
{
|
||||
auto& key = it.key();
|
||||
auto& node = key.empty() ? root : insert(key, root);
|
||||
node->data = it.node.lock()->data;
|
||||
return key.empty() ? begin() : iterator{key, node};
|
||||
if (wipeChildren)
|
||||
node->children.clear();
|
||||
return iterator{key, node};
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -386,21 +394,17 @@ TData& CPrefixTrie<TKey, TData>::at(const TKey& key)
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
std::vector<typename CPrefixTrie<TKey, TData>::iterator> CPrefixTrie<TKey, TData>::nodes(const TKey& key) const
|
||||
std::vector<typename CPrefixTrie<TKey, TData>::iterator> CPrefixTrie<TKey, TData>::nodes(const TKey& key)
|
||||
{
|
||||
std::vector<iterator> ret;
|
||||
if (empty()) return ret;
|
||||
ret.reserve(1 + key.size());
|
||||
ret.emplace_back(TKey{}, root);
|
||||
if (key.empty()) return ret;
|
||||
TKey name;
|
||||
using CBType = callback<std::shared_ptr<Node>>;
|
||||
CBType cb = [&name, &ret](const TKey& key, std::shared_ptr<Node> node) {
|
||||
name.insert(name.end(), key.begin(), key.end());
|
||||
ret.emplace_back(name, node);
|
||||
};
|
||||
find(key, root, cb);
|
||||
return ret;
|
||||
if (empty()) return {};
|
||||
return nodes<iterator>(key, root);
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
std::vector<typename CPrefixTrie<TKey, TData>::const_iterator> CPrefixTrie<TKey, TData>::nodes(const TKey& key) const
|
||||
{
|
||||
if (empty()) return {};
|
||||
return nodes<const_iterator>(key, root);
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -444,7 +448,7 @@ typename CPrefixTrie<TKey, TData>::iterator CPrefixTrie<TKey, TData>::begin()
|
||||
template <typename TKey, typename TData>
|
||||
typename CPrefixTrie<TKey, TData>::iterator CPrefixTrie<TKey, TData>::end()
|
||||
{
|
||||
return iterator{TKey(), std::shared_ptr<Node>{}};
|
||||
return {};
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -456,7 +460,7 @@ typename CPrefixTrie<TKey, TData>::const_iterator CPrefixTrie<TKey, TData>::cbeg
|
||||
template <typename TKey, typename TData>
|
||||
typename CPrefixTrie<TKey, TData>::const_iterator CPrefixTrie<TKey, TData>::cend()
|
||||
{
|
||||
return const_iterator{TKey(), std::shared_ptr<Node>{}};
|
||||
return {};
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -468,7 +472,7 @@ typename CPrefixTrie<TKey, TData>::const_iterator CPrefixTrie<TKey, TData>::begi
|
||||
template <typename TKey, typename TData>
|
||||
typename CPrefixTrie<TKey, TData>::const_iterator CPrefixTrie<TKey, TData>::end() const
|
||||
{
|
||||
return const_iterator{TKey(), std::shared_ptr<Node>{}};
|
||||
return {};
|
||||
}
|
||||
|
||||
using Key = std::string;
|
||||
|
||||
+32
-8
@@ -9,6 +9,10 @@
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
|
||||
namespace bc = boost::container;
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
class CPrefixTrie
|
||||
{
|
||||
@@ -17,7 +21,7 @@ class CPrefixTrie
|
||||
template <bool>
|
||||
friend class Iterator;
|
||||
friend class CPrefixTrie<TKey, TData>;
|
||||
std::map<TKey, std::shared_ptr<Node>> children;
|
||||
bc::flat_map<TKey, std::shared_ptr<Node>> children;
|
||||
|
||||
public:
|
||||
Node() = default;
|
||||
@@ -37,9 +41,10 @@ class CPrefixTrie
|
||||
friend class Iterator;
|
||||
friend class CPrefixTrie<TKey, TData>;
|
||||
|
||||
using TKeyRef = std::reference_wrapper<const TKey>;
|
||||
using TDataRef = std::reference_wrapper<TData>;
|
||||
using TPair = std::pair<TKeyRef, TDataRef>;
|
||||
using TDataRef = typename std::conditional<IsConst, const TData&, TData&>::type;
|
||||
using TKeyWrap = std::reference_wrapper<const TKey>;
|
||||
using TDataWrap = std::reference_wrapper<TData>;
|
||||
using TPair = std::pair<TKeyWrap, TDataWrap>;
|
||||
|
||||
TKey name;
|
||||
std::weak_ptr<Node> node;
|
||||
@@ -61,7 +66,7 @@ class CPrefixTrie
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using iterator_category = std::forward_iterator_tag;
|
||||
|
||||
Iterator() = delete;
|
||||
Iterator() = default;
|
||||
Iterator(const Iterator&) = default;
|
||||
Iterator(Iterator&& o) noexcept = default;
|
||||
Iterator(const TKey& name, const std::shared_ptr<Node>& node) noexcept;
|
||||
@@ -90,7 +95,7 @@ class CPrefixTrie
|
||||
|
||||
const TKey& key() const;
|
||||
|
||||
TData& data();
|
||||
TDataRef data();
|
||||
const TData& data() const;
|
||||
|
||||
std::size_t depth() const;
|
||||
@@ -111,6 +116,9 @@ class CPrefixTrie
|
||||
template <typename TNode>
|
||||
static bool find(const TKey& key, TNode node, const callback<TNode>& cb);
|
||||
|
||||
template <typename TIterator, typename TNode>
|
||||
static std::vector<TIterator> nodes(const TKey& key, TNode root);
|
||||
|
||||
std::shared_ptr<Node>& insert(const TKey& key, std::shared_ptr<Node>& node);
|
||||
void erase(const TKey& key, std::shared_ptr<Node>& node);
|
||||
|
||||
@@ -125,7 +133,7 @@ public:
|
||||
template <typename TDataUni>
|
||||
iterator insert(iterator& it, const TKey& key, TDataUni&& data);
|
||||
|
||||
iterator copy(const_iterator it);
|
||||
iterator copy(const_iterator it, bool wipeChildren);
|
||||
|
||||
iterator find(const TKey& key);
|
||||
const_iterator find(const TKey& key) const;
|
||||
@@ -136,7 +144,8 @@ public:
|
||||
|
||||
TData& at(const TKey& key);
|
||||
|
||||
std::vector<iterator> nodes(const TKey& key) const;
|
||||
std::vector<iterator> nodes(const TKey& key);
|
||||
std::vector<const_iterator> nodes(const TKey& key) const;
|
||||
|
||||
bool erase(const TKey& key);
|
||||
|
||||
@@ -193,4 +202,19 @@ inline bool operator!=(const std::reference_wrapper<std::unique_ptr<T>>& ref, co
|
||||
return !(ref == obj);
|
||||
}
|
||||
|
||||
template <typename TKey>
|
||||
static std::size_t match(const TKey& a, const TKey& b)
|
||||
{
|
||||
std::size_t count = 0;
|
||||
auto ait = a.cbegin(), aend = a.cend();
|
||||
auto bit = b.cbegin(), bend = b.cend();
|
||||
while (ait != aend && bit != bend) {
|
||||
if (*ait != *bit) break;
|
||||
++count;
|
||||
++ait;
|
||||
++bit;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
#endif // BITCOIN_PREFIXTRIE_H
|
||||
@@ -0,0 +1,345 @@
|
||||
|
||||
#ifndef CLAIMRPCHELP_H
|
||||
#define CLAIMRPCHELP_H
|
||||
|
||||
// always keep defines T_ + value in upper case
|
||||
#define T_NORMALIZEDNAME "normalizedName"
|
||||
#define T_BLOCKHASH "blockhash"
|
||||
#define T_CLAIMS "claims"
|
||||
#define T_CLAIMID "claimId"
|
||||
#define T_TXID "txId"
|
||||
#define T_N "n"
|
||||
#define T_AMOUNT "amount"
|
||||
#define T_HEIGHT "height"
|
||||
#define T_VALUE "value"
|
||||
#define T_NAME "name"
|
||||
#define T_VALIDATHEIGHT "validAtHeight"
|
||||
#define T_NAMES "names"
|
||||
#define T_EFFECTIVEAMOUNT "effectiveAmount"
|
||||
#define T_LASTTAKEOVERHEIGHT "lastTakeoverHeight"
|
||||
#define T_SUPPORTS "supports"
|
||||
#define T_SUPPORTSWITHOUTCLAIM "supportsWithoutClaim"
|
||||
#define T_TOTALNAMES "totalNames"
|
||||
#define T_TOTALCLAIMS "totalClaims"
|
||||
#define T_TOTALVALUE "totalValue"
|
||||
#define T_CONTROLLINGONLY "controllingOnly"
|
||||
#define T_CLAIMTYPE "claimType"
|
||||
#define T_DEPTH "depth"
|
||||
#define T_INCLAIMTRIE "inClaimTrie"
|
||||
#define T_ISCONTROLLING "isControlling"
|
||||
#define T_INSUPPORTMAP "inSupportMap"
|
||||
#define T_INQUEUE "inQueue"
|
||||
#define T_BLOCKSTOVALID "blocksToValid"
|
||||
#define T_NODES "nodes"
|
||||
#define T_CHILDREN "children"
|
||||
#define T_CHARACTER "character"
|
||||
#define T_NODEHASH "nodeHash"
|
||||
#define T_VALUEHASH "valueHash"
|
||||
#define T_PAIRS "pairs"
|
||||
#define T_ODD "odd"
|
||||
#define T_HASH "hash"
|
||||
#define T_BID "bid"
|
||||
#define T_SEQUENCE "sequence"
|
||||
#define T_CLAIMSADDEDORUPDATED "claimsAddedOrUpdated"
|
||||
#define T_SUPPORTSADDEDORUPDATED "supportsAddedOrUpdated"
|
||||
#define T_CLAIMSREMOVED "claimsRemoved"
|
||||
#define T_SUPPORTSREMOVED "supportsRemoved"
|
||||
#define T_ADDRESS "address"
|
||||
#define T_PENDINGAMOUNT "pendingAmount"
|
||||
|
||||
enum {
|
||||
GETCLAIMSINTRIE = 0,
|
||||
GETNAMESINTRIE,
|
||||
GETVALUEFORNAME,
|
||||
GETCLAIMSFORNAME,
|
||||
GETCLAIMBYID,
|
||||
GETTOTALCLAIMEDNAMES,
|
||||
GETTOTALCLAIMS,
|
||||
GETTOTALVALUEOFCLAIMS,
|
||||
GETCLAIMSFORTX,
|
||||
GETNAMEPROOF,
|
||||
CHECKNORMALIZATION,
|
||||
GETCLAIMBYBID,
|
||||
GETCLAIMBYSEQ,
|
||||
GETCLAIMPROOFBYBID,
|
||||
GETCLAIMPROOFBYSEQ,
|
||||
GETCHANGESINBLOCK,
|
||||
};
|
||||
|
||||
#define S3_(pre, name, def) pre "\"" name "\"" def "\n"
|
||||
#define S3(pre, name, def) S3_(pre, name, def)
|
||||
#define S1(str) str "\n"
|
||||
|
||||
#define NAME_TEXT " (string) the name to look up"
|
||||
#define BLOCKHASH_TEXT " (string, optional) get claims in the trie\n" \
|
||||
" at the block specified\n" \
|
||||
" by this block hash.\n" \
|
||||
" If none is given,\n" \
|
||||
" the latest active\n" \
|
||||
" block will be used."
|
||||
|
||||
#define CLAIM_OUTPUT \
|
||||
S3(" ", T_NORMALIZEDNAME, " (string) the name of the claim (after normalization)") \
|
||||
S3(" ", T_NAME, " (string) the original name of this claim (before normalization)") \
|
||||
S3(" ", T_VALUE, " (string) the value of this claim") \
|
||||
S3(" ", T_ADDRESS, " (string) the destination address of this claim") \
|
||||
S3(" ", T_CLAIMID, " (string) the claimId of the claim") \
|
||||
S3(" ", T_TXID, " (string) the txid of the claim") \
|
||||
S3(" ", T_N, " (numeric) the index of the claim in the transaction's list of outputs") \
|
||||
S3(" ", T_HEIGHT, " (numeric) the height of the block in which this transaction is located") \
|
||||
S3(" ", T_VALIDATHEIGHT, " (numeric) the height at which the support became/becomes valid") \
|
||||
S3(" ", T_AMOUNT, " (numeric) the amount of the claim") \
|
||||
S3(" ", T_EFFECTIVEAMOUNT, " (numeric) the amount plus amount from all supports associated with the claim") \
|
||||
S3(" ", T_PENDINGAMOUNT, " (numeric) expected amount when claim and its supports are all valid") \
|
||||
S3(" ", T_SUPPORTS, ": [ (array of object) supports for this claim") \
|
||||
S3(" ", T_VALUE, " (string) the metadata of the support if any") \
|
||||
S3(" ", T_ADDRESS, " (string) the destination address of the support") \
|
||||
S3(" ", T_TXID, " (string) the txid of the support") \
|
||||
S3(" ", T_N, " (numeric) the index of the support in the transaction's list of outputs") \
|
||||
S3(" ", T_HEIGHT, " (numeric) the height of the block in which this transaction is located") \
|
||||
S3(" ", T_VALIDATHEIGHT, " (numeric) the height at which the support became/becomes valid") \
|
||||
S3(" ", T_AMOUNT, " (numeric) the amount of the support") \
|
||||
S1(" ]") \
|
||||
S3(" ", T_LASTTAKEOVERHEIGHT, " (numeric) the last height at which ownership of the name changed") \
|
||||
S3(" ", T_BID, " (numeric) lower value means a higher bid rate, ordered by effective amount") \
|
||||
S3(" ", T_SEQUENCE, " (numeric) lower value means an older one in sequence, ordered by height of insertion")
|
||||
|
||||
#define PROOF_OUTPUT \
|
||||
S3(" ", T_NODES, ": [ (array of object, pre-fork) full nodes\n" \
|
||||
" (i.e. those which lead to the requested name)") \
|
||||
S3(" ", T_CHILDREN, ": [ (array of object) the children of the node") \
|
||||
S3(" ", T_CHARACTER, " (string) the character which leads from the parent to this child node") \
|
||||
S3(" ", T_NODEHASH, " (string, if exists) the hash of the node if this is a leaf node") \
|
||||
S1(" ]") \
|
||||
S3(" ", T_VALUEHASH, " (string, if exists) the hash of this node's value, if" \
|
||||
" it has one. If this is the requested name this\n" \
|
||||
" will not exist whether the node has a value or not") \
|
||||
S1(" ]") \
|
||||
S3(" ", T_PAIRS, ": [ (array of pairs, post-fork) hash can be validated by" \
|
||||
" hashing claim from the bottom up") \
|
||||
S3(" ", T_ODD, " (boolean) this value goes on the right of hash") \
|
||||
S3(" ", T_HASH, " (string) the hash to be mixed in") \
|
||||
S1(" ]") \
|
||||
S3(" ", T_TXID, " (string, if exists) the txid of the claim which controls" \
|
||||
" this name, if there is one.") \
|
||||
S3(" ", T_N, " (numeric) the index of the claim in the transaction's list of outputs") \
|
||||
S3(" ", T_LASTTAKEOVERHEIGHT, " (numeric) the last height at which ownership of the name changed")
|
||||
|
||||
static const char* const rpc_help[] = {
|
||||
|
||||
// GETCLAIMSINTRIE
|
||||
S1(R"(getclaimsintrie
|
||||
Return all claims in the name trie. Deprecated
|
||||
Arguments:)")
|
||||
S3("1. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
S3(" ", T_NORMALIZEDNAME, " (string) the name of the claim(s) (after normalization)")
|
||||
S3(" ", T_CLAIMS, ": [ (array of object) the claims for this name")
|
||||
S3(" ", T_NAME, " (string) the original name of this claim (before normalization)")
|
||||
S3(" ", T_VALUE, " (string) the value of this claim")
|
||||
S3(" ", T_ADDRESS, " (string) the destination address of this claim")
|
||||
S3(" ", T_CLAIMID, " (string) the claimId of the claim")
|
||||
S3(" ", T_TXID, " (string) the txid of the claim")
|
||||
S3(" ", T_N, " (numeric) the index of the claim in the transaction's list of outputs")
|
||||
S3(" ", T_HEIGHT, " (numeric) the height of the block in which this transaction is located")
|
||||
S3(" ", T_VALIDATHEIGHT, " (numeric) the height at which the claim became/becomes valid")
|
||||
S3(" ", T_AMOUNT, " (numeric) the amount of the claim")
|
||||
S1(" ]")
|
||||
"]",
|
||||
|
||||
// GETNAMESINTRIE
|
||||
S1(R"(getnamesintrie
|
||||
Return all claim names in the trie.
|
||||
Arguments:)")
|
||||
S3("1. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
S3(" ", T_NAMES, " all names in the trie that have claims")
|
||||
"]",
|
||||
|
||||
// GETVALUEFORNAME
|
||||
S1(R"(getvalueforname
|
||||
Return the winning or specified by claimId value associated with a name
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S3("3. ", T_CLAIMID, " (string, optional) can be partial one")
|
||||
S1("Result: [")
|
||||
CLAIM_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCLAIMSFORNAME
|
||||
S1(R"(getclaimsforname
|
||||
Return all claims and supports for a name
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
S3(" ", T_NORMALIZEDNAME, " (string) the name of the claim(s) (after normalization)")
|
||||
S3(" ", T_CLAIMS, ": [ (array of object) the claims for this name")
|
||||
S3(" ", T_NAME, " (string) the original name of this claim (before normalization)")
|
||||
S3(" ", T_VALUE, " (string) the value of this claim")
|
||||
S3(" ", T_ADDRESS, " (string) the destination address of this claim")
|
||||
S3(" ", T_CLAIMID, " (string) the claimId of the claim")
|
||||
S3(" ", T_TXID, " (string) the txid of the claim")
|
||||
S3(" ", T_N, " (numeric) the index of the claim in the transaction's list of outputs")
|
||||
S3(" ", T_HEIGHT, " (numeric) the height of the block in which this transaction is located")
|
||||
S3(" ", T_VALIDATHEIGHT, " (numeric) the height at which the claim became/becomes valid")
|
||||
S3(" ", T_AMOUNT, " (numeric) the amount of the claim")
|
||||
S3(" ", T_EFFECTIVEAMOUNT, " (numeric) the amount plus amount from all supports associated with the claim")
|
||||
S3(" ", T_PENDINGAMOUNT, " (numeric) expected amount when claim and its support got valid")
|
||||
S3(" ", T_SUPPORTS, ": [ (array of object) supports for this claim")
|
||||
S3(" ", T_VALUE, " (string) the metadata of the support if any")
|
||||
S3(" ", T_ADDRESS, " (string) the destination address of the support")
|
||||
S3(" ", T_TXID, " (string) the txid of the support")
|
||||
S3(" ", T_N, " (numeric) the index of the support in the transaction's list of outputs")
|
||||
S3(" ", T_HEIGHT, " (numeric) the height of the block in which this transaction is located")
|
||||
S3(" ", T_VALIDATHEIGHT, " (numeric) the height at which the support became/becomes valid")
|
||||
S3(" ", T_AMOUNT, " (numeric) the amount of the support")
|
||||
S1(" ]")
|
||||
S3(" ", T_BID, " (numeric) lower value means a higher bid rate, ordered by effective amount")
|
||||
S3(" ", T_SEQUENCE, " (numeric) lower value means an older one in sequence, ordered by height of insertion")
|
||||
S1(" ]")
|
||||
S3(" ", T_LASTTAKEOVERHEIGHT, " (numeric) the last height at which ownership of the name changed")
|
||||
S3(" ", T_SUPPORTSWITHOUTCLAIM, ": [")
|
||||
S3(" ", T_TXID, " (string) the txid of the support")
|
||||
S3(" ", T_N, " (numeric) the index of the support in the transaction's list of outputs")
|
||||
S3(" ", T_HEIGHT, " (numeric) the height of the block in which this transaction is located")
|
||||
S3(" ", T_VALIDATHEIGHT, " (numeric) the height at which the support became/becomes valid")
|
||||
S3(" ", T_AMOUNT, " (numeric) the amount of the support")
|
||||
S1(" ]")
|
||||
"]",
|
||||
|
||||
// GETCLAIMBYID
|
||||
S1(R"(getclaimbyid
|
||||
Get a claim by claim id
|
||||
Arguments:)")
|
||||
S3("1. ", T_CLAIMID, " (string) the claimId of this claim or patial id (at least 3 chars)")
|
||||
S1("Result: [")
|
||||
CLAIM_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETTOTALCLAIMEDNAMES
|
||||
S1(R"(gettotalclaimednames
|
||||
Return the total number of names that have been
|
||||
Arguments:)")
|
||||
S1("Result:")
|
||||
S3(" ", T_TOTALNAMES, " (numeric) the total number of names in the trie")
|
||||
,
|
||||
|
||||
// GETTOTALCLAIMS
|
||||
S1(R"(gettotalclaims
|
||||
Return the total number of active claims in the trie
|
||||
Arguments:)")
|
||||
S1("Result:")
|
||||
S3(" ", T_TOTALCLAIMS, " (numeric) the total number of active claims")
|
||||
,
|
||||
|
||||
// GETTOTALVALUEOFCLAIMS
|
||||
S1(R"(gettotalvalueofclaims
|
||||
Return the total value of the claims in the trie
|
||||
Arguments:)")
|
||||
S3("1. ", T_CONTROLLINGONLY, " (boolean) only include the value of controlling claims")
|
||||
S1("Result:")
|
||||
S3(" ", T_TOTALVALUE, " (numeric) the total value of the claims in the trie")
|
||||
,
|
||||
|
||||
// GETCLAIMSFORTX
|
||||
S1(R"(getclaimsfortx
|
||||
Return any claims or supports found in a transaction
|
||||
Arguments:)")
|
||||
S3("1. ", T_TXID, " (string) the txid of the transaction to check for unspent claims")
|
||||
S1("Result: [")
|
||||
S3(" ", T_N, " (numeric) the index of the claim in the transaction's list of outputs")
|
||||
S3(" ", T_CLAIMTYPE, " (string) claim or support")
|
||||
S3(" ", T_NAME, " (string) the name claimed or supported")
|
||||
S3(" ", T_CLAIMID, " (string) if a claim, its ID")
|
||||
S3(" ", T_VALUE, " (string) if a claim, its value")
|
||||
S3(" ", T_DEPTH, " (numeric) the depth of the transaction in the main chain")
|
||||
S3(" ", T_INCLAIMTRIE, " (boolean) if a name claim, whether the claim is active, i.e. has made it into the trie")
|
||||
S3(" ", T_ISCONTROLLING, " (boolean) if a name claim, whether the claim is the current controlling claim for the name")
|
||||
S3(" ", T_INSUPPORTMAP, " (boolean) if a support, whether the support is active, i.e. has made it into the support map")
|
||||
S3(" ", T_INQUEUE, " (boolean) whether the claim is in a queue waiting to be inserted into the trie or support map")
|
||||
S3(" ", T_BLOCKSTOVALID, " (numeric) if in a queue, the number of blocks until it's inserted into the trie or support map")
|
||||
"]",
|
||||
|
||||
// GETNAMEPROOF
|
||||
S1(R"(getnameproof
|
||||
Return the cryptographic proof that a name maps to a value or doesn't.
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S3("3. ", T_CLAIMID, R"( (string, optional, post-fork) for validating a specific claim
|
||||
can be partial one)")
|
||||
S1("Result: [")
|
||||
PROOF_OUTPUT
|
||||
"]",
|
||||
|
||||
// CHECKNORMALIZATION
|
||||
S1(R"(checknormalization
|
||||
Given an unnormalized name of a claim, return normalized version of it
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, " (string) the name to normalize")
|
||||
S1("Result:")
|
||||
S3(" ", T_NORMALIZEDNAME, " (string) normalized name")
|
||||
,
|
||||
|
||||
// GETCLAIMBYBID
|
||||
S1(R"(getclaimbybid
|
||||
Get a claim by bid
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_BID, " (numeric) bid number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
CLAIM_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCLAIMBYSEQ
|
||||
S1(R"(getclaimbyseq
|
||||
Get a claim by sequence
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_SEQUENCE, " (numeric) sequence number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
CLAIM_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCLAIMPROOFBYBID
|
||||
S1(R"(getclaimproofbyid
|
||||
Return the cryptographic proof that a name maps to a value or doesn't by a bid.
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_BID, " (numeric) bid number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
PROOF_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCLAIMPROOFBYSEQ
|
||||
S1(R"(getclaimproofbyseq
|
||||
Return the cryptographic proof that a name maps to a value or doesn't by a sequence.
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_SEQUENCE, " (numeric) sequence number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
PROOF_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCHANGESINBLOCK
|
||||
S1(R"(getchangesinblock
|
||||
Return the list of claims added, updated, and removed as pulled from the queued work for that block."
|
||||
Use this method to determine which claims or supports went live on a given block."
|
||||
Arguments:)")
|
||||
S3("1. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
S3(" ", T_CLAIMSADDEDORUPDATED, " (array of string) claimIDs added or updated in the trie")
|
||||
S3(" ", T_CLAIMSREMOVED, " (array of string) claimIDs that were removed from the trie")
|
||||
S3(" ", T_SUPPORTSADDEDORUPDATED, " (array of string) IDs of supports added or updated")
|
||||
S3(" ", T_SUPPORTSREMOVED, " (array of string) IDs that were removed from the trie")
|
||||
"]",
|
||||
|
||||
};
|
||||
|
||||
#endif // CLAIMRPCHELP_H
|
||||
+619
-606
File diff suppressed because it is too large.
Load diff
@@ -171,6 +171,14 @@ static const CRPCConvertParam vRPCConvertParams[] =
|
||||
{ "rescanblockchain", 0, "start_height"},
|
||||
{ "rescanblockchain", 1, "stop_height"},
|
||||
{ "createwallet", 1, "disable_private_keys"},
|
||||
{ "listnameclaims", 0, "includesupports"},
|
||||
{ "listnameclaims", 1, "activeonly"},
|
||||
{ "listnameclaims", 2, "minconf"},
|
||||
{ "getclaimbybid", 1, "bid"},
|
||||
{ "getclaimbyseq", 1, "sequence"},
|
||||
{ "getclaimproofbybid", 1, "bid"},
|
||||
{ "getclaimproofbyseq", 1, "sequence"},
|
||||
{ "supportclaim", 4, "isTip"},
|
||||
};
|
||||
|
||||
class CRPCConvertTable
|
||||
|
||||
@@ -1757,7 +1757,7 @@ UniValue converttopsbt(const JSONRPCRequest& request)
|
||||
"createpsbt and walletcreatefundedpsbt should be used for new applications.\n"
|
||||
"\nArguments:\n"
|
||||
"1. \"hexstring\" (string, required) The hex string of a raw transaction\n"
|
||||
"2. permitsigdata (boolean, optional, default=false) If true, any signatures in the input will be discarded and conversion.\n"
|
||||
"2. permitsigdata (boolean, optional, default=false) If true, any signatures in the input will be discarded and conversion\n"
|
||||
" will continue. If false, RPC will fail if any signatures are present.\n"
|
||||
"3. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction.\n"
|
||||
" If iswitness is not present, heuristic tests will be used in decoding. If true, only witness deserializaion\n"
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <script/interpreter.h>
|
||||
#include <nameclaim.h>
|
||||
|
||||
#include <crypto/ripemd160.h>
|
||||
#include <crypto/sha1.h>
|
||||
@@ -1505,10 +1506,13 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
|
||||
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
|
||||
|
||||
// Bare witness programs
|
||||
|
||||
const CScript& strippedScriptPubKey = StripClaimScriptPrefix(scriptPubKey);
|
||||
|
||||
int witnessversion;
|
||||
std::vector<unsigned char> witnessprogram;
|
||||
if (flags & SCRIPT_VERIFY_WITNESS) {
|
||||
if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
|
||||
if (strippedScriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
|
||||
hadWitness = true;
|
||||
if (scriptSig.size() != 0) {
|
||||
// The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
|
||||
@@ -1524,7 +1528,7 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
|
||||
}
|
||||
|
||||
// Additional validation for spend-to-script-hash transactions:
|
||||
if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
|
||||
if ((flags & SCRIPT_VERIFY_P2SH) && strippedScriptPubKey.IsPayToScriptHash())
|
||||
{
|
||||
// scriptSig must be literals-only or validation fails
|
||||
if (!scriptSig.IsPushOnly())
|
||||
|
||||
+17
-29
@@ -40,8 +40,6 @@ enum class IsMineResult
|
||||
WATCH_ONLY = 1, //! Included in watch-only balance
|
||||
SPENDABLE = 2, //! Included in all balances
|
||||
INVALID = 3, //! Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
|
||||
CLAIM = 4,
|
||||
SUPPORT = 5,
|
||||
};
|
||||
|
||||
bool PermitsUncompressed(IsMineSigVersion sigversion)
|
||||
@@ -60,17 +58,11 @@ bool HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
|
||||
|
||||
IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion)
|
||||
{
|
||||
int op = 0;
|
||||
IsMineResult ret = IsMineResult::NO;
|
||||
|
||||
CScript strippedScriptPubKey = StripClaimScriptPrefix(scriptPubKey, op);
|
||||
IsMineResult claim_ret = ((op == OP_CLAIM_NAME || op == OP_UPDATE_CLAIM) ? IsMineResult::CLAIM :
|
||||
((op == OP_SUPPORT_CLAIM) ? IsMineResult::SUPPORT :
|
||||
IsMineResult::NO));
|
||||
|
||||
std::vector<valtype> vSolutions;
|
||||
txnouttype whichType;
|
||||
Solver(strippedScriptPubKey, whichType, vSolutions);
|
||||
Solver(scriptPubKey, whichType, vSolutions);
|
||||
|
||||
CKeyID keyID;
|
||||
switch (whichType)
|
||||
@@ -85,7 +77,7 @@ IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey,
|
||||
return IsMineResult::INVALID;
|
||||
}
|
||||
if (keystore.HaveKey(keyID)) {
|
||||
ret = std::max(claim_ret, IsMineResult::SPENDABLE);
|
||||
ret = std::max(ret, IsMineResult::SPENDABLE);
|
||||
}
|
||||
break;
|
||||
case TX_WITNESS_V0_KEYHASH:
|
||||
@@ -100,10 +92,6 @@ IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey,
|
||||
// This also applies to the P2WSH case.
|
||||
break;
|
||||
}
|
||||
// Claims are not explicitly supported on Witness v0
|
||||
// Transactions, and instead of supporting the wrapped inner
|
||||
// tx, we are ignoring this type at this time (consistent with
|
||||
// previous releases).
|
||||
ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
|
||||
break;
|
||||
}
|
||||
@@ -116,7 +104,7 @@ IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey,
|
||||
}
|
||||
}
|
||||
if (keystore.HaveKey(keyID)) {
|
||||
ret = std::max(claim_ret, IsMineResult::SPENDABLE);
|
||||
ret = std::max(ret, IsMineResult::SPENDABLE);
|
||||
}
|
||||
break;
|
||||
case TX_SCRIPTHASH:
|
||||
@@ -128,7 +116,7 @@ IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey,
|
||||
CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
|
||||
CScript subscript;
|
||||
if (keystore.GetCScript(scriptID, subscript)) {
|
||||
ret = std::max(claim_ret, IsMineInner(keystore, subscript, IsMineSigVersion::P2SH));
|
||||
ret = std::max(ret, IsMineInner(keystore, subscript, IsMineSigVersion::P2SH));
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -146,10 +134,6 @@ IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey,
|
||||
CScriptID scriptID = CScriptID(hash);
|
||||
CScript subscript;
|
||||
if (keystore.GetCScript(scriptID, subscript)) {
|
||||
// Claims are not explicitly supported on Witness v0
|
||||
// Transactions, and instead of supporting the wrapped inner
|
||||
// tx, we are ignoring this type at this time (consistent with
|
||||
// previous releases).
|
||||
ret = std::max(ret, IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0));
|
||||
}
|
||||
break;
|
||||
@@ -176,14 +160,14 @@ IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey,
|
||||
}
|
||||
}
|
||||
if (HaveKeys(keys, keystore)) {
|
||||
ret = std::max(claim_ret, IsMineResult::SPENDABLE);
|
||||
ret = std::max(ret, IsMineResult::SPENDABLE);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
|
||||
ret = std::max(claim_ret, IsMineResult::WATCH_ONLY);
|
||||
ret = std::max(ret, IsMineResult::WATCH_ONLY);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -192,18 +176,22 @@ IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey,
|
||||
|
||||
isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey)
|
||||
{
|
||||
switch (IsMineInner(keystore, scriptPubKey, IsMineSigVersion::TOP)) {
|
||||
isminetype flags = ISMINE_NO;
|
||||
int op;
|
||||
CScript strippedScriptPubKey = StripClaimScriptPrefix(scriptPubKey, op);
|
||||
if (op == OP_CLAIM_NAME || op == OP_UPDATE_CLAIM)
|
||||
flags = ISMINE_CLAIM;
|
||||
else if (op == OP_SUPPORT_CLAIM)
|
||||
flags = ISMINE_SUPPORT;
|
||||
|
||||
switch (IsMineInner(keystore, strippedScriptPubKey, IsMineSigVersion::TOP)) {
|
||||
case IsMineResult::INVALID:
|
||||
case IsMineResult::NO:
|
||||
return ISMINE_NO;
|
||||
case IsMineResult::WATCH_ONLY:
|
||||
return ISMINE_WATCH_ONLY;
|
||||
return ISMINE_WATCH_ONLY; // addresses we're watching are never considered our claim or support -- but should they be?
|
||||
case IsMineResult::SPENDABLE:
|
||||
return ISMINE_SPENDABLE;
|
||||
case IsMineResult::CLAIM:
|
||||
return ISMINE_CLAIM;
|
||||
case IsMineResult::SUPPORT:
|
||||
return ISMINE_SUPPORT;
|
||||
return isminetype(ISMINE_SPENDABLE | flags);
|
||||
}
|
||||
assert(false);
|
||||
}
|
||||
|
||||
+3
-1
@@ -21,7 +21,9 @@ enum isminetype
|
||||
ISMINE_SPENDABLE = 2,
|
||||
ISMINE_CLAIM = 4,
|
||||
ISMINE_SUPPORT = 8,
|
||||
ISMINE_ALL = ISMINE_WATCH_ONLY | ISMINE_SPENDABLE
|
||||
ISMINE_ALL = ISMINE_WATCH_ONLY | ISMINE_SPENDABLE,
|
||||
ISMINE_STAKE = ISMINE_CLAIM | ISMINE_SUPPORT,
|
||||
ISMINE_SPENDABLE_OR_STAKE = ISMINE_SPENDABLE | ISMINE_STAKE
|
||||
};
|
||||
/** used for bitflags of isminetype */
|
||||
typedef uint8_t isminefilter;
|
||||
|
||||
+1
-5
@@ -11,8 +11,6 @@
|
||||
#include <script/standard.h>
|
||||
#include <uint256.h>
|
||||
|
||||
#include "nameclaim.h"
|
||||
|
||||
typedef std::vector<unsigned char> valtype;
|
||||
|
||||
MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn) {}
|
||||
@@ -102,10 +100,8 @@ static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator
|
||||
ret.clear();
|
||||
std::vector<unsigned char> sig;
|
||||
|
||||
const CScript& strippedScriptPubKey = StripClaimScriptPrefix(scriptPubKey);
|
||||
|
||||
std::vector<valtype> vSolutions;
|
||||
if (!Solver(strippedScriptPubKey, whichTypeRet, vSolutions))
|
||||
if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
|
||||
return false;
|
||||
|
||||
switch (whichTypeRet)
|
||||
|
||||
+10
-8
@@ -6,9 +6,9 @@
|
||||
#include <script/standard.h>
|
||||
|
||||
#include <crypto/sha256.h>
|
||||
#include <nameclaim.h>
|
||||
#include <pubkey.h>
|
||||
#include <script/script.h>
|
||||
#include <util.h>
|
||||
#include <utilstrencodings.h>
|
||||
|
||||
|
||||
@@ -91,19 +91,21 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::v
|
||||
{
|
||||
vSolutionsRet.clear();
|
||||
|
||||
auto strippedPubKey = StripClaimScriptPrefix(scriptPubKey);
|
||||
|
||||
// Shortcut for pay-to-script-hash, which are more constrained than the other types:
|
||||
// it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
|
||||
if (scriptPubKey.IsPayToScriptHash())
|
||||
if (strippedPubKey.IsPayToScriptHash())
|
||||
{
|
||||
typeRet = TX_SCRIPTHASH;
|
||||
std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
|
||||
std::vector<unsigned char> hashBytes(strippedPubKey.begin()+2, strippedPubKey.begin()+22);
|
||||
vSolutionsRet.push_back(hashBytes);
|
||||
return true;
|
||||
}
|
||||
|
||||
int witnessversion;
|
||||
std::vector<unsigned char> witnessprogram;
|
||||
if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
|
||||
if (strippedPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
|
||||
if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_KEYHASH_SIZE) {
|
||||
typeRet = TX_WITNESS_V0_KEYHASH;
|
||||
vSolutionsRet.push_back(witnessprogram);
|
||||
@@ -129,19 +131,19 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::v
|
||||
// So long as script passes the IsUnspendable() test and all but the first
|
||||
// byte passes the IsPushOnly() test we don't care what exactly is in the
|
||||
// script.
|
||||
if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
|
||||
if (strippedPubKey.size() >= 1 && strippedPubKey[0] == OP_RETURN && strippedPubKey.IsPushOnly(strippedPubKey.begin()+1)) {
|
||||
typeRet = TX_NULL_DATA;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<unsigned char> data;
|
||||
if (MatchPayToPubkey(scriptPubKey, data)) {
|
||||
if (MatchPayToPubkey(strippedPubKey, data)) {
|
||||
typeRet = TX_PUBKEY;
|
||||
vSolutionsRet.push_back(std::move(data));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (MatchPayToPubkeyHash(scriptPubKey, data)) {
|
||||
if (MatchPayToPubkeyHash(strippedPubKey, data)) {
|
||||
typeRet = TX_PUBKEYHASH;
|
||||
vSolutionsRet.push_back(std::move(data));
|
||||
return true;
|
||||
@@ -149,7 +151,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::v
|
||||
|
||||
unsigned int required;
|
||||
std::vector<std::vector<unsigned char>> keys;
|
||||
if (MatchMultisig(scriptPubKey, required, keys)) {
|
||||
if (MatchMultisig(strippedPubKey, required, keys)) {
|
||||
typeRet = TX_MULTISIG;
|
||||
vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16
|
||||
vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end());
|
||||
|
||||
+7
-7
@@ -559,8 +559,8 @@ template<typename Stream, typename K, typename T> void Unserialize(Stream& is, s
|
||||
/**
|
||||
* map
|
||||
*/
|
||||
template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
|
||||
template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
|
||||
template<typename Stream, typename K, typename T, typename ... Z> void Serialize(Stream& os, const std::map<K, T, Z...>& m);
|
||||
template<typename Stream, typename K, typename T, typename ... Z> void Unserialize(Stream& is, std::map<K, T, Z...>& m);
|
||||
|
||||
/**
|
||||
* set
|
||||
@@ -781,20 +781,20 @@ void Unserialize(Stream& is, std::pair<K, T>& item)
|
||||
/**
|
||||
* map
|
||||
*/
|
||||
template<typename Stream, typename K, typename T, typename Pred, typename A>
|
||||
void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
|
||||
template<typename Stream, typename K, typename T, typename ... Z>
|
||||
void Serialize(Stream& os, const std::map<K, T, Z...>& m)
|
||||
{
|
||||
WriteCompactSize(os, m.size());
|
||||
for (const auto& entry : m)
|
||||
Serialize(os, entry);
|
||||
}
|
||||
|
||||
template<typename Stream, typename K, typename T, typename Pred, typename A>
|
||||
void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
|
||||
template<typename Stream, typename K, typename T, typename ... Z>
|
||||
void Unserialize(Stream& is, std::map<K, T, Z...>& m)
|
||||
{
|
||||
m.clear();
|
||||
unsigned int nSize = ReadCompactSize(is);
|
||||
typename std::map<K, T, Pred, A>::iterator mi = m.begin();
|
||||
typename std::map<K, T, Z...>::iterator mi = m.begin();
|
||||
for (unsigned int i = 0; i < nSize; i++)
|
||||
{
|
||||
std::pair<K, T> item;
|
||||
|
||||
@@ -227,6 +227,10 @@ public:
|
||||
return (std::string(begin(), end()));
|
||||
}
|
||||
|
||||
std::size_t capacity() const
|
||||
{
|
||||
return vch.capacity();
|
||||
}
|
||||
|
||||
//
|
||||
// Vector subset
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include <pow.h>
|
||||
#include <primitives/transaction.h>
|
||||
#include <random.h>
|
||||
#include <rpc/claimrpchelp.h>
|
||||
#include <rpc/server.h>
|
||||
#include <streams.h>
|
||||
#include <test/test_bitcoin.h>
|
||||
@@ -25,6 +26,7 @@
|
||||
extern ::CChainState g_chainstate;
|
||||
extern ::ArgsManager gArgs;
|
||||
extern std::vector<std::string> random_strings(std::size_t count);
|
||||
extern bool getClaimById(const uint160&, std::string&, CClaimValue*);
|
||||
|
||||
using namespace std;
|
||||
|
||||
@@ -72,7 +74,7 @@ static BlockAssembler AssemblerForTest()
|
||||
}
|
||||
|
||||
// Test Fixtures
|
||||
struct ClaimTrieChainFixture: public CClaimTrieCacheExpirationFork
|
||||
struct ClaimTrieChainFixture: public CClaimTrieCache
|
||||
{
|
||||
std::vector<CTransaction> coinbase_txs;
|
||||
std::vector<int> marks;
|
||||
@@ -85,11 +87,12 @@ struct ClaimTrieChainFixture: public CClaimTrieCacheExpirationFork
|
||||
int64_t expirationForkHeight;
|
||||
int64_t originalExpiration;
|
||||
int64_t extendedExpiration;
|
||||
int64_t forkhash_original;
|
||||
|
||||
using CClaimTrieCacheExpirationFork::getSupportsForName;
|
||||
using CClaimTrieCache::getSupportsForName;
|
||||
|
||||
ClaimTrieChainFixture(): CClaimTrieCacheExpirationFork(pclaimTrie),
|
||||
unique_block_counter(0), normalization_original(-1), expirationForkHeight(-1)
|
||||
ClaimTrieChainFixture(): CClaimTrieCache(pclaimTrie),
|
||||
unique_block_counter(0), normalization_original(-1), expirationForkHeight(-1), forkhash_original(-1)
|
||||
{
|
||||
fRequireStandard = false;
|
||||
BOOST_CHECK_EQUAL(nNextHeight, chainActive.Height() + 1);
|
||||
@@ -121,6 +124,9 @@ struct ClaimTrieChainFixture: public CClaimTrieCacheExpirationFork
|
||||
consensus.nExtendedClaimExpirationTime = extendedExpiration;
|
||||
consensus.nOriginalClaimExpirationTime = originalExpiration;
|
||||
}
|
||||
if (forkhash_original >= 0) {
|
||||
consensus.nAllClaimsInMerkleForkHeight = forkhash_original;
|
||||
}
|
||||
}
|
||||
|
||||
void setExpirationForkHeight(int targetMinusCurrent, int64_t preForkExpirationTime, int64_t postForkExpirationTime) {
|
||||
@@ -145,6 +151,15 @@ struct ClaimTrieChainFixture: public CClaimTrieCacheExpirationFork
|
||||
consensus.nNormalizedNameForkHeight = target;
|
||||
}
|
||||
|
||||
void setHashForkHeight(int targetMinusCurrent)
|
||||
{
|
||||
int target = chainActive.Height() + targetMinusCurrent;
|
||||
auto& consensus = const_cast<Consensus::Params&>(Params().GetConsensus());
|
||||
if (forkhash_original < 0)
|
||||
forkhash_original = consensus.nAllClaimsInMerkleForkHeight;
|
||||
consensus.nAllClaimsInMerkleForkHeight = target;
|
||||
}
|
||||
|
||||
bool CreateBlock(const std::unique_ptr<CBlockTemplate>& pblocktemplate)
|
||||
{
|
||||
CBlock* pblock = &pblocktemplate->block;
|
||||
@@ -351,7 +366,7 @@ struct ClaimTrieChainFixture: public CClaimTrieCacheExpirationFork
|
||||
if (!expirationQueue.second.empty())
|
||||
return false;
|
||||
}
|
||||
return keyTypeEmpty<int>(EXP_QUEUE_ROW);
|
||||
return keyTypeEmpty<int>(CLAIM_EXP_QUEUE_ROW);
|
||||
}
|
||||
|
||||
bool supportEmpty()
|
||||
@@ -421,7 +436,7 @@ struct ClaimTrieChainFixture: public CClaimTrieCacheExpirationFork
|
||||
res.message() << "No claim found";
|
||||
return res;
|
||||
} else {
|
||||
CAmount effective_amount = getEffectiveAmountForClaim(name, val.claimId);
|
||||
CAmount effective_amount = getClaimsForName(name).find(val.claimId).effectiveAmount;
|
||||
if (effective_amount != amount) {
|
||||
boost::test_tools::predicate_result res(false);
|
||||
res.message() << amount << " != " << effective_amount;
|
||||
@@ -431,6 +446,8 @@ struct ClaimTrieChainFixture: public CClaimTrieCacheExpirationFork
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t getTotalNamesInTrie() const { return base->getTotalNamesInTrie(); }
|
||||
};
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(claimtriebranching_tests, RegTestingSetup)
|
||||
@@ -495,16 +512,34 @@ BOOST_AUTO_TEST_CASE(triehash_fuzzer_test)
|
||||
}
|
||||
}
|
||||
fixture.IncrementBlocks(1);
|
||||
if (blocks > 13 && i % 50 == 0) // travisCI needs some periodic output
|
||||
std::cerr << "In triehash_fuzzer_test with " << fixture.getTotalNamesInTrie() << " names at block " << i << std::endl;
|
||||
}
|
||||
|
||||
if (blocks == 1000 && claimsPerBlock == 100)
|
||||
BOOST_CHECK_EQUAL(fixture.getMerkleHash().GetHex(), "21b25760f8e0f3e95514ff90b8ef3758b270e50fe17f747ba29f99dd1874bf41");
|
||||
BOOST_CHECK_EQUAL(fixture.getMerkleHash().GetHex(), "28825257a129eef69cab87d6255c8359fc6dc083ca7f09222526e3a7971f382d");
|
||||
else if (blocks == 13 && claimsPerBlock == 100)
|
||||
BOOST_CHECK_EQUAL(fixture.getMerkleHash().GetHex(), "4e5984d6984f5f05d50e821e6228d56bcfbd16ca2093cd0308f6ff1c2bc8689a");
|
||||
else
|
||||
std::cerr << "Hash: " << fixture.getMerkleHash().GetHex() << std::endl;
|
||||
}
|
||||
#endif
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_replace_test) {
|
||||
// no competing bids
|
||||
ClaimTrieChainFixture fixture;
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "bass", "one", 1);
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "basso", "two", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("bass", tx1));
|
||||
fixture.Spend(tx1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "bassfisher", "one", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(fixture.getMerkleHash()));
|
||||
BOOST_CHECK(!fixture.is_best_claim("bass", tx1));
|
||||
BOOST_CHECK(fixture.is_best_claim("bassfisher", tx2));
|
||||
}
|
||||
|
||||
/*
|
||||
claims
|
||||
no competing bids
|
||||
@@ -533,12 +568,12 @@ BOOST_AUTO_TEST_CASE(claim_test)
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(),"test","one",2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx3));
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claims.size());
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claimsNsupports.size());
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",tx2));
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",tx3));
|
||||
BOOST_CHECK_EQUAL(0U, fixture.getClaimsForName("test").claims.size());
|
||||
BOOST_CHECK_EQUAL(0U, fixture.getClaimsForName("test").claimsNsupports.size());
|
||||
|
||||
// make two claims , one older
|
||||
CMutableTransaction tx4 = fixture.MakeClaim(fixture.GetCoinbase(),"test","one",1);
|
||||
@@ -550,7 +585,7 @@ BOOST_AUTO_TEST_CASE(claim_test)
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx4));
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx4));
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claims.size());
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claimsNsupports.size());
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx4));
|
||||
@@ -570,7 +605,7 @@ BOOST_AUTO_TEST_CASE(claim_test)
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx6));
|
||||
fixture.IncrementBlocks(10);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx7));
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claims.size());
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claimsNsupports.size());
|
||||
|
||||
fixture.DecrementBlocks(10);
|
||||
BOOST_CHECK(fixture.is_claim_in_queue("test",tx7));
|
||||
@@ -840,7 +875,7 @@ BOOST_AUTO_TEST_CASE(support_spend_test)
|
||||
CMutableTransaction s2 = fixture.MakeSupport(fixture.GetCoinbase(),tx5,"test",2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx5));
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claims.size());
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claimsNsupports.size());
|
||||
|
||||
// build the spend where s2 is sppent on txin[1] and tx3 is spent on txin[0]
|
||||
uint32_t prevout = 0;
|
||||
@@ -905,7 +940,7 @@ BOOST_AUTO_TEST_CASE(claimtrie_update_test)
|
||||
CMutableTransaction u3 = fixture.MakeUpdate(tx3, "test", "one", ClaimIdHash(tx3.GetHash(), 0), 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",u3));
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claims.size());
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claimsNsupports.size());
|
||||
fixture.DecrementBlocks(11);
|
||||
|
||||
// losing update on winning claim happens without delay
|
||||
@@ -913,7 +948,7 @@ BOOST_AUTO_TEST_CASE(claimtrie_update_test)
|
||||
CMutableTransaction tx6 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 2);
|
||||
fixture.IncrementBlocks(10);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx5));
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claims.size());
|
||||
BOOST_CHECK_EQUAL(2U, fixture.getClaimsForName("test").claimsNsupports.size());
|
||||
CMutableTransaction u4 = fixture.MakeUpdate(tx5, "test", "one", ClaimIdHash(tx5.GetHash(), 0), 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx6));
|
||||
@@ -1021,7 +1056,7 @@ BOOST_AUTO_TEST_CASE(claimtrie_expire_test)
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx6));
|
||||
}
|
||||
/*
|
||||
* tests for CClaimTrie::getEffectiveAmountForClaim
|
||||
* tests for effectiveAmount
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(claimtriebranching_get_effective_amount_for_claim)
|
||||
{
|
||||
@@ -1031,42 +1066,42 @@ BOOST_AUTO_TEST_CASE(claimtriebranching_get_effective_amount_for_claim)
|
||||
uint160 claimId = ClaimIdHash(claimtx.GetHash(), 0);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId), 2);
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("inexistent", claimId), 0); //not found returns 0
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId).effectiveAmount, 2);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("inexistent").find(claimId).effectiveAmount, 0); //not found returns 0
|
||||
|
||||
// one claim, one support
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), claimtx, "test", 40);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId), 42);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId).effectiveAmount, 42);
|
||||
|
||||
// Two claims, first one with supports
|
||||
CMutableTransaction claimtx2 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "two", 1);
|
||||
uint160 claimId2 = ClaimIdHash(claimtx2.GetHash(), 0);
|
||||
fixture.IncrementBlocks(10);
|
||||
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId), 42);
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId2), 1);
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("inexistent", claimId), 0);
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("inexistent", claimId2), 0);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId).effectiveAmount, 42);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId2).effectiveAmount, 1);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("inexistent").find(claimId).effectiveAmount, 0);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("inexistent").find(claimId2).effectiveAmount, 0);
|
||||
|
||||
// Two claims, both with supports, second claim effective amount being less than first claim
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), claimtx2, "test", 6);
|
||||
fixture.IncrementBlocks(13); //delay
|
||||
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId), 42);
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId2), 7);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId).effectiveAmount, 42);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId2).effectiveAmount, 7);
|
||||
|
||||
// Two claims, both with supports, second one taking over
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), claimtx2, "test", 1330);
|
||||
fixture.IncrementBlocks(26); //delay
|
||||
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId), 42);
|
||||
BOOST_CHECK_EQUAL(fixture.getEffectiveAmountForClaim("test", claimId2), 1337);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId).effectiveAmount, 42);
|
||||
BOOST_CHECK_EQUAL(fixture.getClaimsForName("test").find(claimId2).effectiveAmount, 1337);
|
||||
}
|
||||
|
||||
/*
|
||||
* tests for CClaimTrie::getClaimById basic consistency checks
|
||||
* tests for getClaimById basic consistency checks
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(get_claim_by_id_test)
|
||||
{
|
||||
@@ -1078,7 +1113,7 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test)
|
||||
|
||||
CClaimValue claimValue;
|
||||
std::string claimName;
|
||||
fixture.getClaimById(claimId, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId);
|
||||
|
||||
@@ -1089,14 +1124,14 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test)
|
||||
uint160 claimId2 = ClaimIdHash(tx2.GetHash(), 0);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
fixture.getClaimById(claimId2, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimId2, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId2);
|
||||
|
||||
|
||||
CMutableTransaction u1 = fixture.MakeUpdate(tx1, name, "updated one", claimId, 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
fixture.getClaimById(claimId, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId);
|
||||
BOOST_CHECK_EQUAL(claimValue.nAmount, 1);
|
||||
@@ -1104,24 +1139,24 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test)
|
||||
|
||||
fixture.Spend(u1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.getClaimById(claimId, claimName, claimValue));
|
||||
BOOST_CHECK(!getClaimById(claimId, claimName, &claimValue));
|
||||
|
||||
fixture.DecrementBlocks(3);
|
||||
|
||||
CClaimValue claimValue2;
|
||||
claimName = "";
|
||||
fixture.getClaimById(claimId2, claimName, claimValue2);
|
||||
BOOST_CHECK(!getClaimById(claimId2, claimName, &claimValue2));
|
||||
BOOST_CHECK(claimName != name);
|
||||
BOOST_CHECK(claimValue2.claimId != claimId2);
|
||||
|
||||
fixture.getClaimById(claimId, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId);
|
||||
|
||||
fixture.DecrementBlocks(2);
|
||||
|
||||
claimName = "";
|
||||
fixture.getClaimById(claimId, claimName, claimValue2);
|
||||
BOOST_CHECK(!getClaimById(claimId, claimName, &claimValue2));
|
||||
BOOST_CHECK(claimName != name);
|
||||
BOOST_CHECK(claimValue2.claimId != claimId);
|
||||
}
|
||||
@@ -1402,8 +1437,8 @@ BOOST_AUTO_TEST_CASE(claimtriebranching_normalization)
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", tx1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("normalizetest", 3));
|
||||
|
||||
CClaimValue val;
|
||||
BOOST_CHECK(!fixture.getInfoForName("normalizeTest", val));
|
||||
CClaimTrieData data;
|
||||
BOOST_CHECK(!pclaimTrie->find("normalizeTest", data));
|
||||
|
||||
// Check equivalence of normalized claim names
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", tx1)); // collapsed tx2
|
||||
@@ -1502,7 +1537,7 @@ BOOST_AUTO_TEST_CASE(claimtriecache_normalization)
|
||||
|
||||
CClaimValue lookupClaim;
|
||||
std::string lookupName;
|
||||
BOOST_CHECK(fixture.getClaimById(ClaimIdHash(tx2.GetHash(), 0), lookupName, lookupClaim));
|
||||
BOOST_CHECK(getClaimById(ClaimIdHash(tx2.GetHash(), 0), lookupName, &lookupClaim));
|
||||
CClaimValue nval1;
|
||||
BOOST_CHECK(fixture.getInfoForName("amelie1", nval1));
|
||||
// amélie is not found cause normalization still not appear
|
||||
@@ -1532,7 +1567,8 @@ BOOST_AUTO_TEST_CASE(claimtriecache_normalization)
|
||||
BOOST_CHECK(!trieCache.spendClaim(name_normd, COutPoint(tx2.GetHash(), 0), currentHeight, amelieValidHeight));
|
||||
BOOST_CHECK(trieCache.spendClaim(name_upper, COutPoint(tx2.GetHash(), 0), currentHeight, amelieValidHeight));
|
||||
|
||||
BOOST_CHECK(!fixture.getInfoForName(name, nval1));
|
||||
CClaimTrieData data;
|
||||
BOOST_CHECK(!pclaimTrie->find(name, data));
|
||||
BOOST_CHECK(trieCache.getInfoForName(name, nval1));
|
||||
BOOST_CHECK(trieCache.addClaim(name, COutPoint(tx1.GetHash(), 0), ClaimIdHash(tx1.GetHash(), 0), CAmount(2), currentHeight + 1));
|
||||
BOOST_CHECK(trieCache.getInfoForName(name, nval1));
|
||||
@@ -1544,10 +1580,8 @@ BOOST_AUTO_TEST_CASE(claimtriecache_normalization)
|
||||
BOOST_CHECK(trieCache.incrementBlock(insertUndo, expireUndo, insertSupportUndo, expireSupportUndo, takeoverHeightUndo));
|
||||
BOOST_CHECK(trieCache.shouldNormalize());
|
||||
|
||||
// we cannot use getXXXForName cause they will normalized name
|
||||
for (auto it = pclaimTrie->begin(); it != pclaimTrie->end(); ++it) {
|
||||
BOOST_CHECK(it.key() != name);
|
||||
}
|
||||
CClaimTrieDataNode node;
|
||||
BOOST_CHECK(!pclaimTrie->find(name, node));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(undo_normalization_does_not_kill_claim_order)
|
||||
@@ -1582,13 +1616,13 @@ BOOST_AUTO_TEST_CASE(normalized_activations_fall_through)
|
||||
BOOST_CHECK(fixture.is_best_claim("AB", tx1));
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(fixture.is_best_claim("ab", tx2));
|
||||
BOOST_CHECK(fixture.getClaimsForName("ab").claims.size() == 4U);
|
||||
BOOST_CHECK(fixture.getClaimsForName("ab").claimsNsupports.size() == 4U);
|
||||
fixture.DecrementBlocks(3);
|
||||
fixture.Spend(tx1);
|
||||
fixture.Spend(tx2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("ab", tx3));
|
||||
BOOST_CHECK(fixture.getClaimsForName("ab").claims.size() == 2U);
|
||||
BOOST_CHECK(fixture.getClaimsForName("ab").claimsNsupports.size() == 2U);
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("AB", tx1));
|
||||
fixture.Spend(tx1);
|
||||
@@ -1634,8 +1668,10 @@ BOOST_AUTO_TEST_CASE(normalization_removal_test)
|
||||
supportQueueRowType expireSupportUndo;
|
||||
std::vector<std::pair<std::string, int> > takeoverHeightUndo;
|
||||
BOOST_CHECK(cache.incrementBlock(insertUndo, expireUndo, insertSupportUndo, expireSupportUndo, takeoverHeightUndo));
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").claims.size() == 3U);
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").supports.size() == 2U);
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").claimsNsupports.size() == 3U);
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").claimsNsupports[0].supports.size() == 1U);
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").claimsNsupports[1].supports.size() == 0U);
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").claimsNsupports[2].supports.size() == 1U);
|
||||
BOOST_CHECK(cache.decrementBlock(insertUndo, expireUndo, insertSupportUndo, expireSupportUndo));
|
||||
BOOST_CHECK(cache.finalizeDecrement(takeoverHeightUndo));
|
||||
BOOST_CHECK(cache.undoAddSupport("AB", COutPoint(sx1.GetHash(), 0), height));
|
||||
@@ -1643,7 +1679,7 @@ BOOST_AUTO_TEST_CASE(normalization_removal_test)
|
||||
BOOST_CHECK(cache.undoAddClaim("AB", COutPoint(tx1.GetHash(), 0), height));
|
||||
BOOST_CHECK(cache.undoAddClaim("Ab", COutPoint(tx2.GetHash(), 0), height));
|
||||
BOOST_CHECK(cache.undoAddClaim("aB", COutPoint(tx3.GetHash(), 0), height));
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").claims.size() == 0U);
|
||||
BOOST_CHECK(cache.getClaimsForName("ab").claimsNsupports.size() == 0U);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalization_does_not_kill_supports)
|
||||
@@ -1713,7 +1749,7 @@ BOOST_AUTO_TEST_CASE(normalization_does_not_kill_sort_order)
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.is_best_claim("A", tx2));
|
||||
BOOST_CHECK(fixture.is_best_claim("a", tx3));
|
||||
BOOST_CHECK(fixture.getClaimsForName("a").claims.size() == 3U);
|
||||
BOOST_CHECK(fixture.getClaimsForName("a").claimsNsupports.size() == 3U);
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
@@ -2183,7 +2219,7 @@ BOOST_AUTO_TEST_CASE(insert_update_claim_test)
|
||||
<< std::vector<unsigned char>(sName1.begin(), sName1.end())
|
||||
<< std::vector<unsigned char>(tx1ClaimId.begin(), tx1ClaimId.end())
|
||||
<< std::vector<unsigned char>(sValue1.begin(), sValue1.end()) << OP_2DROP << OP_2DROP << OP_TRUE;
|
||||
tx8.vout[0].nValue = tx8.vout[0].nValue - 1;
|
||||
tx8.vout[0].nValue -= 1;
|
||||
tx8.vout[1].scriptPubKey = CScript() << OP_CLAIM_NAME
|
||||
<< std::vector<unsigned char>(sName1.begin(), sName1.end())
|
||||
<< std::vector<unsigned char>(sValue2.begin(), sValue2.end()) << OP_2DROP << OP_DROP << OP_TRUE;
|
||||
@@ -2615,18 +2651,6 @@ BOOST_AUTO_TEST_CASE(claimtrienode_serialize_unserialize)
|
||||
ss >> n2;
|
||||
BOOST_CHECK_EQUAL(n1, n2);
|
||||
|
||||
n1.hash.SetHex("0000000000000000000000000000000000000000000000000000000000000001");
|
||||
BOOST_CHECK(n1 != n2);
|
||||
ss << n1;
|
||||
ss >> n2;
|
||||
BOOST_CHECK_EQUAL(n1, n2);
|
||||
|
||||
n1.hash.SetHex("a79e8a5b28f7fa5e8836a4b48da9988bdf56ce749f81f413cb754f963a516200");
|
||||
BOOST_CHECK(n1 != n2);
|
||||
ss << n1;
|
||||
ss >> n2;
|
||||
BOOST_CHECK_EQUAL(n1, n2);
|
||||
|
||||
CClaimValue v1(COutPoint(uint256S("0000000000000000000000000000000000000000000000000000000000000001"), 0), hash160, 50, 0, 100);
|
||||
CClaimValue v2(COutPoint(uint256S("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"), 1), hash160, 100, 1, 101);
|
||||
|
||||
@@ -3591,10 +3615,10 @@ bool verify_proof(const CClaimTrieProof proof, uint256 rootHash, const std::stri
|
||||
std::string computedReverseName;
|
||||
bool verifiedValue = false;
|
||||
|
||||
for (std::vector<CClaimTrieProofNode>::const_reverse_iterator itNodes = proof.nodes.rbegin(); itNodes != proof.nodes.rend(); ++itNodes) {
|
||||
for (auto itNodes = proof.nodes.rbegin(); itNodes != proof.nodes.rend(); ++itNodes) {
|
||||
bool foundChildInChain = false;
|
||||
std::vector<unsigned char> vchToHash;
|
||||
for (std::vector<std::pair<unsigned char, uint256> >::const_iterator 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);
|
||||
uint256 childHash;
|
||||
if (itChildren->second.IsNull()) {
|
||||
@@ -3817,7 +3841,7 @@ BOOST_AUTO_TEST_CASE(bogus_claimtrie_hash_test)
|
||||
}
|
||||
|
||||
/*
|
||||
* tests for CClaimTrie::getClaimById basic consistency checks
|
||||
* tests for getClaimById basic consistency checks
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(get_claim_by_id_test_2)
|
||||
{
|
||||
@@ -3832,7 +3856,7 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test_2)
|
||||
|
||||
CClaimValue claimValue;
|
||||
std::string claimName;
|
||||
fixture.getClaimById(claimId, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId);
|
||||
|
||||
@@ -3840,16 +3864,16 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test_2)
|
||||
CMutableTransaction txb = fixture.Spend(txx);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.getClaimById(claimId, claimName, claimValue));
|
||||
BOOST_CHECK(!fixture.getClaimById(claimIdx, claimName, claimValue));
|
||||
BOOST_CHECK(!getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK(!getClaimById(claimIdx, claimName, &claimValue));
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
fixture.getClaimById(claimId, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId);
|
||||
|
||||
// this test fails
|
||||
fixture.getClaimById(claimIdx, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimIdx, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimIdx);
|
||||
}
|
||||
@@ -3866,7 +3890,7 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test_3)
|
||||
|
||||
CClaimValue claimValue;
|
||||
std::string claimName;
|
||||
fixture.getClaimById(claimId, claimName, claimValue);
|
||||
BOOST_CHECK(getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId);
|
||||
// make second claim with activation delay 1
|
||||
@@ -3876,14 +3900,14 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test_3)
|
||||
fixture.IncrementBlocks(1);
|
||||
// second claim is not activated yet, but can still access by claim id
|
||||
BOOST_CHECK(fixture.is_best_claim(name, tx1));
|
||||
BOOST_CHECK(fixture.getClaimById(claimId2, claimName, claimValue));
|
||||
BOOST_CHECK(getClaimById(claimId2, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId2);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
// second claim has activated
|
||||
BOOST_CHECK(fixture.is_best_claim(name, tx2));
|
||||
BOOST_CHECK(fixture.getClaimById(claimId2, claimName, claimValue));
|
||||
BOOST_CHECK(getClaimById(claimId2, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId2);
|
||||
|
||||
@@ -3892,14 +3916,14 @@ BOOST_AUTO_TEST_CASE(get_claim_by_id_test_3)
|
||||
// second claim has been deactivated via decrement
|
||||
// should still be accesible via claim id
|
||||
BOOST_CHECK(fixture.is_best_claim(name, tx1));
|
||||
BOOST_CHECK(fixture.getClaimById(claimId2, claimName, claimValue));
|
||||
BOOST_CHECK(getClaimById(claimId2, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId2);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
// second claim should have been re activated via increment
|
||||
BOOST_CHECK(fixture.is_best_claim(name, tx2));
|
||||
BOOST_CHECK(fixture.getClaimById(claimId2, claimName, claimValue));
|
||||
BOOST_CHECK(getClaimById(claimId2, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId2);
|
||||
}
|
||||
@@ -3948,15 +3972,15 @@ BOOST_AUTO_TEST_CASE(getvalueforname_test)
|
||||
req.params.push_back(UniValue(sName1));
|
||||
|
||||
UniValue results = getvalueforname(req);
|
||||
BOOST_CHECK_EQUAL(results["value"].get_str(), HexStr(sValue1));
|
||||
BOOST_CHECK_EQUAL(results["amount"].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(results["effective amount"].get_int(), 5);
|
||||
BOOST_CHECK_EQUAL(results[T_VALUE].get_str(), HexStr(sValue1));
|
||||
BOOST_CHECK_EQUAL(results[T_AMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(results[T_EFFECTIVEAMOUNT].get_int(), 5);
|
||||
|
||||
req.params.push_back(blockHash.GetHex());
|
||||
|
||||
results = getvalueforname(req);
|
||||
BOOST_CHECK_EQUAL(results["amount"].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(results["effective amount"].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(results[T_AMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(results[T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(getclaimsforname_test)
|
||||
@@ -3982,31 +4006,31 @@ BOOST_AUTO_TEST_CASE(getclaimsforname_test)
|
||||
req.params.push_back(UniValue(sName1));
|
||||
|
||||
UniValue results = getclaimsforname(req);
|
||||
UniValue claims = results["claims"];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 1U);
|
||||
BOOST_CHECK_EQUAL(results["nLastTakeoverHeight"].get_int(), height + 1);
|
||||
BOOST_CHECK_EQUAL(claims[0]["nEffectiveAmount"].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(claims[0]["supports"].size(), 0U);
|
||||
UniValue claims = results[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 2U);
|
||||
BOOST_CHECK_EQUAL(results[T_LASTTAKEOVERHEIGHT].get_int(), height + 1);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_SUPPORTS].size(), 0U);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
results = getclaimsforname(req);
|
||||
claims = results["claims"];
|
||||
claims = results[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 2U);
|
||||
BOOST_CHECK_EQUAL(results["nLastTakeoverHeight"].get_int(), height + 3);
|
||||
BOOST_CHECK_EQUAL(claims[0]["nEffectiveAmount"].get_int(), 3);
|
||||
BOOST_CHECK_EQUAL(claims[1]["nEffectiveAmount"].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(claims[0]["supports"].size(), 0U);
|
||||
BOOST_CHECK_EQUAL(claims[1]["supports"].size(), 0U);
|
||||
BOOST_CHECK_EQUAL(results[T_LASTTAKEOVERHEIGHT].get_int(), height + 3);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_EFFECTIVEAMOUNT].get_int(), 3);
|
||||
BOOST_CHECK_EQUAL(claims[1][T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_SUPPORTS].size(), 0U);
|
||||
BOOST_CHECK_EQUAL(claims[1][T_SUPPORTS].size(), 0U);
|
||||
|
||||
req.params.push_back(blockHash.GetHex());
|
||||
|
||||
results = getclaimsforname(req);
|
||||
claims = results["claims"];
|
||||
claims = results[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 1U);
|
||||
BOOST_CHECK_EQUAL(results["nLastTakeoverHeight"].get_int(), height + 1);
|
||||
BOOST_CHECK_EQUAL(claims[0]["nEffectiveAmount"].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(claims[0]["supports"].size(), 0U);
|
||||
BOOST_CHECK_EQUAL(results[T_LASTTAKEOVERHEIGHT].get_int(), height + 1);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_SUPPORTS].size(), 0U);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_rpcs_rollback2_test)
|
||||
@@ -4036,13 +4060,13 @@ BOOST_AUTO_TEST_CASE(claim_rpcs_rollback2_test)
|
||||
req.params.push_back(blockHash.GetHex());
|
||||
|
||||
UniValue claimsResults = getclaimsforname(req);
|
||||
BOOST_CHECK_EQUAL(claimsResults["nLastTakeoverHeight"].get_int(), height + 5);
|
||||
BOOST_CHECK_EQUAL(claimsResults["claims"][0]["supports"].size(), 0U);
|
||||
BOOST_CHECK_EQUAL(claimsResults["claims"][1]["supports"].size(), 0U);
|
||||
BOOST_CHECK_EQUAL(claimsResults[T_LASTTAKEOVERHEIGHT].get_int(), height + 5);
|
||||
BOOST_CHECK_EQUAL(claimsResults[T_CLAIMS][0][T_SUPPORTS].size(), 0U);
|
||||
BOOST_CHECK_EQUAL(claimsResults[T_CLAIMS][1][T_SUPPORTS].size(), 0U);
|
||||
|
||||
UniValue valueResults = getvalueforname(req);
|
||||
BOOST_CHECK_EQUAL(valueResults["value"].get_str(), HexStr(sValue2));
|
||||
BOOST_CHECK_EQUAL(valueResults["amount"].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(valueResults[T_VALUE].get_str(), HexStr(sValue2));
|
||||
BOOST_CHECK_EQUAL(valueResults[T_AMOUNT].get_int(), 2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_rpcs_rollback3_test)
|
||||
@@ -4077,12 +4101,11 @@ BOOST_AUTO_TEST_CASE(claim_rpcs_rollback3_test)
|
||||
req.params.push_back(blockHash.GetHex());
|
||||
|
||||
UniValue claimsResults = getclaimsforname(req);
|
||||
BOOST_CHECK_EQUAL(claimsResults["nLastTakeoverHeight"].get_int(), height + 1);
|
||||
BOOST_CHECK_EQUAL(claimsResults[T_LASTTAKEOVERHEIGHT].get_int(), height + 1);
|
||||
|
||||
UniValue valueResults = getvalueforname(req);
|
||||
BOOST_CHECK_EQUAL(valueResults["value"].get_str(), HexStr(sValue1));
|
||||
BOOST_CHECK_EQUAL(valueResults["amount"].get_int(), 3);
|
||||
|
||||
BOOST_CHECK_EQUAL(valueResults[T_VALUE].get_str(), HexStr(sValue1));
|
||||
BOOST_CHECK_EQUAL(valueResults[T_AMOUNT].get_int(), 3);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(update_on_support2_test)
|
||||
@@ -4099,14 +4122,379 @@ BOOST_AUTO_TEST_CASE(update_on_support2_test)
|
||||
CMutableTransaction s2 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, name, 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK_EQUAL(pclaimTrie->find(name)->nHeightOfLastTakeover, height + 1);
|
||||
CClaimTrieData node;
|
||||
BOOST_CHECK(pclaimTrie->find(name, node));
|
||||
BOOST_CHECK_EQUAL(node.nHeightOfLastTakeover, height + 1);
|
||||
|
||||
fixture.Spend(s1);
|
||||
fixture.Spend(s2);
|
||||
CMutableTransaction u1 = fixture.MakeUpdate(tx1, name, value, ClaimIdHash(tx1.GetHash(), 0), 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK_EQUAL(pclaimTrie->find(name)->nHeightOfLastTakeover, height + 1);
|
||||
BOOST_CHECK(pclaimTrie->find(name, node));
|
||||
BOOST_CHECK_EQUAL(node.nHeightOfLastTakeover, height + 1);
|
||||
}
|
||||
|
||||
void ValidatePairs(CClaimTrieCache& cache, const std::vector<std::pair<bool, uint256>>& pairs, uint256 claimHash)
|
||||
{
|
||||
for (auto& pair : pairs)
|
||||
if (pair.first) // we're on the right because we were an odd index number
|
||||
claimHash = Hash(pair.second.begin(), pair.second.end(), claimHash.begin(), claimHash.end());
|
||||
else
|
||||
claimHash = Hash(claimHash.begin(), claimHash.end(), pair.second.begin(), pair.second.end());
|
||||
|
||||
BOOST_CHECK_EQUAL(cache.getMerkleHash(), claimHash);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(hash_includes_all_claims_rollback_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setHashForkHeight(5);
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
uint256 currentRoot = fixture.getMerkleHash();
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK_EQUAL(currentRoot, fixture.getMerkleHash());
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK_NE(currentRoot, fixture.getMerkleHash());
|
||||
fixture.DecrementBlocks(3);
|
||||
BOOST_CHECK_EQUAL(currentRoot, fixture.getMerkleHash());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(hash_includes_all_claims_single_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setHashForkHeight(2);
|
||||
fixture.IncrementBlocks(4);
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
COutPoint outPoint(tx1.GetHash(), 0);
|
||||
uint160 claimId = ClaimIdHash(tx1.GetHash(), 0);
|
||||
|
||||
CClaimTrieProof proof;
|
||||
BOOST_CHECK(fixture.getProofForName("test", proof, [&claimId](const CClaimValue& claim) {
|
||||
return claim.claimId == claimId;
|
||||
}));
|
||||
BOOST_CHECK(proof.hasValue);
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, outPoint);
|
||||
auto claimHash = getValueHash(outPoint, proof.nHeightOfLastTakeover);
|
||||
ValidatePairs(fixture, proof.pairs, claimHash);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(hash_includes_all_claims_triple_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setHashForkHeight(2);
|
||||
fixture.IncrementBlocks(4);
|
||||
|
||||
std::string names[] = {"test", "tester", "tester2"};
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), names[0], "one", 1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), names[0], "two", 2);
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), names[0], "thr", 3);
|
||||
CMutableTransaction tx7 = fixture.MakeClaim(fixture.GetCoinbase(), names[0], "for", 4);
|
||||
CMutableTransaction tx8 = fixture.MakeClaim(fixture.GetCoinbase(), names[0], "fiv", 5);
|
||||
CMutableTransaction tx4 = fixture.MakeClaim(fixture.GetCoinbase(), names[1], "two", 2);
|
||||
CMutableTransaction tx5 = fixture.MakeClaim(fixture.GetCoinbase(), names[1], "thr", 3);
|
||||
CMutableTransaction tx6 = fixture.MakeClaim(fixture.GetCoinbase(), names[2], "one", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
for (const auto& name : names) {
|
||||
for (auto& claimSupports : fixture.getClaimsForName(name).claimsNsupports) {
|
||||
CClaimTrieProof proof;
|
||||
auto& claim = claimSupports.claim;
|
||||
BOOST_CHECK(fixture.getProofForName(name, proof, [&claim](const CClaimValue& value) {
|
||||
return claim.claimId == value.claimId;
|
||||
}));
|
||||
BOOST_CHECK(proof.hasValue);
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, claim.outPoint);
|
||||
uint256 claimHash = getValueHash(claim.outPoint, proof.nHeightOfLastTakeover);
|
||||
ValidatePairs(fixture, proof.pairs, claimHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(hash_includes_all_claims_branched_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setHashForkHeight(2);
|
||||
fixture.IncrementBlocks(4);
|
||||
|
||||
std::string names[] = {"test", "toast", "tot", "top", "toa", "toad"};
|
||||
for (const auto& name : names)
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), name, "one", 1);
|
||||
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), "toa", "two", 2);
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), "toa", "tre", 3);
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), "toa", "qua", 4);
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), "toa", "cin", 5);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
for (const auto& name : names) {
|
||||
for (auto& claimSupports : fixture.getClaimsForName(name).claimsNsupports) {
|
||||
CClaimTrieProof proof;
|
||||
auto& claim = claimSupports.claim;
|
||||
BOOST_CHECK(fixture.getProofForName(name, proof, [&claim](const CClaimValue& value) {
|
||||
return claim.claimId == value.claimId;
|
||||
}));
|
||||
BOOST_CHECK(proof.hasValue);
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, claim.outPoint);
|
||||
uint256 claimHash = getValueHash(claim.outPoint, proof.nHeightOfLastTakeover);
|
||||
ValidatePairs(fixture, proof.pairs, claimHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(hash_claims_children_fuzzer_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setHashForkHeight(2);
|
||||
fixture.IncrementBlocks(4);
|
||||
|
||||
std::size_t i = 0;
|
||||
auto names = random_strings(300);
|
||||
auto lastTx = MakeTransactionRef(fixture.GetCoinbase());
|
||||
for (const auto& name : names) {
|
||||
auto tx = fixture.MakeClaim(*lastTx, name, "one", 1);
|
||||
lastTx = MakeTransactionRef(std::move(tx));
|
||||
if (++i % 5 == 0)
|
||||
for (std::size_t j = 0; j < (i / 5); ++j) {
|
||||
auto tx = fixture.MakeClaim(*lastTx, name, "one", 1);
|
||||
lastTx = MakeTransactionRef(std::move(tx));
|
||||
}
|
||||
fixture.IncrementBlocks(1);
|
||||
}
|
||||
|
||||
for (const auto& name : names) {
|
||||
for (auto& claimSupports : fixture.getClaimsForName(name).claimsNsupports) {
|
||||
CClaimTrieProof proof;
|
||||
auto& claim = claimSupports.claim;
|
||||
BOOST_CHECK(fixture.getProofForName(name, proof, [&claim](const CClaimValue& value) {
|
||||
return claim.claimId == value.claimId;
|
||||
}));
|
||||
BOOST_CHECK(proof.hasValue);
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, claim.outPoint);
|
||||
uint256 claimHash = getValueHash(claim.outPoint, proof.nHeightOfLastTakeover);
|
||||
ValidatePairs(fixture, proof.pairs, claimHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::pair<bool, uint256>> jsonToPairs(const UniValue& jsonPair)
|
||||
{
|
||||
std::vector<std::pair<bool, uint256>> pairs;
|
||||
for (std::size_t i = 0; i < jsonPair.size(); ++i) {
|
||||
auto& jpair = jsonPair[i];
|
||||
pairs.emplace_back(jpair[T_ODD].get_bool(), uint256S(jpair[T_HASH].get_str()));
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(hash_bid_seq_claim_changes_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setHashForkHeight(2);
|
||||
fixture.IncrementBlocks(4);
|
||||
|
||||
std::string name = "toa";
|
||||
std::string value1 = "one", value2 = "two", value3 = "tre", value4 = "for";
|
||||
|
||||
auto tx1 = fixture.MakeClaim(fixture.GetCoinbase(), name, value1, 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
CMutableTransaction tx2 = BuildTransaction(fixture.GetCoinbase(), 0, 2);
|
||||
tx2.vout[0].scriptPubKey = CScript() << OP_CLAIM_NAME
|
||||
<< std::vector<unsigned char>(name.begin(), name.end())
|
||||
<< std::vector<unsigned char>(value2.begin(), value2.end()) << OP_2DROP << OP_DROP << OP_TRUE;
|
||||
tx2.vout[0].nValue = 3;
|
||||
tx2.vout[1].scriptPubKey = CScript() << OP_CLAIM_NAME
|
||||
<< std::vector<unsigned char>(name.begin(), name.end())
|
||||
<< std::vector<unsigned char>(value3.begin(), value3.end()) << OP_2DROP << OP_DROP << OP_TRUE;
|
||||
tx2.vout[1].nValue = 2;
|
||||
|
||||
fixture.CommitTx(tx2);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
auto tx3 = fixture.MakeClaim(fixture.GetCoinbase(), name, value4, 4);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
int height = chainActive.Height();
|
||||
|
||||
auto claimId1 = ClaimIdHash(tx1.GetHash(), 0);
|
||||
auto claimId2 = ClaimIdHash(tx2.GetHash(), 0);
|
||||
auto claimId3 = ClaimIdHash(tx2.GetHash(), 1);
|
||||
auto claimId4 = ClaimIdHash(tx3.GetHash(), 0);
|
||||
|
||||
int claim1bid = 3, claim1seq = 0;
|
||||
int claim2bid = 1, claim2seq = 1;
|
||||
int claim3bid = 2, claim3seq = 2;
|
||||
int claim4bid = 0, claim4seq = 3;
|
||||
|
||||
auto getclaimsforname = tableRPC["getclaimsforname"]->actor;
|
||||
|
||||
JSONRPCRequest req;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(name));
|
||||
|
||||
auto result = getclaimsforname(req);
|
||||
auto claims = result[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 4U);
|
||||
BOOST_CHECK_EQUAL(result[T_LASTTAKEOVERHEIGHT].get_int(), height);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_EFFECTIVEAMOUNT].get_int(), 4);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_BID].get_int(), claim4bid);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_SEQUENCE].get_int(), claim4seq);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_CLAIMID].get_str(), claimId4.GetHex());
|
||||
BOOST_CHECK_EQUAL(claims[1][T_EFFECTIVEAMOUNT].get_int(), 3);
|
||||
BOOST_CHECK_EQUAL(claims[1][T_BID].get_int(), claim2bid);
|
||||
BOOST_CHECK_EQUAL(claims[1][T_SEQUENCE].get_int(), claim2seq);
|
||||
BOOST_CHECK_EQUAL(claims[1][T_CLAIMID].get_str(), claimId2.GetHex());
|
||||
BOOST_CHECK_EQUAL(claims[2][T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(claims[2][T_BID].get_int(), claim3bid);
|
||||
BOOST_CHECK_EQUAL(claims[2][T_SEQUENCE].get_int(), claim3seq);
|
||||
BOOST_CHECK_EQUAL(claims[2][T_CLAIMID].get_str(), claimId3.GetHex());
|
||||
BOOST_CHECK_EQUAL(claims[3][T_EFFECTIVEAMOUNT].get_int(), 1);
|
||||
BOOST_CHECK_EQUAL(claims[3][T_BID].get_int(), claim1bid);
|
||||
BOOST_CHECK_EQUAL(claims[3][T_SEQUENCE].get_int(), claim1seq);
|
||||
BOOST_CHECK_EQUAL(claims[3][T_CLAIMID].get_str(), claimId1.GetHex());
|
||||
|
||||
auto getclaimbybid = tableRPC["getclaimbybid"]->actor;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(name));
|
||||
req.params.push_back(UniValue(claim3bid));
|
||||
|
||||
result = getclaimbybid(req);
|
||||
BOOST_CHECK_EQUAL(result[T_LASTTAKEOVERHEIGHT].get_int(), height);
|
||||
BOOST_CHECK_EQUAL(result[T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(result[T_BID].get_int(), claim3bid);
|
||||
BOOST_CHECK_EQUAL(result[T_SEQUENCE].get_int(), claim3seq);
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMID].get_str(), claimId3.GetHex());
|
||||
|
||||
auto getclaimbyseq = tableRPC["getclaimbyseq"]->actor;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(name));
|
||||
req.params.push_back(UniValue(claim2seq));
|
||||
|
||||
result = getclaimbyseq(req);
|
||||
BOOST_CHECK_EQUAL(result[T_LASTTAKEOVERHEIGHT].get_int(), height);
|
||||
BOOST_CHECK_EQUAL(result[T_EFFECTIVEAMOUNT].get_int(), 3);
|
||||
BOOST_CHECK_EQUAL(result[T_BID].get_int(), claim2bid);
|
||||
BOOST_CHECK_EQUAL(result[T_SEQUENCE].get_int(), claim2seq);
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMID].get_str(), claimId2.GetHex());
|
||||
|
||||
auto getclaimbyid = tableRPC["getclaimbyid"]->actor;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(claimId1.GetHex()));
|
||||
|
||||
result = getclaimbyid(req);
|
||||
BOOST_CHECK_EQUAL(result[T_LASTTAKEOVERHEIGHT].get_int(), height);
|
||||
BOOST_CHECK_EQUAL(result[T_EFFECTIVEAMOUNT].get_int(), 1);
|
||||
BOOST_CHECK_EQUAL(result[T_BID].get_int(), claim1bid);
|
||||
BOOST_CHECK_EQUAL(result[T_SEQUENCE].get_int(), claim1seq);
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMID].get_str(), claimId1.GetHex());
|
||||
|
||||
// check by partial id (at least 3 chars)
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(claimId3.GetHex().substr(0, 3)));
|
||||
|
||||
result = getclaimbyid(req);
|
||||
BOOST_CHECK_EQUAL(result[T_LASTTAKEOVERHEIGHT].get_int(), height);
|
||||
BOOST_CHECK_EQUAL(result[T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(result[T_BID].get_int(), claim3bid);
|
||||
BOOST_CHECK_EQUAL(result[T_SEQUENCE].get_int(), claim3seq);
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMID].get_str(), claimId3.GetHex());
|
||||
|
||||
auto blockhash = chainActive.Tip()->GetBlockHash();
|
||||
|
||||
auto getnameproof = tableRPC["getnameproof"]->actor;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(name));
|
||||
req.params.push_back(UniValue(blockhash.GetHex()));
|
||||
req.params.push_back(UniValue(claimId3.GetHex()));
|
||||
|
||||
result = getnameproof(req);
|
||||
auto claimHash = getValueHash(COutPoint(tx2.GetHash(), 1), result[T_LASTTAKEOVERHEIGHT].get_int());
|
||||
ValidatePairs(fixture, jsonToPairs(result[T_PAIRS]), claimHash);
|
||||
|
||||
// check by partial id (can be even 1 char)
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(name));
|
||||
req.params.push_back(UniValue(blockhash.GetHex()));
|
||||
req.params.push_back(UniValue(claimId2.GetHex().substr(0, 2)));
|
||||
|
||||
result = getnameproof(req);
|
||||
claimHash = getValueHash(COutPoint(tx2.GetHash(), 0), result[T_LASTTAKEOVERHEIGHT].get_int());
|
||||
ValidatePairs(fixture, jsonToPairs(result[T_PAIRS]), claimHash);
|
||||
|
||||
auto getclaimproofbybid = tableRPC["getclaimproofbybid"]->actor;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(name));
|
||||
req.params.push_back(UniValue(claim1bid));
|
||||
|
||||
result = getclaimproofbybid(req);
|
||||
claimHash = getValueHash(COutPoint(tx1.GetHash(), 0), result[T_LASTTAKEOVERHEIGHT].get_int());
|
||||
ValidatePairs(fixture, jsonToPairs(result[T_PAIRS]), claimHash);
|
||||
|
||||
auto getclaimproofbyseq = tableRPC["getclaimproofbyseq"]->actor;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(name));
|
||||
req.params.push_back(UniValue(claim4seq));
|
||||
|
||||
result = getclaimproofbyseq(req);
|
||||
claimHash = getValueHash(COutPoint(tx3.GetHash(), 0), result[T_LASTTAKEOVERHEIGHT].get_int());
|
||||
ValidatePairs(fixture, jsonToPairs(result[T_PAIRS]), claimHash);
|
||||
|
||||
auto getchangesinblock = tableRPC["getchangesinblock"]->actor;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(blockhash.GetHex()));
|
||||
|
||||
result = getchangesinblock(req);
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMSADDEDORUPDATED].size(), 3);
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMSADDEDORUPDATED][0].get_str(), claimId2.GetHex());
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMSADDEDORUPDATED][1].get_str(), claimId3.GetHex());
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMSADDEDORUPDATED][2].get_str(), claimId4.GetHex());
|
||||
BOOST_CHECK_EQUAL(result[T_CLAIMSREMOVED].size(), 0);
|
||||
BOOST_CHECK_EQUAL(result[T_SUPPORTSADDEDORUPDATED].size(), 0);
|
||||
BOOST_CHECK_EQUAL(result[T_SUPPORTSREMOVED].size(), 0);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_rpc_pending_amount_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
std::string sName1("test");
|
||||
std::string sValue1("test1");
|
||||
std::string sValue2("test2");
|
||||
|
||||
rpcfn_type getclaimsforname = tableRPC["getclaimsforname"]->actor;
|
||||
|
||||
JSONRPCRequest req;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(sName1));
|
||||
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue1, 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue2, 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
auto claims = getclaimsforname(req)[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 2U);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_EFFECTIVEAMOUNT].get_int(), 1);
|
||||
BOOST_CHECK(!claims[0].exists(T_PENDINGAMOUNT));
|
||||
BOOST_CHECK_EQUAL(claims[1][T_EFFECTIVEAMOUNT].get_int(), 0);
|
||||
BOOST_CHECK(claims[1].exists(T_PENDINGAMOUNT));
|
||||
BOOST_CHECK_EQUAL(claims[1][T_PENDINGAMOUNT].get_int(), 2);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
claims = getclaimsforname(req)[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 2U);
|
||||
BOOST_CHECK_EQUAL(claims[0][T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
BOOST_CHECK(!claims[0].exists(T_PENDINGAMOUNT));
|
||||
BOOST_CHECK_EQUAL(claims[1][T_EFFECTIVEAMOUNT].get_int(), 1);
|
||||
BOOST_CHECK(!claims[1].exists(T_PENDINGAMOUNT));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
@@ -36,7 +36,7 @@ public:
|
||||
return nodesToAddOrUpdate.height();
|
||||
}
|
||||
|
||||
CClaimTrie::iterator getCache(const std::string& key)
|
||||
CClaimPrefixTrie::iterator getCache(const std::string& key)
|
||||
{
|
||||
return nodesToAddOrUpdate.find(key);
|
||||
}
|
||||
@@ -124,7 +124,7 @@ BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK_EQUAL(ntState.getMerkleHash(), hash2);
|
||||
BOOST_CHECK(ntState.checkConsistency());
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(hash2));
|
||||
|
||||
CClaimTrieCacheTest ntState1(pclaimTrie);
|
||||
ntState1.removeClaimFromTrie(std::string("test"), tx1OutPoint, unused, true);
|
||||
@@ -144,7 +144,7 @@ BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK_EQUAL(ntState2.getMerkleHash(), hash3);
|
||||
BOOST_CHECK(ntState2.checkConsistency());
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(hash3));
|
||||
|
||||
CClaimTrieCacheTest ntState3(pclaimTrie);
|
||||
ntState3.insertClaimIntoTrie(std::string("test"), CClaimValue(tx1OutPoint, hash160, 50, 100, 200), true);
|
||||
@@ -152,7 +152,7 @@ BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
|
||||
ntState3.flush();
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK_EQUAL(ntState3.getMerkleHash(), hash4);
|
||||
BOOST_CHECK(ntState3.checkConsistency());
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(hash4));
|
||||
|
||||
CClaimTrieCacheTest ntState4(pclaimTrie);
|
||||
ntState4.removeClaimFromTrie(std::string("abab"), tx6OutPoint, unused, true);
|
||||
@@ -160,7 +160,7 @@ BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
|
||||
ntState4.flush();
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK_EQUAL(ntState4.getMerkleHash(), hash2);
|
||||
BOOST_CHECK(ntState4.checkConsistency());
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(hash2));
|
||||
|
||||
CClaimTrieCacheTest ntState5(pclaimTrie);
|
||||
ntState5.removeClaimFromTrie(std::string("test"), tx3OutPoint, unused, true);
|
||||
@@ -169,7 +169,7 @@ BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
|
||||
ntState5.flush();
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK_EQUAL(ntState5.getMerkleHash(), hash2);
|
||||
BOOST_CHECK(ntState5.checkConsistency());
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(hash2));
|
||||
|
||||
CClaimTrieCacheTest ntState6(pclaimTrie);
|
||||
ntState6.insertClaimIntoTrie(std::string("test"), CClaimValue(tx3OutPoint, hash160, 50, 101, 201), true);
|
||||
@@ -178,7 +178,7 @@ BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
|
||||
ntState6.flush();
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK_EQUAL(ntState6.getMerkleHash(), hash2);
|
||||
BOOST_CHECK(ntState6.checkConsistency());
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(hash2));
|
||||
|
||||
CClaimTrieCacheTest ntState7(pclaimTrie);
|
||||
ntState7.removeClaimFromTrie(std::string("test"), tx3OutPoint, unused, true);
|
||||
@@ -190,7 +190,7 @@ BOOST_AUTO_TEST_CASE(merkle_hash_multiple_test)
|
||||
ntState7.flush();
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK_EQUAL(ntState7.getMerkleHash(), hash0);
|
||||
BOOST_CHECK(ntState7.checkConsistency());
|
||||
BOOST_CHECK(pclaimTrie->checkConsistency(hash0));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(basic_insertion_info_test)
|
||||
@@ -200,7 +200,6 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test)
|
||||
CClaimTrieCacheTest ctc(pclaimTrie);
|
||||
|
||||
// create and insert claim
|
||||
CClaimValue unused;
|
||||
uint256 hash0(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
|
||||
CMutableTransaction tx1 = BuildTransaction(hash0);
|
||||
uint160 claimId = ClaimIdHash(tx1.GetHash(), 0);
|
||||
@@ -211,13 +210,13 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test)
|
||||
CClaimValue claimVal(claimOutPoint, claimId, amount, height, validHeight);
|
||||
ctc.insertClaimIntoTrie("test", claimVal, true);
|
||||
|
||||
// try getClaimsForName, getEffectiveAmountForClaim, getInfoForName
|
||||
// try getClaimsForName, effectiveAmount, getInfoForName
|
||||
auto res = ctc.getClaimsForName("test");
|
||||
BOOST_CHECK_EQUAL(res.claims.size(), 1);
|
||||
BOOST_CHECK_EQUAL(res.claims[0], claimVal);
|
||||
BOOST_CHECK_EQUAL(res.supports.size(), 0);
|
||||
BOOST_CHECK_EQUAL(res.claimsNsupports.size(), 1);
|
||||
BOOST_CHECK_EQUAL(res.claimsNsupports[0].claim, claimVal);
|
||||
BOOST_CHECK_EQUAL(res.claimsNsupports[0].supports.size(), 0);
|
||||
|
||||
BOOST_CHECK_EQUAL(10, ctc.getEffectiveAmountForClaim("test", claimId));
|
||||
BOOST_CHECK_EQUAL(10, res.claimsNsupports[0].effectiveAmount);
|
||||
|
||||
CClaimValue claim;
|
||||
BOOST_CHECK(ctc.getInfoForName("test", claim));
|
||||
@@ -232,12 +231,12 @@ BOOST_AUTO_TEST_CASE(basic_insertion_info_test)
|
||||
CSupportValue support(supportOutPoint, claimId, supportAmount, height, validHeight);
|
||||
ctc.insertSupportIntoMap("test", support, false);
|
||||
|
||||
res = ctc.getClaimsForName("test");
|
||||
BOOST_CHECK_EQUAL(res.claims.size(), 1);
|
||||
BOOST_CHECK_EQUAL(res.supports.size(), 1);
|
||||
auto res1 = ctc.getClaimsForName("test");
|
||||
BOOST_CHECK_EQUAL(res1.claimsNsupports.size(), 1);
|
||||
BOOST_CHECK_EQUAL(res1.claimsNsupports[0].supports.size(), 1);
|
||||
|
||||
// try getEffectiveAmount
|
||||
BOOST_CHECK_EQUAL(20, ctc.getEffectiveAmountForClaim("test", claimId));
|
||||
BOOST_CHECK_EQUAL(20, res1.claimsNsupports[0].effectiveAmount);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(recursive_prune_test)
|
||||
@@ -298,29 +297,14 @@ BOOST_AUTO_TEST_CASE(iteratetrie_test)
|
||||
ctc.insertClaimIntoTrie("test", claimVal, true);
|
||||
BOOST_CHECK(ctc.flush());
|
||||
|
||||
std::size_t count = 0;
|
||||
for (auto it = pclaimTrie->begin(); it != pclaimTrie->end(); ++it) {
|
||||
++count;
|
||||
if (it.key() == "test") {
|
||||
BOOST_CHECK_EQUAL(it->claims.size(), 1);
|
||||
}
|
||||
}
|
||||
BOOST_CHECK_EQUAL(count, 2);
|
||||
|
||||
count = 0;
|
||||
for (const auto& it: *pclaimTrie) {
|
||||
++count;
|
||||
if (it.first == "test") {
|
||||
const CClaimTrieData& data = it.second;
|
||||
BOOST_CHECK_EQUAL(data.claims.size(), 1);
|
||||
}
|
||||
}
|
||||
BOOST_CHECK_EQUAL(count, 2);
|
||||
|
||||
auto it = pclaimTrie->find("test");
|
||||
BOOST_CHECK(it != pclaimTrie->end());
|
||||
BOOST_CHECK_EQUAL(it->claims.size(), 1);
|
||||
BOOST_CHECK_EQUAL(pclaimTrie->height(), 1);
|
||||
CClaimTrieDataNode node;
|
||||
BOOST_CHECK(pclaimTrie->find("", node));
|
||||
BOOST_CHECK_EQUAL(node.children.size(), 1U);
|
||||
BOOST_CHECK(pclaimTrie->find("test", node));
|
||||
BOOST_CHECK_EQUAL(node.children.size(), 0U);
|
||||
CClaimTrieData data;
|
||||
BOOST_CHECK(pclaimTrie->find("test", data));
|
||||
BOOST_CHECK_EQUAL(data.claims.size(), 1);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(trie_stays_consistent_test)
|
||||
@@ -337,15 +321,15 @@ BOOST_AUTO_TEST_CASE(trie_stays_consistent_test)
|
||||
BOOST_CHECK(cache.insertClaimIntoTrie(name, value, false));
|
||||
|
||||
cache.flush();
|
||||
BOOST_CHECK(cache.checkConsistency());
|
||||
BOOST_CHECK(trie.checkConsistency(cache.getMerkleHash()));
|
||||
|
||||
for (auto& name: names) {
|
||||
CClaimValue temp;
|
||||
BOOST_CHECK(cache.removeClaimFromTrie(name, COutPoint(), temp, false));
|
||||
cache.flush();
|
||||
BOOST_CHECK(cache.checkConsistency());
|
||||
BOOST_CHECK(trie.checkConsistency(cache.getMerkleHash()));
|
||||
}
|
||||
BOOST_CHECK_EQUAL(trie.height(), 0);
|
||||
BOOST_CHECK(trie.empty());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(takeover_workaround_triggers)
|
||||
@@ -394,9 +378,29 @@ BOOST_AUTO_TEST_CASE(takeover_workaround_triggers)
|
||||
|
||||
BOOST_CHECK(cache.incrementBlock(icu, ecu, isu, esu, thu));
|
||||
|
||||
BOOST_CHECK_EQUAL(3, cache.find("aa")->nHeightOfLastTakeover);
|
||||
BOOST_CHECK_EQUAL(3, cache.find("bb")->nHeightOfLastTakeover);
|
||||
BOOST_CHECK_EQUAL(1, cache.find("cc")->nHeightOfLastTakeover);
|
||||
BOOST_CHECK_EQUAL(3, cache.getCache("aa")->nHeightOfLastTakeover);
|
||||
BOOST_CHECK_EQUAL(3, cache.getCache("bb")->nHeightOfLastTakeover);
|
||||
BOOST_CHECK_EQUAL(1, cache.getCache("cc")->nHeightOfLastTakeover);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(verify_basic_serialization)
|
||||
{
|
||||
CClaimValue cv;
|
||||
cv.outPoint = COutPoint(uint256S("123"), 2);
|
||||
cv.nHeight = 3;
|
||||
cv.claimId.SetHex("4567");
|
||||
cv.nEffectiveAmount = 4;
|
||||
cv.nAmount = 5;
|
||||
cv.nValidAtHeight = 6;
|
||||
|
||||
CDataStream ssData(SER_NETWORK, PROTOCOL_VERSION);
|
||||
ssData << cv;
|
||||
|
||||
CClaimValue cv2;
|
||||
ssData >> cv2;
|
||||
|
||||
BOOST_CHECK_EQUAL(cv, cv2);
|
||||
BOOST_CHECK_EQUAL(cv.nEffectiveAmount, cv2.nEffectiveAmount);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
@@ -20,6 +20,8 @@
|
||||
#include <script/sigcache.h>
|
||||
|
||||
#include "claimtrie.h"
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <boost/test/unit_test_parameters.hpp>
|
||||
|
||||
void CConnmanTest::AddNode(CNode& node)
|
||||
{
|
||||
@@ -39,7 +41,6 @@ void CConnmanTest::ClearNodes()
|
||||
uint256 insecure_rand_seed = GetRandHash();
|
||||
FastRandomContext insecure_rand_ctx(insecure_rand_seed);
|
||||
|
||||
extern bool fPrintToConsole;
|
||||
extern void noui_connect();
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, const uint256& num)
|
||||
@@ -90,6 +91,14 @@ std::ostream& operator<<(std::ostream& os, const CSupportValue& support)
|
||||
BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
|
||||
: m_path_root(fs::temp_directory_path() / "test_bitcoin" / strprintf("%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30))))
|
||||
{
|
||||
// for debugging:
|
||||
if (boost::unit_test::runtime_config::get<boost::unit_test::log_level>(boost::unit_test::runtime_config::btrt_log_level)
|
||||
<= boost::unit_test::log_level::log_messages) {
|
||||
g_logger->m_print_to_console = true;
|
||||
g_logger->m_log_time_micros = true;
|
||||
g_logger->EnableCategory(BCLog::ALL);
|
||||
}
|
||||
|
||||
SHA256AutoDetect();
|
||||
RandomInit();
|
||||
ECC_Start();
|
||||
@@ -135,7 +144,7 @@ TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(cha
|
||||
pblocktree.reset(new CBlockTreeDB(1 << 20, true));
|
||||
pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true));
|
||||
pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get()));
|
||||
pclaimTrie = new CClaimTrie(true, false, 1);
|
||||
pclaimTrie = new CClaimTrieHashFork(true, false, 1);
|
||||
if (!LoadGenesisBlock(chainparams)) {
|
||||
throw std::runtime_error("LoadGenesisBlock failed.");
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ struct BasicTestingSetup {
|
||||
ECCVerifyHandle globalVerifyHandle;
|
||||
|
||||
explicit BasicTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
|
||||
~BasicTestingSetup();
|
||||
virtual ~BasicTestingSetup();
|
||||
|
||||
fs::path SetDataDir(const std::string& name);
|
||||
|
||||
@@ -70,7 +70,7 @@ struct TestingSetup: public BasicTestingSetup {
|
||||
std::unique_ptr<PeerLogicValidation> peerLogic;
|
||||
|
||||
explicit TestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
|
||||
~TestingSetup();
|
||||
~TestingSetup() override;
|
||||
};
|
||||
|
||||
class CBlock;
|
||||
@@ -89,7 +89,7 @@ struct TestChain100Setup : public TestingSetup {
|
||||
CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
|
||||
const CScript& scriptPubKey);
|
||||
|
||||
~TestChain100Setup();
|
||||
~TestChain100Setup() override;
|
||||
|
||||
std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
|
||||
CKey coinbaseKey; // private/public key needed to spend coinbase transactions
|
||||
@@ -97,7 +97,7 @@ struct TestChain100Setup : public TestingSetup {
|
||||
|
||||
struct RegTestingSetup: public TestingSetup {
|
||||
RegTestingSetup();
|
||||
~RegTestingSetup();
|
||||
~RegTestingSetup() override;
|
||||
};
|
||||
|
||||
class CTxMemPoolEntry;
|
||||
|
||||
+2
-2
@@ -26,7 +26,7 @@ struct CDiskTxPos;
|
||||
//! No need to periodic flush if at least this much space still available.
|
||||
static constexpr int MAX_BLOCK_COINSDB_USAGE = 10;
|
||||
//! -dbcache default (MiB)
|
||||
static const int64_t nDefaultDbCache = sizeof(void*) > 4 ? 700 : 450;
|
||||
static const int64_t nDefaultDbCache = 500;
|
||||
//! -dbbatchsize default (bytes)
|
||||
static const int64_t nDefaultDbBatchSize = 16 << 20;
|
||||
//! max. -dbcache (MiB)
|
||||
@@ -34,7 +34,7 @@ static const int64_t nMaxDbCache = sizeof(void*) > 4 ? 16384 : 1024;
|
||||
//! min. -dbcache (MiB)
|
||||
static const int64_t nMinDbCache = 4;
|
||||
//! Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
|
||||
static const int64_t nMaxBlockDBCache = 8;
|
||||
static const int64_t nMaxBlockDBCache = 4;
|
||||
//! Max memory allocated to block tree DB specific cache, if -txindex (MiB)
|
||||
// Unlike for the UTXO database, for the txindex scenario the leveldb cache make
|
||||
// a meaningful difference: https://github.com/bitcoin/bitcoin/pull/8273#issuecomment-229601991
|
||||
|
||||
+40
-44
@@ -1351,36 +1351,7 @@ bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsVi
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
|
||||
{
|
||||
// Open history file to append
|
||||
CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
|
||||
if (fileout.IsNull())
|
||||
return error("%s: OpenUndoFile failed", __func__);
|
||||
|
||||
// Write index header
|
||||
unsigned int nSize = GetSerializeSize(fileout, blockundo);
|
||||
fileout << messageStart << nSize;
|
||||
|
||||
// Write undo data
|
||||
long fileOutPos = ftell(fileout.Get());
|
||||
if (fileOutPos < 0)
|
||||
return error("%s: ftell failed", __func__);
|
||||
pos.nPos = (unsigned int)fileOutPos;
|
||||
fileout << blockundo;
|
||||
|
||||
// calculate & write checksum
|
||||
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
|
||||
hasher << hashBlock;
|
||||
hasher << blockundo;
|
||||
fileout << hasher.GetHash();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex)
|
||||
bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex)
|
||||
{
|
||||
CDiskBlockPos pos = pindex->GetUndoPos();
|
||||
if (pos.IsNull()) {
|
||||
@@ -1411,6 +1382,35 @@ static bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex)
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
|
||||
{
|
||||
// Open history file to append
|
||||
CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
|
||||
if (fileout.IsNull())
|
||||
return error("%s: OpenUndoFile failed", __func__);
|
||||
|
||||
// Write index header
|
||||
unsigned int nSize = GetSerializeSize(fileout, blockundo);
|
||||
fileout << messageStart << nSize;
|
||||
|
||||
// Write undo data
|
||||
long fileOutPos = ftell(fileout.Get());
|
||||
if (fileOutPos < 0)
|
||||
return error("%s: ftell failed", __func__);
|
||||
pos.nPos = (unsigned int)fileOutPos;
|
||||
fileout << blockundo;
|
||||
|
||||
// calculate & write checksum
|
||||
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
|
||||
hasher << hashBlock;
|
||||
hasher << blockundo;
|
||||
fileout << hasher.GetHash();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Abort with a message */
|
||||
static bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
|
||||
{
|
||||
@@ -1562,20 +1562,16 @@ DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockI
|
||||
assert(trieCache.finalizeDecrement(blockUndo.takeoverHeightUndo));
|
||||
auto merkleHash = trieCache.getMerkleHash();
|
||||
if (merkleHash != pindex->pprev->hashClaimTrie) {
|
||||
if (trieCache.checkConsistency()) {
|
||||
for (auto cit = trieCache.begin(); cit != trieCache.end(); ++cit) {
|
||||
if (cit->claims.size() && cit->nHeightOfLastTakeover <= 0)
|
||||
LogPrintf("Invalid takeover height discovered in cache for %s\n", cit.key());
|
||||
if (cit->hash.IsNull())
|
||||
LogPrintf("Invalid hash discovered in cache for %s\n", cit.key());
|
||||
}
|
||||
for (auto cit = trieCache.begin(); cit != trieCache.end(); ++cit) {
|
||||
if (cit->claims.size() && cit->nHeightOfLastTakeover <= 0)
|
||||
LogPrintf("Invalid takeover height discovered in cache for %s\n", cit.key());
|
||||
if (cit->hash.IsNull())
|
||||
LogPrintf("Invalid hash discovered in cache for %s\n", cit.key());
|
||||
}
|
||||
LogPrintf("Hash comparison failure at block %d\n", pindex->nHeight);
|
||||
assert(merkleHash == pindex->pprev->hashClaimTrie);
|
||||
}
|
||||
|
||||
trieCache.expirationForkActive(pindex->nHeight, false);
|
||||
|
||||
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
|
||||
}
|
||||
|
||||
@@ -1933,8 +1929,6 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
|
||||
// Get the script flags for this block
|
||||
unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
|
||||
|
||||
trieCache.expirationForkActive(pindex->nHeight, true);
|
||||
|
||||
int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
|
||||
LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
|
||||
|
||||
@@ -1942,6 +1936,8 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
|
||||
|
||||
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
|
||||
|
||||
trieCache.initializeIncrement();
|
||||
|
||||
std::vector<int> prevheights;
|
||||
CAmount nFees = 0;
|
||||
int nInputs = 0;
|
||||
@@ -2048,7 +2044,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
|
||||
|
||||
if (trieCache.getMerkleHash() != block.hashClaimTrie)
|
||||
{
|
||||
if (!trieCache.empty() && trieCache.checkConsistency())
|
||||
if (!trieCache.empty()) // we could run checkConsistency here, but it would take a while
|
||||
trieCache.dumpToLog(trieCache.begin());
|
||||
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(),
|
||||
@@ -2296,13 +2292,13 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar
|
||||
auto oldBlock = pindexNew->nTime + MAX_FUTURE_BLOCK_TIME < currentTime;
|
||||
if (!warningMessages.empty() || !oldBlock || lastBlockPrintTime < currentTime - 15 || LogAcceptCategory(BCLog::CLAIMS)) {
|
||||
lastBlockPrintTime = currentTime;
|
||||
LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g txb=%lu tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo) trie nodes=%zu%s",
|
||||
LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g txb=%lu tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s",
|
||||
__func__, pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
|
||||
log(pindexNew->nChainWork.getdouble()) / log(2.0), (unsigned long) pindexNew->nTx,
|
||||
(unsigned long) pindexNew->nChainTx, FormatISO8601DateTime(pindexNew->GetBlockTime()),
|
||||
GuessVerificationProgress(chainParams.TxData(), pindexNew),
|
||||
pcoinsTip->DynamicMemoryUsage() * (1.0 / (1U << 20U)), pcoinsTip->GetCacheSize(),
|
||||
pclaimTrie->height(), oldBlock ? " (synchronizing)" : "");
|
||||
oldBlock ? " (synchronizing)" : "");
|
||||
if (!warningMessages.empty())
|
||||
LogPrintf(" warning='%s'", warningMessages); /* Continued */
|
||||
LogPrintf("\n");
|
||||
|
||||
@@ -203,6 +203,11 @@ public:
|
||||
|
||||
ThresholdState VersionBitsState(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, VersionBitsCache& cache)
|
||||
{
|
||||
// Check if we've past a hardfork state for segwit.
|
||||
if ((pos == Consensus::DEPLOYMENT_SEGWIT) && (pindexPrev != nullptr) &&
|
||||
(pindexPrev->nHeight + 1 >= params.nWitnessForkHeight))
|
||||
return ThresholdState::ACTIVE;
|
||||
|
||||
return VersionBitsConditionChecker(pos).GetStateFor(pindexPrev, params, cache.caches[pos]);
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -154,6 +154,7 @@ BerkeleyEnvironment::BerkeleyEnvironment(const fs::path& dir_path) : strPath(dir
|
||||
|
||||
BerkeleyEnvironment::~BerkeleyEnvironment()
|
||||
{
|
||||
LOCK(cs_db);
|
||||
g_dbenvs.erase(strPath);
|
||||
Close();
|
||||
}
|
||||
@@ -558,6 +559,7 @@ BerkeleyBatch::BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode, bo
|
||||
|
||||
void BerkeleyBatch::Flush()
|
||||
{
|
||||
LOCK(cs_db);
|
||||
if (activeTxn)
|
||||
return;
|
||||
|
||||
@@ -566,7 +568,9 @@ void BerkeleyBatch::Flush()
|
||||
if (fReadOnly)
|
||||
nMinutes = 1;
|
||||
|
||||
env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
|
||||
if (env && env->dbenv) { // env is nullptr for dummy databases (i.e. in tests). Don't actually flush if env is nullptr so we don't segfault
|
||||
env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void BerkeleyDatabase::IncrementUpdateCounter()
|
||||
|
||||
@@ -218,7 +218,7 @@ UniValue abortrescan(const JSONRPCRequest& request)
|
||||
static void ImportAddress(CWallet*, const CTxDestination& dest, const std::string& strLabel);
|
||||
static void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
|
||||
{
|
||||
if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
|
||||
if (!isRedeemScript && (::IsMine(*pwallet, script) & ISMINE_SPENDABLE)) {
|
||||
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
|
||||
}
|
||||
|
||||
@@ -902,7 +902,7 @@ static UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, con
|
||||
|
||||
CScript redeemDestination = GetScriptForDestination(redeem_id);
|
||||
|
||||
if (::IsMine(*pwallet, redeemDestination) == ISMINE_SPENDABLE) {
|
||||
if (::IsMine(*pwallet, redeemDestination) & ISMINE_SPENDABLE) {
|
||||
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
|
||||
}
|
||||
|
||||
@@ -986,7 +986,7 @@ static UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, con
|
||||
|
||||
CScript pubKeyScript = GetScriptForDestination(pubkey_dest);
|
||||
|
||||
if (::IsMine(*pwallet, pubKeyScript) == ISMINE_SPENDABLE) {
|
||||
if (::IsMine(*pwallet, pubKeyScript) & ISMINE_SPENDABLE) {
|
||||
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
|
||||
}
|
||||
|
||||
@@ -1005,7 +1005,7 @@ static UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, con
|
||||
// TODO Is this necessary?
|
||||
CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey);
|
||||
|
||||
if (::IsMine(*pwallet, scriptRawPubKey) == ISMINE_SPENDABLE) {
|
||||
if (::IsMine(*pwallet, scriptRawPubKey) & ISMINE_SPENDABLE) {
|
||||
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
|
||||
}
|
||||
|
||||
@@ -1071,7 +1071,7 @@ static UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, con
|
||||
|
||||
// Import scriptPubKey only.
|
||||
if (pubKeys.size() == 0 && keys.size() == 0) {
|
||||
if (::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
|
||||
if (::IsMine(*pwallet, script) & ISMINE_SPENDABLE) {
|
||||
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
|
||||
}
|
||||
|
||||
|
||||
+179
-130
@@ -480,7 +480,7 @@ static CTransactionRef SendMoney(CWallet * const pwallet, const CTxDestination &
|
||||
}
|
||||
|
||||
// Parse Bitcoin address
|
||||
CScript scriptPubKey = prefix + GetScriptForDestination(address);
|
||||
const CScript scriptPubKey = prefix + GetScriptForDestination(address);
|
||||
|
||||
// Create and send the transaction
|
||||
CReserveKey reservekey(pwallet);
|
||||
@@ -513,16 +513,16 @@ UniValue claimname(const JSONRPCRequest& request)
|
||||
return NullUniValue;
|
||||
}
|
||||
|
||||
if (request.fHelp || request.params.size() != 3)
|
||||
if (request.fHelp || (request.params.size() != 3 && request.params.size() != 4))
|
||||
throw std::runtime_error(
|
||||
"claimname \"name\" \"value\" amount\n"
|
||||
"\nCreate a transaction which issues a claim assigning a value to a name. The claim will be authoritative if the transaction amount is greater than the transaction amount of all other unspent transactions which issue a claim over the same name, and it will remain au\
|
||||
thoritative as long as it remains unspent and there are no other greater unspent transactions issuing a claim over the same name. The amount is a real and is rounded to the nearest 0.00000001\n"
|
||||
+ HelpRequiringPassphrase(pwallet) +
|
||||
"\nArguments:\n"
|
||||
"1. \"name\" (string, required) The name to be assigned the value.\n"
|
||||
"2. \"value\" (string, required) The value to assign to the name encoded in hexadecimal.\n"
|
||||
"3. \"amount\" (numeric, required) The amount in LBRYcrd to send. eg 0.1\n"
|
||||
"1. \"name\" (string, required) The name to be assigned the value.\n"
|
||||
"2. \"value\" (string, required) The value to assign to the name encoded in hexadecimal.\n"
|
||||
"3. \"amount\" (numeric, required) The amount in LBRYcrd to send. eg 0.1\n"
|
||||
"\nResult:\n"
|
||||
"\"transactionid\" (string) The transaction id.\n");
|
||||
auto sName = request.params[0].get_str();
|
||||
@@ -545,9 +545,13 @@ thoritative as long as it remains unspent and there are no other greater unspent
|
||||
if (!pwallet->GetKeyFromPool(newKey))
|
||||
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
|
||||
|
||||
OutputType output_type = pwallet->m_default_address_type;
|
||||
pwallet->LearnRelatedScripts(newKey, output_type);
|
||||
CTxDestination dest = GetDestinationForKey(newKey, output_type);
|
||||
|
||||
CCoinControl cc;
|
||||
cc.m_change_type = DEFAULT_ADDRESS_TYPE;
|
||||
auto tx = SendMoney(pwallet, CTxDestination(newKey.GetID()), nAmount, false, cc, {}, {}, claimScript);
|
||||
cc.m_change_type = pwallet->m_default_change_type;
|
||||
auto tx = SendMoney(pwallet, dest, nAmount, false, cc, {}, {}, claimScript);
|
||||
return tx->GetHash().GetHex();
|
||||
}
|
||||
|
||||
@@ -560,15 +564,15 @@ UniValue updateclaim(const JSONRPCRequest& request)
|
||||
return NullUniValue;
|
||||
}
|
||||
|
||||
if (request.fHelp || request.params.size() != 3)
|
||||
if (request.fHelp || (request.params.size() != 3 && request.params.size() != 4))
|
||||
throw std::runtime_error(
|
||||
"updateclaim \"txid\" \"value\" amount\n"
|
||||
"Create a transaction which issues a claim assigning a value to a name, spending the previous txout which issued a claim over the same name and therefore superseding that claim. The claim will be authoritative if the transaction amount is greater than the transaction amount of all other unspent transactions which issue a claim over the same name, and it will remain authoritative as long as it remains unspent and there are no greater unspent transactions issuing a claim over the same name.\n"
|
||||
+ HelpRequiringPassphrase(pwallet) + "\n"
|
||||
"Arguments:\n"
|
||||
"1. \"txid\" (string, required) The transaction containing the unspent txout which should be spent.\n"
|
||||
"2. \"value\" (string, required) The value to assign to the name encoded in hexadecimal.\n"
|
||||
"3. \"amount\" (numeric, required) The amount in LBRYcrd to use to bid for the name. eg 0.1\n"
|
||||
"1. \"txid\" (string, required) The transaction containing the unspent txout which should be spent.\n"
|
||||
"2. \"value\" (string, required) The value to assign to the name encoded in hexadecimal.\n"
|
||||
"3. \"amount\" (numeric, required) The amount in LBRYcrd to use to bid for the name. eg 0.1\n"
|
||||
"\nResult:\n"
|
||||
"\"transactionid\" (string) The new transaction id.\n");
|
||||
|
||||
@@ -621,11 +625,15 @@ UniValue updateclaim(const JSONRPCRequest& request)
|
||||
if (!pwallet->GetKeyFromPool(newKey))
|
||||
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
|
||||
|
||||
OutputType output_type = pwallet->m_default_address_type;
|
||||
pwallet->LearnRelatedScripts(newKey, output_type);
|
||||
CTxDestination dest = GetDestinationForKey(newKey, output_type);
|
||||
|
||||
CCoinControl cc;
|
||||
cc.m_change_type = DEFAULT_ADDRESS_TYPE;
|
||||
cc.m_change_type = pwallet->m_default_change_type;
|
||||
cc.Select(COutPoint(wtx.tx->GetHash(), i));
|
||||
cc.fAllowOtherInputs = true; // the doc comment on this parameter says it should be false; experience says otherwise
|
||||
wtxNew = SendMoney(pwallet, CTxDestination(newKey.GetID()), nAmount, false, cc, {}, {}, updateScript);
|
||||
cc.fAllowOtherInputs = true; // when selecting a coin, that's the only one used without this flag (and we need to cover the fee)
|
||||
wtxNew = SendMoney(pwallet, dest, nAmount, false, cc, {}, {}, updateScript);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -658,8 +666,7 @@ UniValue abandonclaim(const JSONRPCRequest& request)
|
||||
uint256 hash;
|
||||
hash.SetHex(request.params[0].get_str());
|
||||
|
||||
CKeyID address;
|
||||
address.SetHex(request.params[1].get_str());
|
||||
CTxDestination address = DecodeDestination(request.params[1].get_str());
|
||||
|
||||
pwallet->BlockUntilSyncedToCurrentChain();
|
||||
LOCK2(cs_main, pwallet->cs_wallet);
|
||||
@@ -677,7 +684,7 @@ UniValue abandonclaim(const JSONRPCRequest& request)
|
||||
{
|
||||
EnsureWalletIsUnlocked(pwallet);
|
||||
CCoinControl cc;
|
||||
cc.m_change_type = DEFAULT_ADDRESS_TYPE;
|
||||
cc.m_change_type = pwallet->m_default_change_type;
|
||||
cc.Select(COutPoint(wtx.tx->GetHash(), i));
|
||||
wtxNew = SendMoney(pwallet, address, wtx.tx->vout[i].nValue, true, cc, {}, {});
|
||||
break;
|
||||
@@ -700,92 +707,93 @@ void ListNameClaims(const CWalletTx& wtx, CWallet* const pwallet, const std::str
|
||||
std::list<COutputEntry> listSent;
|
||||
std::list<COutputEntry> listReceived;
|
||||
|
||||
isminefilter filter = isminetype::ISMINE_CLAIM;
|
||||
if (include_supports)
|
||||
filter |= isminetype::ISMINE_SUPPORT;
|
||||
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
|
||||
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, isminetype::ISMINE_ALL);
|
||||
|
||||
bool fAllAccounts = (strAccount == std::string("*"));
|
||||
if (!fAllAccounts && wtx.strFromAccount != strAccount)
|
||||
return;
|
||||
|
||||
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
|
||||
for (const auto& s: listSent)
|
||||
{
|
||||
for (const COutputEntry& s: listSent)
|
||||
{
|
||||
if (!list_spent && pwallet->IsSpent(wtx.GetHash(), s.vout))
|
||||
continue;
|
||||
if (!list_spent && pwallet->IsSpent(wtx.GetHash(), s.vout))
|
||||
continue;
|
||||
|
||||
UniValue entry(UniValue::VOBJ);
|
||||
const CScript& scriptPubKey = wtx.tx->vout[s.vout].scriptPubKey;
|
||||
int op;
|
||||
std::vector<std::vector<unsigned char>> vvchParams;
|
||||
if (!DecodeClaimScript(scriptPubKey, op, vvchParams)) {
|
||||
continue;
|
||||
}
|
||||
std::string sName (vvchParams[0].begin(), vvchParams[0].end());
|
||||
entry.pushKV("name", escapeNonUtf8(sName));
|
||||
if (op == OP_CLAIM_NAME)
|
||||
{
|
||||
uint160 claimId = ClaimIdHash(wtx.GetHash(), s.vout);
|
||||
entry.pushKV("claimtype", "CLAIM");
|
||||
entry.pushKV("claimId", claimId.GetHex());
|
||||
entry.pushKV("value", HexStr(vvchParams[1].begin(), vvchParams[1].end()));
|
||||
}
|
||||
else if (op == OP_UPDATE_CLAIM)
|
||||
{
|
||||
uint160 claimId(vvchParams[1]);
|
||||
entry.pushKV("claimtype", "CLAIM");
|
||||
entry.pushKV("claimId", claimId.GetHex());
|
||||
UniValue entry(UniValue::VOBJ);
|
||||
const CScript& scriptPubKey = wtx.tx->vout[s.vout].scriptPubKey;
|
||||
int op;
|
||||
std::vector<std::vector<unsigned char>> vvchParams;
|
||||
if (!DecodeClaimScript(scriptPubKey, op, vvchParams)) {
|
||||
continue;
|
||||
}
|
||||
if (!include_supports && op == OP_SUPPORT_CLAIM)
|
||||
continue;
|
||||
|
||||
std::string sName (vvchParams[0].begin(), vvchParams[0].end());
|
||||
entry.pushKV("name", escapeNonUtf8(sName));
|
||||
if (op == OP_CLAIM_NAME)
|
||||
{
|
||||
uint160 claimId = ClaimIdHash(wtx.GetHash(), s.vout);
|
||||
entry.pushKV("claimtype", "CLAIM");
|
||||
entry.pushKV("claimId", claimId.GetHex());
|
||||
entry.pushKV("value", HexStr(vvchParams[1].begin(), vvchParams[1].end()));
|
||||
}
|
||||
else if (op == OP_UPDATE_CLAIM)
|
||||
{
|
||||
uint160 claimId(vvchParams[1]);
|
||||
entry.pushKV("claimtype", "CLAIM");
|
||||
entry.pushKV("claimId", claimId.GetHex());
|
||||
entry.pushKV("value", HexStr(vvchParams[2].begin(), vvchParams[2].end()));
|
||||
}
|
||||
else if (op == OP_SUPPORT_CLAIM)
|
||||
{
|
||||
uint160 claimId(vvchParams[1]);
|
||||
entry.pushKV("claimtype", "SUPPORT");
|
||||
entry.pushKV("supported_claimid", claimId.GetHex());
|
||||
if (vvchParams.size() > 2) {
|
||||
entry.pushKV("value", HexStr(vvchParams[2].begin(), vvchParams[2].end()));
|
||||
}
|
||||
else if (op == OP_SUPPORT_CLAIM)
|
||||
{
|
||||
uint160 claimId(vvchParams[1]);
|
||||
entry.pushKV("claimtype", "SUPPORT");
|
||||
entry.pushKV("supported_claimid", claimId.GetHex());
|
||||
if (vvchParams.size() > 2) {
|
||||
entry.pushKV("value", HexStr(vvchParams[2].begin(), vvchParams[2].end()));
|
||||
}
|
||||
}
|
||||
entry.pushKV("txid", wtx.GetHash().ToString());
|
||||
entry.pushKV("account", strSentAccount);
|
||||
MaybePushAddress(entry, s.destination);
|
||||
entry.pushKV("amount", ValueFromAmount(s.amount));
|
||||
entry.pushKV("vout", s.vout);
|
||||
entry.pushKV("fee", ValueFromAmount(nFee));
|
||||
|
||||
CClaimTrieCache trieCache(pclaimTrie);
|
||||
|
||||
auto it = mapBlockIndex.find(wtx.hashBlock);
|
||||
if (it != mapBlockIndex.end())
|
||||
{
|
||||
CBlockIndex* pindex = it->second;
|
||||
if (pindex)
|
||||
{
|
||||
entry.pushKV("height", pindex->nHeight);
|
||||
entry.pushKV("expiration height", pindex->nHeight + trieCache.expirationTime());
|
||||
if (pindex->nHeight + trieCache.expirationTime() > chainActive.Height())
|
||||
{
|
||||
entry.pushKV("expired", false);
|
||||
entry.pushKV("blocks to expiration", pindex->nHeight + trieCache.expirationTime() - chainActive.Height());
|
||||
}
|
||||
else
|
||||
{
|
||||
entry.pushKV("expired", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
entry.pushKV("confirmations", wtx.GetDepthInMainChain());
|
||||
entry.pushKV("is spent", pwallet->IsSpent(wtx.GetHash(), s.vout));
|
||||
if (op == OP_CLAIM_NAME)
|
||||
{
|
||||
entry.pushKV("is in name trie", trieCache.haveClaim(sName, COutPoint(wtx.GetHash(), s.vout)));
|
||||
}
|
||||
else if (op == OP_SUPPORT_CLAIM)
|
||||
{
|
||||
entry.pushKV("is in support map", trieCache.haveSupport(sName, COutPoint(wtx.GetHash(), s.vout)));
|
||||
}
|
||||
ret.push_back(entry);
|
||||
}
|
||||
else
|
||||
throw JSONRPCError(RPC_INTERNAL_ERROR, "Undefined claim operator.");
|
||||
entry.pushKV("txid", wtx.GetHash().ToString());
|
||||
entry.pushKV("account", strSentAccount);
|
||||
MaybePushAddress(entry, s.destination);
|
||||
entry.pushKV("amount", ValueFromAmount(s.amount));
|
||||
entry.pushKV("vout", s.vout);
|
||||
entry.pushKV("fee", ValueFromAmount(nFee));
|
||||
|
||||
CClaimTrieCache trieCache(pclaimTrie);
|
||||
|
||||
auto it = mapBlockIndex.find(wtx.hashBlock);
|
||||
if (it != mapBlockIndex.end())
|
||||
{
|
||||
CBlockIndex* pindex = it->second;
|
||||
if (pindex)
|
||||
{
|
||||
entry.pushKV("height", pindex->nHeight);
|
||||
entry.pushKV("expiration height", pindex->nHeight + trieCache.expirationTime());
|
||||
if (pindex->nHeight + trieCache.expirationTime() > chainActive.Height())
|
||||
{
|
||||
entry.pushKV("expired", false);
|
||||
entry.pushKV("blocks to expiration", pindex->nHeight + trieCache.expirationTime() - chainActive.Height());
|
||||
}
|
||||
else
|
||||
{
|
||||
entry.pushKV("expired", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
entry.pushKV("confirmations", wtx.GetDepthInMainChain());
|
||||
entry.pushKV("is spent", pwallet->IsSpent(wtx.GetHash(), s.vout));
|
||||
if (op == OP_CLAIM_NAME)
|
||||
{
|
||||
entry.pushKV("is in name trie", trieCache.haveClaim(sName, COutPoint(wtx.GetHash(), s.vout)));
|
||||
}
|
||||
else if (op == OP_SUPPORT_CLAIM)
|
||||
{
|
||||
entry.pushKV("is in support map", trieCache.haveSupport(sName, COutPoint(wtx.GetHash(), s.vout)));
|
||||
}
|
||||
ret.push_back(entry);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -804,8 +812,7 @@ UniValue listnameclaims(const JSONRPCRequest& request)
|
||||
"Return a list of all transactions claiming names.\n"
|
||||
"\nArguments\n"
|
||||
"1. includesupports (bool, optional) Whether to also include claim supports. Default is true.\n"
|
||||
"2. activeonly (bool, optional, not implemented) Whether to only include transactions which are still active, i.e. have n\
|
||||
ot been spent. Default is false.\n"
|
||||
"2. activeonly (bool, optional) Whether to only include transactions which are still active, i.e. have not been spent. Default is true.\n"
|
||||
"3. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
|
||||
"\nResult:\n"
|
||||
"[\n"
|
||||
@@ -835,7 +842,7 @@ ot been spent. Default is false.\n"
|
||||
std::string strAccount = "*";
|
||||
|
||||
auto include_supports = request.params.size() < 1 || request.params[0].get_bool();
|
||||
bool fListSpent = request.params.size() > 1 && request.params[1].get_bool();
|
||||
bool fListSpent = request.params.size() > 1 && !request.params[1].get_bool();
|
||||
|
||||
// Minimum confirmations
|
||||
int nMinDepth = 1;
|
||||
@@ -873,7 +880,7 @@ UniValue supportclaim(const JSONRPCRequest& request)
|
||||
return NullUniValue;
|
||||
}
|
||||
|
||||
if (request.fHelp || (request.params.size() != 3 && request.params.size() != 4))
|
||||
if (request.fHelp || request.params.size() < 1 || request.params.size() > 5)
|
||||
throw std::runtime_error(
|
||||
"supportclaim \"name\" \"claimid\" \"amount\" \"value\"\n"
|
||||
"Increase the value of a claim. Whichever claim has the greatest value, including all support values, will be the authoritative claim, according to the rest of the rules. The name is the name which is claimed by the claim that will be supported, the txid is the txid\
|
||||
@@ -881,52 +888,93 @@ UniValue supportclaim(const JSONRPCRequest& request)
|
||||
. Otherwise, it will go into effect after 100 blocks. The support will be in effect until it is spent, and will lose its effect when the claim is spent or expires. The amount is a real and is rounded to the nearest .00000001\n"
|
||||
+ HelpRequiringPassphrase(pwallet) +
|
||||
"\nArguments:\n"
|
||||
"1. \"name\" (string, required) The name claimed by the claim to support.\n"
|
||||
"2. \"claimid\" (string, required) The claimid of the claim to support. This can be obtained by TODO PUT IN PLACE THAT SHOWS THIS.\n"
|
||||
"3. \"amount\" (numeric, required) The amount in LBC to use to support the claim.\n"
|
||||
"4. \"value\" (string, optional) The metadata of the support encoded in hexadecimal.\n"
|
||||
"\nResult:\n"
|
||||
"\"transactionid\" (string) The transaction id of the support.\n");
|
||||
"1. \"name\" (string, required) The name claimed by the claim to support.\n"
|
||||
"2. \"claimid\" (string, optional) The claimid or partialid of the claim to support.\n"
|
||||
"3. \"amount\" (numeric, optional) The amount in LBC to use to support the claim.\n"
|
||||
"4. \"value\" (string, optional) The metadata of the support encoded in hexadecimal.\n"
|
||||
"5. \"isTip\" (boolean, optional, defaults to false) spendable by owning claim's address when true.\n"
|
||||
"\nResult: [\n"
|
||||
"\"txId\" (string) The transaction id of the support.\n"
|
||||
"\"address\" (string) The destination address of the claim.\n"
|
||||
"\n]");
|
||||
|
||||
auto sName = request.params[0].get_str();
|
||||
auto sClaimId = request.params[1].get_str();
|
||||
std::string sClaimId;
|
||||
if (request.params.size() > 1)
|
||||
sClaimId = request.params[1].get_str();
|
||||
|
||||
const size_t claimLength = 40;
|
||||
|
||||
if (!IsHex(sClaimId))
|
||||
if (!IsHexNumber(sClaimId))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "claimid must be a 20-character hexadecimal string (not '" + sClaimId + "')");
|
||||
if (sClaimId.length() != claimLength)
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("claimid must be of length %d", claimLength));
|
||||
|
||||
uint160 claimId;
|
||||
claimId.SetHex(sClaimId);
|
||||
std::vector<unsigned char> vchName (sName.begin(), sName.end());
|
||||
std::vector<unsigned char> vchClaimId (claimId.begin(), claimId.end());
|
||||
CAmount nAmount = AmountFromValue(request.params[2]);
|
||||
if (sClaimId.length() > claimLength)
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("claimid must be maximum of length %d", claimLength));
|
||||
|
||||
pwallet->BlockUntilSyncedToCurrentChain();
|
||||
LOCK2(cs_main, pwallet->cs_wallet);
|
||||
EnsureWalletIsUnlocked(pwallet);
|
||||
|
||||
CClaimTrieCache trieCache(pclaimTrie);
|
||||
auto csToName = trieCache.getClaimsForName(sName);
|
||||
if (csToName.claimsNsupports.empty())
|
||||
return NullUniValue;
|
||||
auto& claimNsupports = !sClaimId.empty() ? csToName.find(sClaimId) : csToName.claimsNsupports[0];
|
||||
if (claimNsupports.IsNull())
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to find a claimid that starts with %s", sClaimId));
|
||||
auto& claimId = claimNsupports.claim.claimId;
|
||||
|
||||
std::vector<unsigned char> vchName (sName.begin(), sName.end());
|
||||
std::vector<unsigned char> vchClaimId (claimId.begin(), claimId.end());
|
||||
CAmount nAmount = AmountFromValue(request.params.size() > 2 ? request.params[2] : "0.00000001");
|
||||
|
||||
CScript supportScript = CScript() << OP_SUPPORT_CLAIM << vchName << vchClaimId;
|
||||
auto lastOp = OP_DROP;
|
||||
if (request.params.size() > 3) {
|
||||
auto hex = request.params[3].get_str();
|
||||
if (!IsHex(hex))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "value/metadata must be of hexadecimal data");
|
||||
supportScript = supportScript << ParseHex(hex);
|
||||
lastOp = OP_2DROP;
|
||||
if (!hex.empty()) {
|
||||
if (!IsHex(hex))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "value/metadata must be of hexadecimal data");
|
||||
if (!IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus()))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "value/metadata on supports is not enabled yet");
|
||||
supportScript = supportScript << ParseHex(hex);
|
||||
lastOp = OP_2DROP;
|
||||
}
|
||||
}
|
||||
|
||||
supportScript = supportScript << OP_2DROP << lastOp;
|
||||
|
||||
CPubKey newKey;
|
||||
if (!pwallet->GetKeyFromPool(newKey))
|
||||
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
|
||||
auto isTip = false;
|
||||
if (request.params.size() > 4)
|
||||
isTip = request.params[4].get_bool();
|
||||
|
||||
CTxDestination dest;
|
||||
if (isTip) {
|
||||
CTransactionRef ref;
|
||||
uint256 block;
|
||||
if (!GetTransaction(claimNsupports.claim.outPoint.hash, ref, Params().GetConsensus(), block, true))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Unable to locate the TX with the claim's output.");
|
||||
if (!ExtractDestination(ref->vout[claimNsupports.claim.outPoint.n].scriptPubKey, dest))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Unable to extract the destination from the chosen claim.");
|
||||
}
|
||||
else {
|
||||
CPubKey newKey;
|
||||
if (!pwallet->GetKeyFromPool(newKey))
|
||||
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
|
||||
|
||||
OutputType output_type = pwallet->m_default_address_type;
|
||||
pwallet->LearnRelatedScripts(newKey, output_type);
|
||||
dest = GetDestinationForKey(newKey, output_type);
|
||||
}
|
||||
|
||||
CCoinControl cc;
|
||||
cc.m_change_type = DEFAULT_ADDRESS_TYPE;
|
||||
auto tx = SendMoney(pwallet, CTxDestination(newKey.GetID()), nAmount, false, cc, {}, {}, supportScript);
|
||||
return tx->GetHash().GetHex();
|
||||
cc.m_change_type = pwallet->m_default_change_type;
|
||||
auto tx = SendMoney(pwallet, dest, nAmount, false, cc, {}, {}, supportScript);
|
||||
|
||||
UniValue result(UniValue::VOBJ);
|
||||
result.pushKV("txId", tx->GetHash().GetHex());
|
||||
result.pushKV("address", EncodeDestination(dest));
|
||||
return result;
|
||||
}
|
||||
|
||||
UniValue abandonsupport(const JSONRPCRequest& request)
|
||||
@@ -952,8 +1000,7 @@ UniValue abandonsupport(const JSONRPCRequest& request)
|
||||
uint256 hash;
|
||||
hash.SetHex(request.params[0].get_str());
|
||||
|
||||
CKeyID address;
|
||||
address.SetHex(request.params[1].get_str());
|
||||
CTxDestination address = DecodeDestination(request.params[1].get_str());
|
||||
|
||||
pwallet->BlockUntilSyncedToCurrentChain();
|
||||
LOCK2(cs_main, pwallet->cs_wallet);
|
||||
@@ -971,7 +1018,7 @@ UniValue abandonsupport(const JSONRPCRequest& request)
|
||||
{
|
||||
EnsureWalletIsUnlocked(pwallet);
|
||||
CCoinControl cc;
|
||||
cc.m_change_type = DEFAULT_ADDRESS_TYPE;
|
||||
cc.m_change_type = pwallet->m_default_change_type;
|
||||
cc.Select(COutPoint(wtx.tx->GetHash(), i));
|
||||
wtxNew = SendMoney(pwallet, address, wtx.tx->vout[i].nValue, true, cc, {}, {});
|
||||
break;
|
||||
@@ -4688,6 +4735,8 @@ UniValue getaddressinfo(const JSONRPCRequest& request)
|
||||
isminetype mine = IsMine(*pwallet, dest);
|
||||
ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE));
|
||||
ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY));
|
||||
ret.pushKV("isclaim", bool(mine & ISMINE_CLAIM));
|
||||
ret.pushKV("issupport", bool(mine & ISMINE_SUPPORT));
|
||||
UniValue detail = DescribeWalletAddress(pwallet, dest);
|
||||
ret.pushKVs(detail);
|
||||
if (pwallet->mapAddressBook.count(dest)) {
|
||||
@@ -5311,11 +5360,11 @@ static const CRPCCommand commands[] =
|
||||
|
||||
{ "generating", "generate", &generate, {"nblocks","maxtries"} },
|
||||
|
||||
{ "Claimtrie", "claimname", &claimname, {"name","value","amount"} },
|
||||
{ "Claimtrie", "updateclaim", &updateclaim, {"txid","value","amount"} },
|
||||
{ "Claimtrie", "claimname", &claimname, {"name","value","amount","address_type"} },
|
||||
{ "Claimtrie", "updateclaim", &updateclaim, {"txid","value","amount","address_type"} },
|
||||
{ "Claimtrie", "abandonclaim", &abandonclaim, {"txid","address"} },
|
||||
{ "Claimtrie", "listnameclaims", &listnameclaims, {"includesuppports","activeonly","minconf"} },
|
||||
{ "Claimtrie", "supportclaim", &supportclaim, {"name","claimid","amount","value"} },
|
||||
{ "Claimtrie", "supportclaim", &supportclaim, {"name","claimid","amount","value","address_type"} },
|
||||
{ "Claimtrie", "abandonsupport", &abandonsupport, {"txid","address"} },
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#include <wallet/wallet.h>
|
||||
|
||||
#include <consensus/validation.h>
|
||||
#include <core_io.h>
|
||||
#include <key_io.h>
|
||||
#include <rpc/server.h>
|
||||
#include <test/test_bitcoin.h>
|
||||
#include <validation.h>
|
||||
@@ -28,11 +30,11 @@ struct CatchWalletTestSetup: public TestingSetup {
|
||||
UniValue results = rpc_method(req);
|
||||
BOOST_CHECK_EQUAL(results["name"].get_str(), "tester_wallet");
|
||||
}
|
||||
~CatchWalletTestSetup() {
|
||||
~CatchWalletTestSetup() override {
|
||||
rpcfn_type rpc_method = tableRPC["unloadwallet"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back("tester_wallet");
|
||||
rpc_method(req);
|
||||
}
|
||||
};
|
||||
@@ -42,6 +44,7 @@ BOOST_FIXTURE_TEST_SUITE(claim_rpc_tests, CatchWalletTestSetup)
|
||||
double AvailableBalance() {
|
||||
rpcfn_type rpc_method = tableRPC["getbalance"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
UniValue results = rpc_method(req);
|
||||
return results.get_real();
|
||||
@@ -51,6 +54,7 @@ uint256 ClaimAName(const std::string& name, const std::string& data, const std::
|
||||
// pass a txid as name for update
|
||||
rpcfn_type rpc_method = tableRPC[isUpdate ? "updateclaim" : "claimname"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(name);
|
||||
req.params.push_back(data);
|
||||
@@ -67,13 +71,14 @@ uint256 SupportAName(const std::string& name, const std::string& claimId, const
|
||||
// pass a txid as name for update
|
||||
rpcfn_type rpc_method = tableRPC["supportclaim"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(name);
|
||||
req.params.push_back(claimId);
|
||||
req.params.push_back(price);
|
||||
|
||||
UniValue results = rpc_method(req);
|
||||
auto txid = results.get_str();
|
||||
auto txid = results["txId"].get_str();
|
||||
uint256 ret;
|
||||
ret.SetHex(txid);
|
||||
return ret;
|
||||
@@ -82,6 +87,7 @@ uint256 SupportAName(const std::string& name, const std::string& claimId, const
|
||||
UniValue LookupAllNames() {
|
||||
rpcfn_type rpc_method = tableRPC["listnameclaims"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
return rpc_method(req);
|
||||
}
|
||||
@@ -89,6 +95,7 @@ UniValue LookupAllNames() {
|
||||
std::vector<uint256> generateBlock(int blocks = 1) {
|
||||
rpcfn_type rpc_method = tableRPC["generate"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(blocks);
|
||||
UniValue results = rpc_method(req);
|
||||
@@ -107,6 +114,7 @@ void rollbackBlock(const std::vector<uint256>& ids) {
|
||||
rpcfn_type rpc_method = tableRPC["invalidateblock"]->actor;
|
||||
for (auto it = ids.rbegin(); it != ids.rend(); ++it) {
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(it->GetHex());
|
||||
rpc_method(req);
|
||||
@@ -119,6 +127,7 @@ void rollbackBlock(const std::vector<uint256>& ids) {
|
||||
uint256 AbandonAClaim(const uint256& txid, bool isSupport = false) {
|
||||
rpcfn_type pre_rpc_method = tableRPC["getrawchangeaddress"]->actor;
|
||||
JSONRPCRequest pre_req;
|
||||
pre_req.URI = "/wallet/tester_wallet";
|
||||
pre_req.params = UniValue(UniValue::VARR);
|
||||
pre_req.params.push_back("legacy");
|
||||
UniValue adr_hash = pre_rpc_method(pre_req);
|
||||
@@ -126,6 +135,7 @@ uint256 AbandonAClaim(const uint256& txid, bool isSupport = false) {
|
||||
// pass a txid as name for update
|
||||
rpcfn_type rpc_method = tableRPC[isSupport ? "abandonsupport" : "abandonclaim"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(txid.GetHex());
|
||||
req.params.push_back(adr_hash.get_str());
|
||||
@@ -141,11 +151,9 @@ uint256 AbandonAClaim(const uint256& txid, bool isSupport = false) {
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_op_runthrough)
|
||||
{
|
||||
generateBlock(105);
|
||||
|
||||
BOOST_CHECK_GE(AvailableBalance(), 2.0);
|
||||
void AddClaimSupportThenRemove() {
|
||||
generateBlock(155);
|
||||
BOOST_CHECK_EQUAL(AvailableBalance(), 55.0);
|
||||
|
||||
// ops for test: claimname, updateclaim, abandonclaim, listnameclaims, supportclaim, abandonsupport
|
||||
// order of ops:
|
||||
@@ -163,7 +171,7 @@ BOOST_AUTO_TEST_CASE(claim_op_runthrough)
|
||||
BOOST_CHECK_EQUAL(looked[0]["value"].get_str(), "deadbeef");
|
||||
BOOST_CHECK_EQUAL(looked[0]["txid"].get_str(), txid.GetHex());
|
||||
|
||||
// udpate it
|
||||
// update it
|
||||
auto txid2 = ClaimAName(txid.GetHex(), "deadbeef02", "1.0", true);
|
||||
auto g2 = generateBlock();
|
||||
looked = LookupAllNames().get_array();
|
||||
@@ -244,4 +252,208 @@ BOOST_AUTO_TEST_CASE(claim_op_runthrough)
|
||||
*/
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
BOOST_AUTO_TEST_CASE(claim_op_runthrough_legacy)
|
||||
{
|
||||
for (auto& wallet: GetWallets())
|
||||
wallet->m_default_address_type = OutputType::LEGACY;
|
||||
AddClaimSupportThenRemove();
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_op_runthrough_p2sh)
|
||||
{
|
||||
for (auto& wallet: GetWallets()) {
|
||||
BOOST_CHECK(DEFAULT_ADDRESS_TYPE == wallet->m_default_address_type); // BOOST_CHECK_EQUAL no compile here
|
||||
wallet->m_default_address_type = OutputType::P2SH_SEGWIT;
|
||||
}
|
||||
AddClaimSupportThenRemove();
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_op_runthrough_bech32)
|
||||
{
|
||||
for (auto& wallet: GetWallets()) {
|
||||
BOOST_CHECK(DEFAULT_ADDRESS_TYPE == wallet->m_default_address_type); // BOOST_CHECK_EQUAL no compile here
|
||||
wallet->m_default_address_type = OutputType::BECH32;
|
||||
}
|
||||
AddClaimSupportThenRemove();
|
||||
}
|
||||
|
||||
std::vector<COutPoint> SpendableCoins() {
|
||||
rpcfn_type rpc_method = tableRPC["listunspent"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
UniValue unspents = rpc_method(req);
|
||||
std::vector<COutPoint> ret;
|
||||
for (uint32_t i = 0; i < unspents.size(); ++i)
|
||||
ret.emplace_back(uint256S(unspents[i]["txid"].get_str()), unspents[i]["vout"].get_int());
|
||||
return ret;
|
||||
}
|
||||
|
||||
CTxDestination NewAddress(OutputType t) {
|
||||
rpcfn_type rpc_method = tableRPC["getnewaddress"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back("");
|
||||
req.params.push_back(FormatOutputType(t));
|
||||
UniValue address = rpc_method(req);
|
||||
return DecodeDestination(address.get_str());
|
||||
}
|
||||
|
||||
std::string SignRawTransaction(const std::string& tx) {
|
||||
rpcfn_type rpc_method = tableRPC["signrawtransactionwithwallet"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(tx);
|
||||
UniValue results = rpc_method(req);
|
||||
BOOST_CHECK(results["complete"].get_bool());
|
||||
BOOST_CHECK(!results.exists("errors"));
|
||||
if (results.exists("errors"))
|
||||
fprintf(stderr, "Errors: %s\n", results.write(2).c_str());
|
||||
return results["hex"].get_str();
|
||||
}
|
||||
|
||||
std::string SendRawTransaction(const std::string& tx) {
|
||||
rpcfn_type rpc_method = tableRPC["sendrawtransaction"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(tx);
|
||||
req.params.push_back(UniValue(true)); // allow high fees
|
||||
UniValue results = rpc_method(req);
|
||||
return results.get_str();
|
||||
}
|
||||
|
||||
std::string FundRawTransaction(const std::string& tx) {
|
||||
rpcfn_type rpc_method = tableRPC["fundrawtransaction"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(tx);
|
||||
UniValue results = rpc_method(req);
|
||||
return results["hex"].get_str();
|
||||
}
|
||||
|
||||
std::string ProcessPsbt(const PartiallySignedTransaction& pst) {
|
||||
BOOST_CHECK(pst.IsSane());
|
||||
rpcfn_type rpc_method = tableRPC["walletprocesspsbt"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
|
||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||
ssTx << pst;
|
||||
auto base64 = EncodeBase64((unsigned char*)ssTx.data(), ssTx.size());
|
||||
req.params.push_back(base64);
|
||||
UniValue results = rpc_method(req);
|
||||
BOOST_CHECK(results["complete"].get_bool());
|
||||
return results["psbt"].get_str();
|
||||
}
|
||||
|
||||
std::string FinalizePsbt(const std::string& pst) {
|
||||
rpcfn_type rpc_method = tableRPC["finalizepsbt"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(pst);
|
||||
req.params.push_back(UniValue(true));
|
||||
UniValue results = rpc_method(req);
|
||||
BOOST_CHECK(results["complete"].get_bool());
|
||||
return results["hex"].get_str();
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(can_sign_all_addr)
|
||||
{
|
||||
generateBlock(110);
|
||||
BOOST_CHECK_EQUAL(AvailableBalance(), 10.0);
|
||||
auto coins = SpendableCoins();
|
||||
|
||||
std::vector<std::string> txids;
|
||||
std::vector<std::string> spends;
|
||||
for (uint32_t i = 0; i < 3; ++i) {
|
||||
CMutableTransaction claimTx, spendTx;
|
||||
CTxIn in(coins[i]);
|
||||
claimTx.vin.push_back(in);
|
||||
auto destination = NewAddress(OutputType(i));
|
||||
CScript scriptPubKey = ClaimNameScript("name" + std::to_string(i), "value", false)
|
||||
+ GetScriptForDestination(destination);
|
||||
CTxOut out(100000, scriptPubKey);
|
||||
claimTx.vout.push_back(out);
|
||||
auto hex = EncodeHexTx(claimTx);
|
||||
hex = SignRawTransaction(hex);
|
||||
txids.push_back(SendRawTransaction(hex));
|
||||
CTxIn spendIn(uint256S(txids.back()), 0);
|
||||
auto destination2 = NewAddress(OutputType(i));
|
||||
CTxOut spendOut(90000, GetScriptForDestination(destination2));
|
||||
spendTx.vin.push_back(spendIn);
|
||||
spendTx.vout.push_back(spendOut);
|
||||
hex = EncodeHexTx(spendTx);
|
||||
spends.push_back(hex);
|
||||
}
|
||||
generateBlock(1);
|
||||
auto looked = LookupAllNames().get_array();
|
||||
|
||||
for (std::size_t i = 0; i < 3; ++i) {
|
||||
BOOST_CHECK_EQUAL(looked[i]["name"].get_str(), "name" + std::to_string(i));
|
||||
BOOST_CHECK_EQUAL(looked[i]["value"].get_str(), HexStr(std::string("value")));
|
||||
BOOST_CHECK_EQUAL(looked[i]["txid"].get_str(), txids[i]);
|
||||
}
|
||||
for (auto& s: spends) {
|
||||
auto hex = FundRawTransaction(s); // redundant
|
||||
hex = SignRawTransaction(hex);
|
||||
txids.push_back(SendRawTransaction(hex));
|
||||
}
|
||||
generateBlock(1);
|
||||
looked = LookupAllNames().get_array();
|
||||
BOOST_CHECK_EQUAL(looked.size(), 0U);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(can_sign_all_pbst)
|
||||
{
|
||||
generateBlock(110);
|
||||
BOOST_CHECK_EQUAL(AvailableBalance(), 10.0);
|
||||
auto coins = SpendableCoins();
|
||||
|
||||
std::vector<std::string> txids;
|
||||
std::vector<PartiallySignedTransaction> spends;
|
||||
for (uint32_t i = 0; i < 3; ++i) {
|
||||
CMutableTransaction claimTx, spendTx;
|
||||
CTxIn in(coins[i]);
|
||||
claimTx.vin.push_back(in);
|
||||
auto destination = NewAddress(OutputType(i));
|
||||
CScript scriptPubKey = ClaimNameScript("name" + std::to_string(i), "value", false)
|
||||
+ GetScriptForDestination(destination);
|
||||
CTxOut out(100000, scriptPubKey);
|
||||
claimTx.vout.push_back(out);
|
||||
PartiallySignedTransaction pst(claimTx);
|
||||
auto result = ProcessPsbt(pst);
|
||||
auto hex = FinalizePsbt(result);
|
||||
txids.push_back(SendRawTransaction(hex));
|
||||
CTxIn spendIn(uint256S(txids.back()), 0);
|
||||
auto destination2 = NewAddress(OutputType(i));
|
||||
CTxOut spendOut(90000, GetScriptForDestination(destination2));
|
||||
spendTx.vin.push_back(spendIn);
|
||||
spendTx.vout.push_back(spendOut);
|
||||
spends.push_back(PartiallySignedTransaction(spendTx));
|
||||
}
|
||||
generateBlock(1);
|
||||
auto looked = LookupAllNames().get_array();
|
||||
|
||||
for (std::size_t i = 0; i < 3; ++i) {
|
||||
BOOST_CHECK_EQUAL(looked[i]["name"].get_str(), "name" + std::to_string(i));
|
||||
BOOST_CHECK_EQUAL(looked[i]["value"].get_str(), HexStr(std::string("value")));
|
||||
BOOST_CHECK_EQUAL(looked[i]["txid"].get_str(), txids[i]);
|
||||
}
|
||||
for (auto& s: spends) {
|
||||
auto result = ProcessPsbt(s);
|
||||
auto hex = FinalizePsbt(result);
|
||||
txids.push_back(SendRawTransaction(hex));
|
||||
}
|
||||
generateBlock(1);
|
||||
looked = LookupAllNames().get_array();
|
||||
BOOST_CHECK_EQUAL(looked.size(), 0U);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
+15
-17
@@ -1401,16 +1401,15 @@ bool CWallet::IsChange(const CTxOut& txout) const
|
||||
// a better way of identifying which outputs are 'the send' and which are
|
||||
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
|
||||
// which output, if any, was change).
|
||||
if (::IsMine(*this, txout.scriptPubKey))
|
||||
auto isMine = ::IsMine(*this, txout.scriptPubKey);
|
||||
if (isMine && !(isMine & ISMINE_STAKE)) // stakes are never change
|
||||
{
|
||||
CTxDestination address;
|
||||
const CScript& scriptPubKey = StripClaimScriptPrefix(txout.scriptPubKey);
|
||||
|
||||
if (!ExtractDestination(scriptPubKey, address))
|
||||
if (!ExtractDestination(txout.scriptPubKey, address))
|
||||
return true;
|
||||
|
||||
LOCK(cs_wallet);
|
||||
if (!mapAddressBook.count(address) && (scriptPubKey == txout.scriptPubKey))
|
||||
if (!mapAddressBook.count(address))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -1693,11 +1692,9 @@ void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
|
||||
|
||||
// In either case, we need to get the destination address
|
||||
CTxDestination address;
|
||||
const CScript& scriptPubKey = StripClaimScriptPrefix(txout.scriptPubKey);
|
||||
|
||||
if (!ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable())
|
||||
if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
|
||||
{
|
||||
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
|
||||
pwallet->WalletLogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
|
||||
this->GetHash().ToString());
|
||||
address = CNoDestination();
|
||||
}
|
||||
@@ -1705,7 +1702,7 @@ void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
|
||||
COutputEntry output = {address, txout.nValue, (int)i};
|
||||
|
||||
// If we are debited by the transaction, add the output as a "sent" entry
|
||||
if (nDebit > 0 || filter & ISMINE_CLAIM || filter & ISMINE_SUPPORT)
|
||||
if (nDebit > 0)
|
||||
listSent.push_back(output);
|
||||
|
||||
// If we are receiving the output, add it as a "received" entry
|
||||
@@ -2081,7 +2078,7 @@ bool CWalletTx::IsTrusted() const
|
||||
if (parent == nullptr)
|
||||
return false;
|
||||
const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
|
||||
if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
|
||||
if (!(pwallet->IsMine(parentOut) & ISMINE_SPENDABLE))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -2375,15 +2372,15 @@ void CWallet::AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe, const
|
||||
continue;
|
||||
}
|
||||
|
||||
bool solvable = IsSolvable(*this, pcoin->tx->vout[i].scriptPubKey);
|
||||
bool spendable = (mine & ISMINE_SPENDABLE) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
|
||||
|
||||
// spending claims or supports requires specific selection:
|
||||
auto isClaimCoin = (mine & ISMINE_CLAIM) || (mine & ISMINE_SUPPORT);
|
||||
auto claimSpendRequested = isClaimCoin && coinControl && coinControl->IsSelected(COutPoint(entry.first, i));
|
||||
|
||||
bool solvable = IsSolvable(*this, pcoin->tx->vout[i].scriptPubKey);
|
||||
bool spendable = claimSpendRequested || ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
|
||||
|
||||
if (spendable && isClaimCoin && !claimSpendRequested)
|
||||
continue; // double check
|
||||
continue;
|
||||
|
||||
vCoins.push_back(COutput(pcoin, i, nDepth, spendable, solvable, safeTx, (coinControl && coinControl->fAllowWatchOnly)));
|
||||
|
||||
@@ -2437,7 +2434,7 @@ std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
|
||||
if (it != mapWallet.end()) {
|
||||
int depth = it->second.GetDepthInMainChain();
|
||||
if (depth >= 0 && output.n < it->second.tx->vout.size() &&
|
||||
IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
|
||||
IsMine(it->second.tx->vout[output.n]) & ISMINE_SPENDABLE) {
|
||||
CTxDestination address;
|
||||
if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
|
||||
result[address].emplace_back(
|
||||
@@ -2704,7 +2701,8 @@ OutputType CWallet::TransactionChangeType(OutputType change_type, const std::vec
|
||||
// Check if any destination contains a witness program:
|
||||
int witnessversion = 0;
|
||||
std::vector<unsigned char> witnessprogram;
|
||||
if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
|
||||
const auto stripped = StripClaimScriptPrefix(recipient.scriptPubKey);
|
||||
if (stripped.IsWitnessProgram(witnessversion, witnessprogram)) {
|
||||
return OutputType::BECH32;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"reqSigs": 1,
|
||||
"type": "witness_v0_scripthash",
|
||||
"addresses": [
|
||||
"bc1qu9dgdg330r6r84g5mw7wqshg04exv2uttmw2elfwx74h5tgntuzs44gyfg"
|
||||
"lbc1qu9dgdg330r6r84g5mw7wqshg04exv2uttmw2elfwx74h5tgntuzsq9wzaf"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"reqSigs": 1,
|
||||
"type": "witness_v0_keyhash",
|
||||
"addresses": [
|
||||
"bc1q5fgkuac9s2ry56jka5s6zqsyfcugcchry5cwu0"
|
||||
"lbc1q5fgkuac9s2ry56jka5s6zqsyfcugcchry7rwyw"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"reqSigs": 1,
|
||||
"type": "witness_v0_scripthash",
|
||||
"addresses": [
|
||||
"bc1qp0lfxhnscvsu0j36l36uurgv5tuck4pzuqytkvwqp3kh78cupttqyf705v"
|
||||
"lbc1qp0lfxhnscvsu0j36l36uurgv5tuck4pzuqytkvwqp3kh78cupttq3ecfqd"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user