Compare commits
50
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a072d06d5 | ||
|
|
76e3d8861c | ||
|
|
b16356b927 | ||
|
|
1bbedef565 | ||
|
|
e5f049e5ed | ||
|
|
9dee2eee5f | ||
|
|
785471745c | ||
|
|
7afebb02f4 | ||
|
|
8932d90a9e | ||
|
|
96fdb05689 | ||
|
|
9149e371ed | ||
|
|
12ab16f50e | ||
|
|
c185b49ede | ||
|
|
d05eee35e8 | ||
|
|
4df4136c5d | ||
|
|
b7cdd9f2a0 | ||
|
|
ffe828b1d9 | ||
|
|
71bd612c4a | ||
|
|
f176db058e | ||
|
|
b434864f18 | ||
|
|
4da4ab1995 | ||
|
|
920a9b09dc | ||
|
|
8b98a9a4e9 | ||
|
|
476eae3e93 | ||
|
|
6575fb9534 | ||
|
|
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
-13
@@ -7,7 +7,6 @@ cache:
|
||||
stages:
|
||||
- build
|
||||
- test
|
||||
- quality
|
||||
|
||||
jobs:
|
||||
include:
|
||||
@@ -68,7 +67,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,19 +78,9 @@ 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
|
||||
osx_image: xcode8.3
|
||||
env: NAME=darwin
|
||||
|
||||
|
||||
- stage: quality
|
||||
name: "check format"
|
||||
os: linux
|
||||
dist: xenial
|
||||
language: minimal
|
||||
install:
|
||||
- sudo apt-get install -y clang-format-3.9
|
||||
script: git diff -U0 origin/master -- '*.h' '*.cpp' | ./contrib/devtools/clang-format-diff.py -p1
|
||||
@@ -178,6 +178,10 @@ Testnet is maintained for testing purposes and can be accessed using the command
|
||||
|
||||
It is easy to solo mine on testnet. (It's easy on mainnet too, but much harder to win.) For instructions see https://github.com/lbryio/sgminer-gm and https://github.com/lbryio/lbrycrd/tree/master/contrib/mining
|
||||
|
||||
## Mailing List
|
||||
|
||||
We maintain a mailing list for notifications of upgrades, security issues, and soft/hard forks. To join, visit [https://lbry.com/forklist](https://lbry.com/forklist).
|
||||
|
||||
## License
|
||||
|
||||
This project is MIT licensed. For the full license, see [LICENSE](LICENSE).
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ dnl require autoconf 2.60 (AS_ECHO/AS_ECHO_N)
|
||||
AC_PREREQ([2.60])
|
||||
define(_CLIENT_VERSION_MAJOR, 0)
|
||||
define(_CLIENT_VERSION_MINOR, 17)
|
||||
define(_CLIENT_VERSION_REVISION, 2)
|
||||
define(_CLIENT_VERSION_BUILD, 1)
|
||||
define(_CLIENT_VERSION_REVISION, 3)
|
||||
define(_CLIENT_VERSION_BUILD, 2)
|
||||
define(_CLIENT_VERSION_IS_RELEASE, true)
|
||||
define(_COPYRIGHT_YEAR, 2019)
|
||||
define(_COPYRIGHT_HOLDERS,[The %s developers])
|
||||
|
||||
@@ -36,7 +36,7 @@ insert into coins(name, symbol, symbol2, algo, enable, auto_ready, rpcuser, rpcp
|
||||
values('Local LBRY Instance', 'LBC', 'LBC', 'lbry', 1, 1, 'ruser', 'rpswd', '127.0.0.1', 19245, 1, 'utf-8', 0, 1, 0, 0, 0);
|
||||
exit
|
||||
```
|
||||
Use port 19245 for testnet, port 9245 for main.
|
||||
Use port 19245 for testnet, port 9245 for main. Set usesegwit to 1 after the segwit fork is enabled on December 11, 2019.
|
||||
#### 3. Run the stratum server:
|
||||
```
|
||||
docker run --network host -d lbry/yiimp_stratum
|
||||
@@ -47,10 +47,11 @@ docker run --network host -it lbry/yiimp_stratum bash
|
||||
cat config/lbry.conf
|
||||
./stratum config/lbry
|
||||
```
|
||||
When testing with an ASIC you may need to modify the TCP server address in said lbry.conf file to be an external IP address.
|
||||
|
||||
#### 4. Connect sgminer to it:
|
||||
```
|
||||
sgminer -k lbry -o stratum+tcp://127.0.0.1:3334/ -D -T -O mn824Su1wX7ip8WcNYzXwwWqvBvkeWGRo6:x
|
||||
```
|
||||
The username there is the account to receive payments from the pool. The password is unused. Tested with https://github.com/lbryio/sgminer-gm.
|
||||
You can use whatever miner you prefer.
|
||||
You can use whatever miner you prefer.
|
||||
@@ -20,9 +20,6 @@ if which ccache >/dev/null; then
|
||||
ccache -ps
|
||||
fi
|
||||
|
||||
export CXXFLAGS="${CXXFLAGS:--frecord-gcc-switches}"
|
||||
echo "CXXFLAGS set to $CXXFLAGS"
|
||||
|
||||
pushd depends
|
||||
make -j`getconf _NPROCESSORS_ONLN` HOST=i686-w64-mingw32 NO_QT=1 V=1
|
||||
popd
|
||||
|
||||
@@ -19,9 +19,6 @@ if which ccache >/dev/null; then
|
||||
ccache -ps
|
||||
fi
|
||||
|
||||
export CXXFLAGS="${CXXFLAGS:--frecord-gcc-switches}"
|
||||
echo "CXXFLAGS set to $CXXFLAGS"
|
||||
|
||||
pushd depends
|
||||
make -j`getconf _NPROCESSORS_ONLN` HOST=x86_64-w64-mingw32 NO_QT=1 V=1
|
||||
popd
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -66,6 +66,11 @@ BITCOIN_TESTS =\
|
||||
test/net_tests.cpp \
|
||||
test/claimtriecache_tests.cpp \
|
||||
test/claimtriebranching_tests.cpp \
|
||||
test/claimtrieexpirationfork_tests.cpp \
|
||||
test/claimtriefixture.cpp \
|
||||
test/claimtriehashfork_tests.cpp \
|
||||
test/claimtrienormalization_tests.cpp \
|
||||
test/claimtrierpc_tests.cpp \
|
||||
test/nameclaim_tests.cpp \
|
||||
test/netbase_tests.cpp \
|
||||
test/pmt_tests.cpp \
|
||||
|
||||
@@ -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>
|
||||
|
||||
+15
-10
@@ -123,7 +123,7 @@ void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64
|
||||
class CMainParams : public CChainParams {
|
||||
public:
|
||||
CMainParams() {
|
||||
strNetworkID = "lbrycrd";
|
||||
strNetworkID = CBaseChainParams::MAIN;
|
||||
consensus.nSubsidyLevelInterval = 1<<5;
|
||||
consensus.nMajorityEnforceBlockUpgrade = 750;
|
||||
consensus.nMajorityRejectBlockOutdated = 950;
|
||||
@@ -144,7 +144,9 @@ public:
|
||||
consensus.nAllowMinDiffMaxHeight = -1;
|
||||
consensus.nNormalizedNameForkHeight = 539940; // targeting 21 March 2019
|
||||
consensus.nMinTakeoverWorkaroundHeight = 496850;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 10000000;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 658300; // targeting 30 Oct 2019
|
||||
consensus.nWitnessForkHeight = 680770; // targeting 11 Dec 2019
|
||||
consensus.nAllClaimsInMerkleForkHeight = 658310; // 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.
|
||||
@@ -240,7 +241,7 @@ public:
|
||||
class CTestNetParams : public CChainParams {
|
||||
public:
|
||||
CTestNetParams() {
|
||||
strNetworkID = "lbrycrdtest";
|
||||
strNetworkID = CBaseChainParams::TESTNET;
|
||||
consensus.nSubsidyLevelInterval = 1 << 5;
|
||||
consensus.nMajorityEnforceBlockUpgrade = 51;
|
||||
consensus.nMajorityRejectBlockOutdated = 75;
|
||||
@@ -261,7 +262,9 @@ public:
|
||||
consensus.nAllowMinDiffMaxHeight = 1100000;
|
||||
consensus.nNormalizedNameForkHeight = 993380; // targeting, 21 Feb 2019
|
||||
consensus.nMinTakeoverWorkaroundHeight = 99;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 10000000;
|
||||
consensus.nMaxTakeoverWorkaroundHeight = 1198550; // targeting 30 Sep 2019
|
||||
consensus.nWitnessForkHeight = 1198600;
|
||||
consensus.nAllClaimsInMerkleForkHeight = 1198560; // targeting 30 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
|
||||
@@ -348,7 +351,7 @@ public:
|
||||
class CRegTestParams : public CChainParams {
|
||||
public:
|
||||
CRegTestParams() {
|
||||
strNetworkID = "lbrycrdreg";
|
||||
strNetworkID = CBaseChainParams::REGTEST;
|
||||
consensus.nSubsidyLevelInterval = 1 << 5;
|
||||
consensus.BIP16Exception = uint256();
|
||||
consensus.BIP34Height = 1000; // BIP34 is needed for validation_block_tests
|
||||
@@ -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
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
const std::string CBaseChainParams::MAIN = "lbrycrd";
|
||||
const std::string CBaseChainParams::TESTNET = "lbrycrdtest";
|
||||
const std::string CBaseChainParams::REGTEST = "regtest";
|
||||
const std::string CBaseChainParams::REGTEST = "lbrycrdreg";
|
||||
|
||||
void SetupChainParamsBaseOptions()
|
||||
{
|
||||
|
||||
@@ -149,7 +149,7 @@ bool ProcessClaim(CClaimScriptOp& claimOp, CClaimTrieCache& trieCache, const CSc
|
||||
{
|
||||
int op;
|
||||
std::vector<std::vector<unsigned char> > vvchParams;
|
||||
if (!DecodeClaimScript(scriptPubKey, op, vvchParams))
|
||||
if (!DecodeClaimScript(scriptPubKey, op, vvchParams, trieCache.allowSupportMetadata()))
|
||||
return false;
|
||||
|
||||
switch (op) {
|
||||
|
||||
+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;
|
||||
|
||||
+237
-185
@@ -8,9 +8,7 @@
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
|
||||
#include <boost/scoped_ptr.hpp>
|
||||
|
||||
static const uint256 one = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
|
||||
extern const uint256 one = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
|
||||
|
||||
std::vector<unsigned char> heightToVch(int n)
|
||||
{
|
||||
@@ -63,7 +61,7 @@ template <typename T, typename C>
|
||||
auto findOutPoint(T& cont, const C& point) -> decltype(cont.begin())
|
||||
{
|
||||
using type = typename T::value_type;
|
||||
static_assert(std::is_same<typename std::remove_const<T>::type, std::vector<type>>::value, "T should be a vector type");
|
||||
static_assert(std::is_same<typename std::decay<T>::type, std::vector<type>>::value, "T should be a vector type");
|
||||
return std::find_if(cont.begin(), cont.end(), [&point](const type& val) {
|
||||
return equals(val, point);
|
||||
});
|
||||
@@ -123,13 +121,13 @@ void CClaimTrieData::reorderClaims(const supportEntryType& supports)
|
||||
claim.nEffectiveAmount += support.nAmount;
|
||||
}
|
||||
|
||||
std::make_heap(claims.begin(), claims.end());
|
||||
std::sort(claims.rbegin(), claims.rend());
|
||||
}
|
||||
|
||||
CClaimTrie::CClaimTrie(bool fMemory, bool fWipe, int proportionalDelayFactor)
|
||||
CClaimTrie::CClaimTrie(bool fMemory, bool fWipe, int proportionalDelayFactor, std::size_t cacheMB)
|
||||
{
|
||||
nProportionalDelayFactor = proportionalDelayFactor;
|
||||
db.reset(new CDBWrapper(GetDataDir() / "claimtrie", 100 * 1024 * 1024, fMemory, fWipe, false));
|
||||
db.reset(new CDBWrapper(GetDataDir() / "claimtrie", cacheMB * 1024ULL * 1024ULL, fMemory, fWipe, false));
|
||||
}
|
||||
|
||||
bool CClaimTrie::SyncToDisk()
|
||||
@@ -137,19 +135,31 @@ bool CClaimTrie::SyncToDisk()
|
||||
return db && db->Sync();
|
||||
}
|
||||
|
||||
template <typename Key, typename Container>
|
||||
typename Container::value_type* getQueue(CDBWrapper& db, uint8_t dbkey, const Key& key, Container& queue, bool create)
|
||||
template <typename T>
|
||||
using rm_ref = typename std::remove_reference<T>::type;
|
||||
|
||||
template <typename Key, typename Map>
|
||||
auto getRow(const CDBWrapper& db, uint8_t dbkey, const Key& key, Map& queue) -> COptional<rm_ref<decltype(queue.at(key))>>
|
||||
{
|
||||
auto itQueue = queue.find(key);
|
||||
if (itQueue != queue.end())
|
||||
return &(*itQueue);
|
||||
typename Container::mapped_type row;
|
||||
if (db.Read(std::make_pair(dbkey, key), row) || create) {
|
||||
auto ret = queue.insert(std::make_pair(key, row));
|
||||
auto it = queue.find(key);
|
||||
if (it != queue.end())
|
||||
return {&(it->second)};
|
||||
typename Map::mapped_type row;
|
||||
if (db.Read(std::make_pair(dbkey, key), row))
|
||||
return {std::move(row)};
|
||||
return {};
|
||||
}
|
||||
|
||||
template <typename Key, typename Value>
|
||||
Value* getQueue(const CDBWrapper& db, uint8_t dbkey, const Key& key, std::map<Key, Value>& queue, bool create)
|
||||
{
|
||||
auto row = getRow(db, dbkey, key, queue);
|
||||
if (row.unique() || (!row && create)) {
|
||||
auto ret = queue.emplace(key, row ? std::move(*row) : Value{});
|
||||
assert(ret.second);
|
||||
return &(*ret.first);
|
||||
return &(ret.first->second);
|
||||
}
|
||||
return nullptr;
|
||||
return row;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
@@ -160,57 +170,95 @@ inline constexpr bool supportedType()
|
||||
}
|
||||
|
||||
template <>
|
||||
std::pair<const int, std::vector<queueEntryType<CClaimValue>>>* CClaimTrieCacheBase::getQueueCacheRow(int nHeight, bool createIfNotExists)
|
||||
std::vector<queueEntryType<CClaimValue>>* CClaimTrieCacheBase::getQueueCacheRow(int nHeight, bool createIfNotExists)
|
||||
{
|
||||
return getQueue(*(base->db), CLAIM_QUEUE_ROW, nHeight, claimQueueCache, createIfNotExists);
|
||||
}
|
||||
|
||||
template <>
|
||||
std::pair<const int, std::vector<queueEntryType<CSupportValue>>>* CClaimTrieCacheBase::getQueueCacheRow(int nHeight, bool createIfNotExists)
|
||||
std::vector<queueEntryType<CSupportValue>>* CClaimTrieCacheBase::getQueueCacheRow(int nHeight, bool createIfNotExists)
|
||||
{
|
||||
return getQueue(*(base->db), SUPPORT_QUEUE_ROW, nHeight, supportQueueCache, createIfNotExists);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::pair<const int, std::vector<queueEntryType<T>>>* CClaimTrieCacheBase::getQueueCacheRow(int, bool)
|
||||
std::vector<queueEntryType<T>>* CClaimTrieCacheBase::getQueueCacheRow(int, bool)
|
||||
{
|
||||
supportedType<T>();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template <>
|
||||
typename queueNameType::value_type* CClaimTrieCacheBase::getQueueCacheNameRow<CClaimValue>(const std::string& name, bool createIfNotExists)
|
||||
COptional<const std::vector<queueEntryType<CClaimValue>>> CClaimTrieCacheBase::getQueueCacheRow(int nHeight) const
|
||||
{
|
||||
return getQueue(*(base->db), CLAIM_QUEUE_NAME_ROW, name, claimQueueNameCache, createIfNotExists);
|
||||
return getRow(*(base->db), CLAIM_QUEUE_ROW, nHeight, claimQueueCache);
|
||||
}
|
||||
|
||||
template <>
|
||||
typename queueNameType::value_type* CClaimTrieCacheBase::getQueueCacheNameRow<CSupportValue>(const std::string& name, bool createIfNotExists)
|
||||
COptional<const std::vector<queueEntryType<CSupportValue>>> CClaimTrieCacheBase::getQueueCacheRow(int nHeight) const
|
||||
{
|
||||
return getQueue(*(base->db), SUPPORT_QUEUE_NAME_ROW, name, supportQueueNameCache, createIfNotExists);
|
||||
return getRow(*(base->db), SUPPORT_QUEUE_ROW, nHeight, supportQueueCache);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
typename queueNameType::value_type* CClaimTrieCacheBase::getQueueCacheNameRow(const std::string&, bool)
|
||||
COptional<const std::vector<queueEntryType<T>>> CClaimTrieCacheBase::getQueueCacheRow(int) const
|
||||
{
|
||||
supportedType<T>();
|
||||
return {};
|
||||
}
|
||||
|
||||
template <>
|
||||
queueNameRowType* CClaimTrieCacheBase::getQueueCacheNameRow<CClaimValue>(const std::string& name, bool createIfNoExists)
|
||||
{
|
||||
return getQueue(*(base->db), CLAIM_QUEUE_NAME_ROW, name, claimQueueNameCache, createIfNoExists);
|
||||
}
|
||||
|
||||
template <>
|
||||
queueNameRowType* CClaimTrieCacheBase::getQueueCacheNameRow<CSupportValue>(const std::string& name, bool createIfNoExists)
|
||||
{
|
||||
return getQueue(*(base->db), SUPPORT_QUEUE_NAME_ROW, name, supportQueueNameCache, createIfNoExists);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
queueNameRowType* CClaimTrieCacheBase::getQueueCacheNameRow(const std::string&, bool)
|
||||
{
|
||||
supportedType<T>();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template <>
|
||||
typename expirationQueueType::value_type* CClaimTrieCacheBase::getExpirationQueueCacheRow<CClaimValue>(int nHeight, bool createIfNotExists)
|
||||
COptional<const queueNameRowType> CClaimTrieCacheBase::getQueueCacheNameRow<CClaimValue>(const std::string& name) const
|
||||
{
|
||||
return getQueue(*(base->db), EXP_QUEUE_ROW, nHeight, expirationQueueCache, createIfNotExists);
|
||||
return getRow(*(base->db), CLAIM_QUEUE_NAME_ROW, name, claimQueueNameCache);
|
||||
}
|
||||
|
||||
template <>
|
||||
typename expirationQueueType::value_type* CClaimTrieCacheBase::getExpirationQueueCacheRow<CSupportValue>(int nHeight, bool createIfNotExists)
|
||||
COptional<const queueNameRowType> CClaimTrieCacheBase::getQueueCacheNameRow<CSupportValue>(const std::string& name) const
|
||||
{
|
||||
return getQueue(*(base->db), SUPPORT_EXP_QUEUE_ROW, nHeight, supportExpirationQueueCache, createIfNotExists);
|
||||
return getRow(*(base->db), SUPPORT_QUEUE_NAME_ROW, name, supportQueueNameCache);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
typename expirationQueueType::value_type* CClaimTrieCacheBase::getExpirationQueueCacheRow(int, bool)
|
||||
COptional<const queueNameRowType> CClaimTrieCacheBase::getQueueCacheNameRow(const std::string&) const
|
||||
{
|
||||
supportedType<T>();
|
||||
return {};
|
||||
}
|
||||
|
||||
template <>
|
||||
expirationQueueRowType* CClaimTrieCacheBase::getExpirationQueueCacheRow<CClaimValue>(int nHeight, bool createIfNoExists)
|
||||
{
|
||||
return getQueue(*(base->db), CLAIM_EXP_QUEUE_ROW, nHeight, expirationQueueCache, createIfNoExists);
|
||||
}
|
||||
|
||||
template <>
|
||||
expirationQueueRowType* CClaimTrieCacheBase::getExpirationQueueCacheRow<CSupportValue>(int nHeight, bool createIfNoExists)
|
||||
{
|
||||
return getQueue(*(base->db), SUPPORT_EXP_QUEUE_ROW, nHeight, supportExpirationQueueCache, createIfNoExists);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
expirationQueueRowType* CClaimTrieCacheBase::getExpirationQueueCacheRow(int, bool)
|
||||
{
|
||||
supportedType<T>();
|
||||
return nullptr;
|
||||
@@ -241,16 +289,16 @@ supportEntryType CClaimTrieCacheBase::getSupportsForName(const std::string& name
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool CClaimTrieCacheBase::haveInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight)
|
||||
bool CClaimTrieCacheBase::haveInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const
|
||||
{
|
||||
supportedType<T>();
|
||||
if (auto nameRow = getQueueCacheNameRow<T>(name)) {
|
||||
auto itNameRow = findOutPoint(nameRow->second, outPoint);
|
||||
if (itNameRow != nameRow->second.end()) {
|
||||
auto itNameRow = findOutPoint(*nameRow, outPoint);
|
||||
if (itNameRow != nameRow->end()) {
|
||||
nValidAtHeight = itNameRow->nHeight;
|
||||
if (auto row = getQueueCacheRow<T>(nValidAtHeight)) {
|
||||
auto iRow = findOutPoint(row->second, CNameOutPointType{name, outPoint});
|
||||
if (iRow != row->second.end()) {
|
||||
auto iRow = findOutPoint(*row, CNameOutPointType{name, outPoint});
|
||||
if (iRow != row->end()) {
|
||||
if (iRow->second.nValidAtHeight != nValidAtHeight)
|
||||
LogPrintf("%s: An inconsistency was found in the support queue. Please report this to the developers:\nDifferent nValidAtHeight between named queue and height queue\n: name: %s, txid: %s, nOut: %d, nValidAtHeight in named queue: %d, nValidAtHeight in height queue: %d current height: %d\n", __func__, name, outPoint.hash.GetHex(), outPoint.n, nValidAtHeight, iRow->second.nValidAtHeight, nNextHeight);
|
||||
return true;
|
||||
@@ -262,37 +310,37 @@ bool CClaimTrieCacheBase::haveInQueue(const std::string& name, const COutPoint&
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight)
|
||||
bool CClaimTrieCacheBase::haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const
|
||||
{
|
||||
return haveInQueue<CClaimValue>(name, outPoint, nValidAtHeight);
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::haveSupportInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight)
|
||||
bool CClaimTrieCacheBase::haveSupportInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const
|
||||
{
|
||||
return haveInQueue<CSupportValue>(name, outPoint, nValidAtHeight);
|
||||
}
|
||||
|
||||
std::size_t CClaimTrieCacheBase::getTotalNamesInTrie() const
|
||||
std::size_t CClaimTrie::getTotalNamesInTrie() const
|
||||
{
|
||||
std::size_t count = 0;
|
||||
for (auto it = base->cbegin(); it != base->cend(); ++it)
|
||||
for (auto it = begin(); it != end(); ++it)
|
||||
if (!it->empty()) ++count;
|
||||
return count;
|
||||
}
|
||||
|
||||
std::size_t CClaimTrieCacheBase::getTotalClaimsInTrie() const
|
||||
std::size_t CClaimTrie::getTotalClaimsInTrie() const
|
||||
{
|
||||
std::size_t count = 0;
|
||||
for (auto it = base->cbegin(); it != base->cend(); ++it)
|
||||
for (auto it = begin(); it != end(); ++it)
|
||||
count += it->claims.size();
|
||||
return count;
|
||||
}
|
||||
|
||||
CAmount CClaimTrieCacheBase::getTotalValueOfClaimsInTrie(bool fControllingOnly) const
|
||||
CAmount CClaimTrie::getTotalValueOfClaimsInTrie(bool fControllingOnly) const
|
||||
{
|
||||
CAmount value_in_subtrie = 0;
|
||||
for (auto it = base->cbegin(); it != base->cend(); ++it) {
|
||||
for (const auto& claim : it->claims) {
|
||||
for (auto it = begin(); it != end(); ++it) {
|
||||
for (auto& claim : it->claims) {
|
||||
value_in_subtrie += claim.nAmount;
|
||||
if (fControllingOnly)
|
||||
break;
|
||||
@@ -307,40 +355,50 @@ bool CClaimTrieCacheBase::getInfoForName(const std::string& name, CClaimValue& c
|
||||
return it && it->getBestClaim(claim);
|
||||
}
|
||||
|
||||
CClaimsForNameType CClaimTrieCacheBase::getClaimsForName(const std::string& name) const
|
||||
template <typename T>
|
||||
void CClaimTrieCacheBase::insertRowsFromQueue(std::vector<T>& result, const std::string& name) const
|
||||
{
|
||||
supportedType<T>();
|
||||
if (auto nameRows = getQueueCacheNameRow<T>(name))
|
||||
for (auto& nameRow : *nameRows)
|
||||
if (auto rows = getQueueCacheRow<T>(nameRow.nHeight))
|
||||
for (auto& row : *rows)
|
||||
if (row.first == name)
|
||||
result.push_back(row.second);
|
||||
}
|
||||
|
||||
CClaimSupportToName CClaimTrieCacheBase::getClaimsForName(const std::string& name) const
|
||||
{
|
||||
claimEntryType claims;
|
||||
int nLastTakeoverHeight = 0;
|
||||
auto supports = getSupportsForName(name);
|
||||
insertRowsFromQueue(supports, name);
|
||||
|
||||
if (auto it = find(name)) {
|
||||
claims = it->claims;
|
||||
nLastTakeoverHeight = it->nHeightOfLastTakeover;
|
||||
}
|
||||
return {std::move(claims), std::move(supports), nLastTakeoverHeight, name};
|
||||
}
|
||||
insertRowsFromQueue(claims, name);
|
||||
|
||||
CAmount CClaimTrieCacheBase::getEffectiveAmountForClaim(const std::string& name, const uint160& claimId, std::vector<CSupportValue>* supports) const
|
||||
{
|
||||
return getEffectiveAmountForClaim(getClaimsForName(name), claimId, supports);
|
||||
}
|
||||
auto find = [&supports](decltype(supports)::iterator& it, const CClaimValue& claim) {
|
||||
it = std::find_if(it, supports.end(), [&claim](const CSupportValue& support) {
|
||||
return claim.claimId == support.supportedClaimId;
|
||||
});
|
||||
return it != supports.end();
|
||||
};
|
||||
|
||||
CAmount CClaimTrieCacheBase::getEffectiveAmountForClaim(const CClaimsForNameType& claims, const uint160& claimId, std::vector<CSupportValue>* supports) const
|
||||
{
|
||||
CAmount effectiveAmount = 0;
|
||||
for (const auto& claim : claims.claims) {
|
||||
if (claim.claimId == claimId && claim.nValidAtHeight < nNextHeight) {
|
||||
effectiveAmount += claim.nAmount;
|
||||
for (const auto& support : claims.supports) {
|
||||
if (support.supportedClaimId == claimId && support.nValidAtHeight < nNextHeight) {
|
||||
effectiveAmount += support.nAmount;
|
||||
if (supports) supports->push_back(support);
|
||||
}
|
||||
}
|
||||
break;
|
||||
// match support to claim
|
||||
std::vector<CClaimNsupports> claimsNsupports;
|
||||
for (const auto& claim : claims) {
|
||||
CAmount nAmount = claim.nValidAtHeight < nNextHeight ? claim.nAmount : 0;
|
||||
auto ic = claimsNsupports.emplace(claimsNsupports.end(), claim, nAmount);
|
||||
for (auto it = supports.begin(); find(it, claim); it = supports.erase(it)) {
|
||||
if (it->nValidAtHeight < nNextHeight)
|
||||
ic->effectiveAmount += it->nAmount;
|
||||
ic->supports.emplace_back(std::move(*it));
|
||||
}
|
||||
}
|
||||
return effectiveAmount;
|
||||
return {name, nLastTakeoverHeight, std::move(claimsNsupports), std::move(supports)};
|
||||
}
|
||||
|
||||
void completeHash(uint256& partialHash, const std::string& key, std::size_t to)
|
||||
@@ -357,7 +415,7 @@ template <typename T>
|
||||
using iCbType = std::function<void(T&)>;
|
||||
|
||||
template <typename TIterator>
|
||||
uint256 recursiveMerkleHash(TIterator& it, const iCbType<TIterator>& process, const iCbType<TIterator>& verify = {})
|
||||
uint256 recursiveMerkleHash(TIterator& it, const iCbType<TIterator>& process)
|
||||
{
|
||||
std::vector<uint8_t> vchToHash;
|
||||
const auto pos = it.key().size();
|
||||
@@ -374,28 +432,19 @@ uint256 recursiveMerkleHash(TIterator& it, const iCbType<TIterator>& process, co
|
||||
if (it->getBestClaim(claim)) {
|
||||
uint256 valueHash = getValueHash(claim.outPoint, it->nHeightOfLastTakeover);
|
||||
vchToHash.insert(vchToHash.end(), valueHash.begin(), valueHash.end());
|
||||
} else if (verify) {
|
||||
verify(it);
|
||||
} else if (!it.hasChildren()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return Hash(vchToHash.begin(), vchToHash.end());
|
||||
}
|
||||
|
||||
bool recursiveCheckConsistency(CClaimTrie::const_iterator& it, std::string& failed)
|
||||
bool CClaimTrieCacheBase::recursiveCheckConsistency(CClaimTrie::const_iterator& it, std::string& failed) const
|
||||
{
|
||||
struct CRecursiveBreak : public std::exception {};
|
||||
|
||||
struct CRecursiveBreak {};
|
||||
using iterator = CClaimTrie::const_iterator;
|
||||
iCbType<iterator> verify = [&failed](iterator& it) {
|
||||
if (!it.hasChildren()) {
|
||||
// we don't allow a situation of no children and no claims; no empty leaf nodes allowed
|
||||
failed = it.key();
|
||||
throw CRecursiveBreak();
|
||||
}
|
||||
};
|
||||
|
||||
iCbType<iterator> process = [&failed, &process, &verify](iterator& it) {
|
||||
if (it->hash != recursiveMerkleHash(it, process, verify)) {
|
||||
iCbType<iterator> process = [&failed, &process](iterator& it) {
|
||||
if (it->hash.IsNull() || it->hash != recursiveMerkleHash(it, process)) {
|
||||
failed = it.key();
|
||||
throw CRecursiveBreak();
|
||||
}
|
||||
@@ -437,19 +486,6 @@ bool CClaimTrieCacheBase::checkConsistency() const
|
||||
return consistent;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::getClaimById(const uint160& claimId, std::string& name, CClaimValue& claim) const
|
||||
{
|
||||
CClaimIndexElement element;
|
||||
if (!base->db->Read(std::make_pair(CLAIM_BY_ID, claimId), element))
|
||||
return false;
|
||||
if (element.claim.claimId == claimId) {
|
||||
name = element.name;
|
||||
claim = element.claim;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename K, typename T>
|
||||
void BatchWrite(CDBBatch& batch, uint8_t dbkey, const K& key, const std::vector<T>& value)
|
||||
{
|
||||
@@ -505,17 +541,22 @@ bool CClaimTrieCacheBase::flush()
|
||||
}
|
||||
|
||||
BatchWriteQueue(batch, SUPPORT, supportCache);
|
||||
|
||||
BatchWriteQueue(batch, CLAIM_QUEUE_ROW, claimQueueCache);
|
||||
BatchWriteQueue(batch, CLAIM_QUEUE_NAME_ROW, claimQueueNameCache);
|
||||
BatchWriteQueue(batch, EXP_QUEUE_ROW, expirationQueueCache);
|
||||
BatchWriteQueue(batch, CLAIM_EXP_QUEUE_ROW, expirationQueueCache);
|
||||
|
||||
BatchWriteQueue(batch, SUPPORT_QUEUE_ROW, supportQueueCache);
|
||||
BatchWriteQueue(batch, SUPPORT_QUEUE_NAME_ROW, supportQueueNameCache);
|
||||
BatchWriteQueue(batch, SUPPORT_EXP_QUEUE_ROW, supportExpirationQueueCache);
|
||||
|
||||
base->nNextHeight = nNextHeight;
|
||||
if (!nodesToAddOrUpdate.empty())
|
||||
LogPrint(BCLog::CLAIMS, "Cache size: %zu from base size: %zu on block %d\n", nodesToAddOrUpdate.height(), base->height(), nNextHeight);
|
||||
if (!nodesToAddOrUpdate.empty() && (LogAcceptCategory(BCLog::CLAIMS) || LogAcceptCategory(BCLog::BENCH))) {
|
||||
LogPrintf("TrieCache size: %zu nodes on block %d, batch writes %zu bytes.\n",
|
||||
nodesToAddOrUpdate.height(), nNextHeight, batch.SizeEstimate());
|
||||
}
|
||||
auto ret = base->db->WriteBatch(batch);
|
||||
|
||||
clear();
|
||||
return ret;
|
||||
}
|
||||
@@ -526,12 +567,15 @@ bool CClaimTrieCacheBase::ReadFromDisk(const CBlockIndex* tip)
|
||||
|
||||
base->nNextHeight = nNextHeight = tip ? tip->nHeight + 1 : 0;
|
||||
|
||||
if (tip && base->db->Exists(std::make_pair(TRIE_NODE_CHILDREN, std::string()))) {
|
||||
LogPrintf("The claim trie database contains deprecated data and will need to be rebuilt.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
clear();
|
||||
base->clear();
|
||||
boost::scoped_ptr<CDBIterator> pcursor(base->db->NewIterator());
|
||||
|
||||
std::vector<std::pair<std::string, uint256>> hashesOnEmptyNodes;
|
||||
|
||||
for (pcursor->SeekToFirst(); pcursor->Valid(); pcursor->Next()) {
|
||||
std::pair<uint8_t, std::string> key;
|
||||
if (!pcursor->GetKey(key) || key.first != TRIE_NODE)
|
||||
@@ -542,7 +586,7 @@ bool CClaimTrieCacheBase::ReadFromDisk(const CBlockIndex* tip)
|
||||
if (data.empty()) {
|
||||
// we have a situation where our old trie had many empty nodes
|
||||
// we don't want to automatically throw those all into our prefix trie
|
||||
hashesOnEmptyNodes.emplace_back(key.second, data.hash);
|
||||
// we'll run a second pass to clean them up
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -555,15 +599,18 @@ bool CClaimTrieCacheBase::ReadFromDisk(const CBlockIndex* tip)
|
||||
}
|
||||
}
|
||||
|
||||
CDBBatch batch(*(base->db));
|
||||
for (auto& kvp: hashesOnEmptyNodes) {
|
||||
auto hit = base->find(kvp.first);
|
||||
if (hit != base->end())
|
||||
hit->hash = kvp.second;
|
||||
for (pcursor->SeekToFirst(); pcursor->Valid(); pcursor->Next()) {
|
||||
std::pair<uint8_t, std::string> key;
|
||||
if (!pcursor->GetKey(key) || key.first != TRIE_NODE)
|
||||
continue;
|
||||
auto hit = base->find(key.second);
|
||||
if (hit) {
|
||||
CClaimTrieData data;
|
||||
if (pcursor->GetValue(data))
|
||||
hit->hash = data.hash;
|
||||
}
|
||||
else {
|
||||
// the first time the prefix trie is ran there will be many unused nodes
|
||||
// we need to clean those out so that we can go faster next time
|
||||
batch.Erase(std::make_pair(TRIE_NODE, kvp.first));
|
||||
base->db->Erase(key); // this uses a lot of memory and it's 1-time upgrade from 12.4 so we aren't going to batch it
|
||||
}
|
||||
}
|
||||
|
||||
@@ -572,7 +619,6 @@ bool CClaimTrieCacheBase::ReadFromDisk(const CBlockIndex* tip)
|
||||
LogPrintf("consistent\n");
|
||||
if (tip && tip->hashClaimTrie != getMerkleHash())
|
||||
return error("%s(): hashes don't match when reading claimtrie from disk", __func__);
|
||||
base->db->WriteBatch(batch);
|
||||
return true;
|
||||
}
|
||||
LogPrintf("inconsistent!\n");
|
||||
@@ -596,6 +642,7 @@ uint256 CClaimTrieCacheBase::recursiveComputeMerkleHash(CClaimTrie::iterator& it
|
||||
iCbType<iterator> process = [&process](iterator& it) {
|
||||
if (it->hash.IsNull())
|
||||
it->hash = recursiveMerkleHash(it, process);
|
||||
assert(!it->hash.IsNull());
|
||||
};
|
||||
process(it);
|
||||
return it->hash;
|
||||
@@ -604,31 +651,22 @@ uint256 CClaimTrieCacheBase::recursiveComputeMerkleHash(CClaimTrie::iterator& it
|
||||
uint256 CClaimTrieCacheBase::getMerkleHash()
|
||||
{
|
||||
auto it = nodesToAddOrUpdate.begin();
|
||||
if (nodesToAddOrUpdate.empty() && nodesToDelete.empty())
|
||||
if (!it && nodesToDelete.empty())
|
||||
it = base->begin();
|
||||
return !it ? one : recursiveComputeMerkleHash(it);
|
||||
}
|
||||
|
||||
CClaimTrie::const_iterator CClaimTrieCacheBase::begin() const
|
||||
{
|
||||
return nodesToAddOrUpdate.empty() && nodesToDelete.empty() ? base->cbegin() : nodesToAddOrUpdate.begin();
|
||||
}
|
||||
|
||||
CClaimTrie::const_iterator CClaimTrieCacheBase::end() const
|
||||
{
|
||||
return nodesToAddOrUpdate.empty() && nodesToDelete.empty() ? base->cend() : nodesToAddOrUpdate.end();
|
||||
}
|
||||
|
||||
CClaimTrie::const_iterator CClaimTrieCacheBase::find(const std::string& name) const
|
||||
{
|
||||
if (auto it = nodesToAddOrUpdate.find(name))
|
||||
auto it = nodesToAddOrUpdate.find(name);
|
||||
if (it || nodesToDelete.count(name))
|
||||
return it;
|
||||
return base->find(name);
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::empty() const
|
||||
{
|
||||
return base->empty() && nodesToAddOrUpdate.empty();
|
||||
return nodesToAddOrUpdate.empty(); // only used with the dump method, and we don't want to dump base
|
||||
}
|
||||
|
||||
CClaimTrie::iterator CClaimTrieCacheBase::cacheData(const std::string& name, bool create)
|
||||
@@ -712,7 +750,7 @@ bool CClaimTrieCacheBase::removeClaimFromTrie(const std::string& name, const COu
|
||||
auto it = cacheData(name, false);
|
||||
|
||||
if (!it || !it->removeClaim(outPoint, claim)) {
|
||||
LogPrint(BCLog::CLAIMS, "%s: Removing a claim was unsuccessful. name = %s, txhash = %s, nOut = %d", __func__, name, outPoint.hash.GetHex(), outPoint.n);
|
||||
LogPrint(BCLog::CLAIMS, "%s: Removing a claim was unsuccessful. name = %s, txhash = %s, nOut = %d\n", __func__, name, outPoint.hash.GetHex(), outPoint.n);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -721,11 +759,9 @@ bool CClaimTrieCacheBase::removeClaimFromTrie(const std::string& name, const COu
|
||||
it->reorderClaims(supports);
|
||||
} else {
|
||||
// in case we pull a child into our spot; we will then need their kids for hash
|
||||
bool hasChild = false;
|
||||
for (auto& child: it.children()) {
|
||||
hasChild = true;
|
||||
bool hasChild = it.hasChildren();
|
||||
for (auto& child: it.children())
|
||||
cacheData(child.key(), false);
|
||||
}
|
||||
|
||||
nodesToAddOrUpdate.erase(name);
|
||||
nodesToDelete.insert(name);
|
||||
@@ -773,11 +809,11 @@ bool CClaimTrieCacheBase::addToQueue(const std::string& name, const T& value)
|
||||
supportedType<T>();
|
||||
const auto newName = adjustNameForValidHeight(name, value.nValidAtHeight);
|
||||
auto itQueueCache = getQueueCacheRow<T>(value.nValidAtHeight, true);
|
||||
itQueueCache->second.emplace_back(newName, value);
|
||||
itQueueCache->emplace_back(newName, value);
|
||||
auto itQueueName = getQueueCacheNameRow<T>(newName, true);
|
||||
itQueueName->second.emplace_back(value.outPoint, value.nValidAtHeight);
|
||||
itQueueName->emplace_back(value.outPoint, value.nValidAtHeight);
|
||||
auto itQueueExpiration = getExpirationQueueCacheRow<T>(value.nHeight + expirationTime(), true);
|
||||
itQueueExpiration->second.emplace_back(newName, value.outPoint);
|
||||
itQueueExpiration->emplace_back(newName, value.outPoint);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -806,7 +842,7 @@ bool CClaimTrieCacheBase::undoSpend(const std::string& name, const T& value, int
|
||||
supportedType<T>();
|
||||
if (nValidAtHeight < nNextHeight) {
|
||||
auto itQueueExpiration = getExpirationQueueCacheRow<T>(value.nHeight + expirationTime(), true);
|
||||
itQueueExpiration->second.emplace_back(adjustNameForValidHeight(name, nValidAtHeight), value.outPoint);
|
||||
itQueueExpiration->emplace_back(adjustNameForValidHeight(name, nValidAtHeight), value.outPoint);
|
||||
return addToCache(name, value, false);
|
||||
}
|
||||
return addToQueue(name, value);
|
||||
@@ -831,15 +867,15 @@ template <typename T>
|
||||
bool CClaimTrieCacheBase::removeFromQueue(const std::string& name, const COutPoint& outPoint, T& value)
|
||||
{
|
||||
supportedType<T>();
|
||||
if (auto itQueueNameRow = getQueueCacheNameRow<T>(name)) {
|
||||
auto itQueueName = findOutPoint(itQueueNameRow->second, outPoint);
|
||||
if (itQueueName != itQueueNameRow->second.end()) {
|
||||
if (auto itQueueRow = getQueueCacheRow<T>(itQueueName->nHeight)) {
|
||||
auto itQueue = findOutPoint(itQueueRow->second, CNameOutPointType{name, outPoint});
|
||||
if (itQueue != itQueueRow->second.end()) {
|
||||
if (auto itQueueNameRow = getQueueCacheNameRow<T>(name, false)) {
|
||||
auto itQueueName = findOutPoint(*itQueueNameRow, outPoint);
|
||||
if (itQueueName != itQueueNameRow->end()) {
|
||||
if (auto itQueueRow = getQueueCacheRow<T>(itQueueName->nHeight, false)) {
|
||||
auto itQueue = findOutPoint(*itQueueRow, CNameOutPointType{name, outPoint});
|
||||
if (itQueue != itQueueRow->end()) {
|
||||
std::swap(value, itQueue->second);
|
||||
itQueueNameRow->second.erase(itQueueName);
|
||||
itQueueRow->second.erase(itQueue);
|
||||
itQueueNameRow->erase(itQueueName);
|
||||
itQueueRow->erase(itQueue);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -901,8 +937,8 @@ bool CClaimTrieCacheBase::remove(T& value, const std::string& name, const COutPo
|
||||
|
||||
if (removeFromQueue(adjusted, outPoint, value) || removeFromCache(name, outPoint, value, fCheckTakeover)) {
|
||||
int expirationHeight = value.nHeight + expirationTime();
|
||||
if (auto itQueueRow = getExpirationQueueCacheRow<T>(expirationHeight))
|
||||
eraseOutPoint(itQueueRow->second, CNameOutPointType{adjusted, outPoint});
|
||||
if (auto itQueueRow = getExpirationQueueCacheRow<T>(expirationHeight, false))
|
||||
eraseOutPoint(*itQueueRow, CNameOutPointType{adjusted, outPoint});
|
||||
nValidAtHeight = value.nValidAtHeight;
|
||||
return true;
|
||||
}
|
||||
@@ -1032,10 +1068,10 @@ template <typename T>
|
||||
void CClaimTrieCacheBase::undoIncrement(insertUndoType& insertUndo, std::vector<queueEntryType<T>>& expireUndo, std::set<T>* deleted)
|
||||
{
|
||||
supportedType<T>();
|
||||
if (auto itQueueRow = getQueueCacheRow<T>(nNextHeight)) {
|
||||
for (const auto& itEntry : itQueueRow->second) {
|
||||
if (auto itQueueNameRow = getQueueCacheNameRow<T>(itEntry.first)) {
|
||||
auto& points = itQueueNameRow->second;
|
||||
if (auto itQueueRow = getQueueCacheRow<T>(nNextHeight, false)) {
|
||||
for (const auto& itEntry : *itQueueRow) {
|
||||
if (auto itQueueNameRow = getQueueCacheNameRow<T>(itEntry.first, false)) {
|
||||
auto& points = *itQueueNameRow;
|
||||
auto itQueueName = std::find_if(points.begin(), points.end(), [&itEntry, this](const COutPointHeightType& point) {
|
||||
return point.outPoint == itEntry.second.outPoint && point.nHeight == nNextHeight;
|
||||
});
|
||||
@@ -1044,7 +1080,7 @@ void CClaimTrieCacheBase::undoIncrement(insertUndoType& insertUndo, std::vector<
|
||||
} else {
|
||||
LogPrintf("%s: An inconsistency was found in the queue. Please report this to the developers:\nFound in height queue but not in named queue: name: %s, txid: %s, nOut: %d, nValidAtHeight: %d, current height: %d\n", __func__, itEntry.first, itEntry.second.outPoint.hash.GetHex(), itEntry.second.outPoint.n, itEntry.second.nValidAtHeight, nNextHeight);
|
||||
LogPrintf("Elements found for that name:\n");
|
||||
for (const auto& itQueueNameInner : itQueueNameRow->second)
|
||||
for (const auto& itQueueNameInner : points)
|
||||
LogPrintf("\ttxid: %s, nOut: %d, nValidAtHeight: %d\n", itQueueNameInner.outPoint.hash.GetHex(), itQueueNameInner.outPoint.n, itQueueNameInner.nHeight);
|
||||
assert(false);
|
||||
}
|
||||
@@ -1055,17 +1091,17 @@ void CClaimTrieCacheBase::undoIncrement(insertUndoType& insertUndo, std::vector<
|
||||
addToCache(itEntry.first, itEntry.second, true);
|
||||
insertUndo.emplace_back(itEntry.first, itEntry.second.outPoint, itEntry.second.nValidAtHeight);
|
||||
}
|
||||
itQueueRow->second.clear();
|
||||
itQueueRow->clear();
|
||||
}
|
||||
|
||||
if (auto itExpirationRow = getExpirationQueueCacheRow<T>(nNextHeight)) {
|
||||
for (const auto& itEntry : itExpirationRow->second) {
|
||||
if (auto itExpirationRow = getExpirationQueueCacheRow<T>(nNextHeight, false)) {
|
||||
for (const auto& itEntry : *itExpirationRow) {
|
||||
T value;
|
||||
assert(removeFromCache(itEntry.name, itEntry.outPoint, value, true));
|
||||
expireUndo.emplace_back(itEntry.name, value);
|
||||
addTo(deleted, value);
|
||||
}
|
||||
itExpirationRow->second.clear();
|
||||
itExpirationRow->clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1073,12 +1109,12 @@ template <typename T>
|
||||
void CClaimTrieCacheBase::undoIncrement(const std::string& name, insertUndoType& insertUndo, std::vector<queueEntryType<T>>& expireUndo)
|
||||
{
|
||||
supportedType<T>();
|
||||
if (auto itQueueNameRow = getQueueCacheNameRow<T>(name)) {
|
||||
for (const auto& itQueueName : itQueueNameRow->second) {
|
||||
if (auto itQueueNameRow = getQueueCacheNameRow<T>(name, false)) {
|
||||
for (const auto& itQueueName : *itQueueNameRow) {
|
||||
bool found = false;
|
||||
// Pull those claims out of the height-based queue
|
||||
if (auto itQueueRow = getQueueCacheRow<T>(itQueueName.nHeight)) {
|
||||
auto& points = itQueueRow->second;
|
||||
if (auto itQueueRow = getQueueCacheRow<T>(itQueueName.nHeight, false)) {
|
||||
auto& points = *itQueueRow;
|
||||
auto itQueue = std::find_if(points.begin(), points.end(), [&name, &itQueueName](const queueEntryType<T>& point) {
|
||||
return name == point.first && point.second.outPoint == itQueueName.outPoint && point.second.nValidAtHeight == itQueueName.nHeight;
|
||||
});
|
||||
@@ -1098,7 +1134,7 @@ void CClaimTrieCacheBase::undoIncrement(const std::string& name, insertUndoType&
|
||||
assert(found);
|
||||
}
|
||||
// remove all claims from the queue for that name
|
||||
itQueueNameRow->second.clear();
|
||||
itQueueNameRow->clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1194,12 +1230,13 @@ void CClaimTrieCacheBase::undoDecrement(insertUndoType& insertUndo, std::vector<
|
||||
{
|
||||
supportedType<T>();
|
||||
if (!expireUndo.empty()) {
|
||||
auto itExpireRow = getExpirationQueueCacheRow<T>(nNextHeight, true);
|
||||
for (auto itExpireUndo = expireUndo.crbegin(); itExpireUndo != expireUndo.crend(); ++itExpireUndo) {
|
||||
addToCache(itExpireUndo->first, itExpireUndo->second, false);
|
||||
addToIndex(index, itExpireUndo->first, itExpireUndo->second);
|
||||
if (nNextHeight == itExpireUndo->second.nHeight + expirationTime())
|
||||
itExpireRow->second.emplace_back(itExpireUndo->first, itExpireUndo->second.outPoint);
|
||||
if (nNextHeight == itExpireUndo->second.nHeight + expirationTime()) {
|
||||
auto itExpireRow = getExpirationQueueCacheRow<T>(nNextHeight, true);
|
||||
itExpireRow->emplace_back(itExpireUndo->first, itExpireUndo->second.outPoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1212,8 +1249,8 @@ void CClaimTrieCacheBase::undoDecrement(insertUndoType& insertUndo, std::vector<
|
||||
value.nValidAtHeight = itInsertUndo->nHeight;
|
||||
auto itQueueRow = getQueueCacheRow<T>(itInsertUndo->nHeight, true);
|
||||
auto itQueueNameRow = getQueueCacheNameRow<T>(itInsertUndo->name, true);
|
||||
itQueueRow->second.emplace_back(itInsertUndo->name, value);
|
||||
itQueueNameRow->second.emplace_back(itInsertUndo->outPoint, value.nValidAtHeight);
|
||||
itQueueRow->emplace_back(itInsertUndo->name, value);
|
||||
itQueueNameRow->emplace_back(itInsertUndo->outPoint, value.nValidAtHeight);
|
||||
} else {
|
||||
addTo(deleted, value);
|
||||
}
|
||||
@@ -1226,7 +1263,6 @@ bool CClaimTrieCacheBase::decrementBlock(insertUndoType& insertUndo, claimQueueR
|
||||
|
||||
undoDecrement(insertSupportUndo, expireSupportUndo);
|
||||
undoDecrement(insertUndo, expireUndo, &claimsToAddToByIdIndex, &claimsToDeleteFromByIdIndex);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1253,13 +1289,13 @@ void CClaimTrieCacheBase::reactivate(const expirationQueueRowType& row, int heig
|
||||
supportedType<T>();
|
||||
for (auto& e: row) {
|
||||
// remove and insert with new expiration time
|
||||
if (auto itQueueRow = getExpirationQueueCacheRow<T>(height))
|
||||
eraseOutPoint(itQueueRow->second, CNameOutPointType{e.name, e.outPoint});
|
||||
if (auto itQueueRow = getExpirationQueueCacheRow<T>(height, false))
|
||||
eraseOutPoint(*itQueueRow, CNameOutPointType{e.name, e.outPoint});
|
||||
|
||||
int extend_expiration = Params().GetConsensus().nExtendedClaimExpirationTime - Params().GetConsensus().nOriginalClaimExpirationTime;
|
||||
int new_expiration_height = increment ? height + extend_expiration : height - extend_expiration;
|
||||
auto itQueueExpiration = getExpirationQueueCacheRow<T>(new_expiration_height, true);
|
||||
itQueueExpiration->second.emplace_back(e.name, e.outPoint);
|
||||
itQueueExpiration->emplace_back(e.name, e.outPoint);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1281,8 +1317,8 @@ int CClaimTrieCacheBase::getNumBlocksOfContinuousOwnership(const std::string& na
|
||||
that->removalWorkaround.erase(hit);
|
||||
return 0;
|
||||
}
|
||||
auto it = find(name);
|
||||
return it && !it->empty() ? nNextHeight - it->nHeightOfLastTakeover : 0;
|
||||
auto it = nodesToAddOrUpdate.find(name);
|
||||
return (it || (it = base->find(name))) && !it->empty() ? nNextHeight - it->nHeightOfLastTakeover : 0;
|
||||
}
|
||||
|
||||
int CClaimTrieCacheBase::getDelayForName(const std::string& name) const
|
||||
@@ -1309,35 +1345,32 @@ std::string CClaimTrieCacheBase::adjustNameForValidHeight(const std::string& nam
|
||||
|
||||
bool CClaimTrieCacheBase::clear()
|
||||
{
|
||||
nodesToAddOrUpdate.clear();
|
||||
claimsToAddToByIdIndex.clear();
|
||||
supportCache.clear();
|
||||
nodesToDelete.clear();
|
||||
claimsToDeleteFromByIdIndex.clear();
|
||||
takeoverCache.clear();
|
||||
claimQueueCache.clear();
|
||||
supportQueueCache.clear();
|
||||
removalWorkaround.clear();
|
||||
nodesToAddOrUpdate.clear();
|
||||
nodesAlreadyCached.clear();
|
||||
takeoverWorkaround.clear();
|
||||
removalWorkaround.clear();
|
||||
claimQueueNameCache.clear();
|
||||
expirationQueueCache.clear();
|
||||
supportQueueNameCache.clear();
|
||||
claimsToAddToByIdIndex.clear();
|
||||
namesToCheckForTakeover.clear();
|
||||
supportExpirationQueueCache.clear();
|
||||
claimsToDeleteFromByIdIndex.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::getProofForName(const std::string& name, CClaimTrieProof& proof)
|
||||
{
|
||||
COutPoint outPoint;
|
||||
// cache the parent nodes
|
||||
cacheData(name, false);
|
||||
getMerkleHash();
|
||||
bool fNameHasValue = false;
|
||||
int nHeightOfLastTakeover = 0;
|
||||
std::vector<CClaimTrieProofNode> nodes;
|
||||
for (const auto& it : nodesToAddOrUpdate.nodes(name)) {
|
||||
proof = CClaimTrieProof();
|
||||
for (auto& it : static_cast<const CClaimTrie&>(nodesToAddOrUpdate).nodes(name)) {
|
||||
CClaimValue claim;
|
||||
const auto& key = it.key();
|
||||
bool fNodeHasValue = it->getBestClaim(claim);
|
||||
@@ -1347,13 +1380,13 @@ bool CClaimTrieCacheBase::getProofForName(const std::string& name, CClaimTriePro
|
||||
|
||||
const auto pos = key.size();
|
||||
std::vector<std::pair<unsigned char, uint256>> children;
|
||||
for (const auto& child : it.children()) {
|
||||
auto childKey = child.key();
|
||||
for (auto& child : it.children()) {
|
||||
auto& childKey = child.key();
|
||||
if (name.find(childKey) == 0) {
|
||||
for (auto i = pos; i + 1 < childKey.size(); ++i) {
|
||||
children.emplace_back(childKey[i], uint256{});
|
||||
nodes.emplace_back(std::move(children), fNodeHasValue, valueHash);
|
||||
children.clear(); // move promises to leave it in a valid state only
|
||||
proof.nodes.emplace_back(children, fNodeHasValue, valueHash);
|
||||
children.clear();
|
||||
valueHash.SetNull();
|
||||
fNodeHasValue = false;
|
||||
}
|
||||
@@ -1365,15 +1398,34 @@ bool CClaimTrieCacheBase::getProofForName(const std::string& name, CClaimTriePro
|
||||
children.emplace_back(childKey[pos], hash);
|
||||
}
|
||||
if (key == name) {
|
||||
fNameHasValue = fNodeHasValue;
|
||||
if (fNameHasValue) {
|
||||
outPoint = claim.outPoint;
|
||||
nHeightOfLastTakeover = it->nHeightOfLastTakeover;
|
||||
proof.hasValue = fNodeHasValue;
|
||||
if (proof.hasValue) {
|
||||
proof.outPoint = claim.outPoint;
|
||||
proof.nHeightOfLastTakeover = it->nHeightOfLastTakeover;
|
||||
}
|
||||
valueHash.SetNull();
|
||||
}
|
||||
nodes.emplace_back(std::move(children), fNodeHasValue, valueHash);
|
||||
proof.nodes.emplace_back(std::move(children), fNodeHasValue, valueHash);
|
||||
}
|
||||
proof = CClaimTrieProof(std::move(nodes), fNameHasValue, outPoint, nHeightOfLastTakeover);
|
||||
return true;
|
||||
}
|
||||
|
||||
void CClaimTrieCacheBase::iterate(std::function<void(const std::string&, const CClaimTrieData&)> callback) const
|
||||
{
|
||||
if (nodesToAddOrUpdate.empty()) {
|
||||
for (auto it = base->cbegin(); it != base->cend(); ++it)
|
||||
if (!nodesToDelete.count(it.key()))
|
||||
callback(it.key(), it.data());
|
||||
return;
|
||||
}
|
||||
for (auto it = nodesToAddOrUpdate.begin(); it != nodesToAddOrUpdate.end(); ++it) {
|
||||
callback(it.key(), it.data());
|
||||
if (it.hasChildren() || nodesToDelete.count(it.key()))
|
||||
continue;
|
||||
auto children = base->find(it.key()).children();
|
||||
for (auto& child : children)
|
||||
for (; child; ++child)
|
||||
if (!nodesToDelete.count(child.key()))
|
||||
callback(child.key(), child.data());
|
||||
}
|
||||
}
|
||||
+177
-63
@@ -19,10 +19,11 @@
|
||||
|
||||
// leveldb keys
|
||||
#define TRIE_NODE 'n'
|
||||
#define TRIE_NODE_CHILDREN 'b'
|
||||
#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 +35,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;
|
||||
|
||||
@@ -91,9 +92,9 @@ struct CSupportValue
|
||||
{
|
||||
COutPoint outPoint;
|
||||
uint160 supportedClaimId;
|
||||
CAmount nAmount;
|
||||
int nHeight;
|
||||
int nValidAtHeight;
|
||||
CAmount nAmount = 0;
|
||||
int nHeight = 0;
|
||||
int nValidAtHeight = 0;
|
||||
|
||||
CSupportValue() = default;
|
||||
|
||||
@@ -191,7 +192,7 @@ struct CClaimTrieData
|
||||
struct COutPointHeightType
|
||||
{
|
||||
COutPoint outPoint;
|
||||
int nHeight;
|
||||
int nHeight = 0;
|
||||
|
||||
COutPointHeightType() = default;
|
||||
|
||||
@@ -214,7 +215,7 @@ struct CNameOutPointHeightType
|
||||
{
|
||||
std::string name;
|
||||
COutPoint outPoint;
|
||||
int nHeight;
|
||||
int nHeight = 0;
|
||||
|
||||
CNameOutPointHeightType() = default;
|
||||
|
||||
@@ -283,35 +284,73 @@ 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;
|
||||
};
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
class CClaimTrie : public CPrefixTrie<std::string, CClaimTrieData>
|
||||
{
|
||||
int nNextHeight = 0;
|
||||
int nProportionalDelayFactor = 0;
|
||||
std::unique_ptr<CDBWrapper> db;
|
||||
|
||||
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 +361,17 @@ 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;
|
||||
CAmount getTotalValueOfClaimsInTrie(bool fControllingOnly) const;
|
||||
|
||||
protected:
|
||||
int nNextHeight = 0;
|
||||
int nProportionalDelayFactor = 0;
|
||||
std::unique_ptr<CDBWrapper> db;
|
||||
};
|
||||
|
||||
struct CClaimTrieProofNode
|
||||
@@ -344,21 +394,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 +483,17 @@ 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 checkConsistency() 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 +523,24 @@ 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;
|
||||
|
||||
CClaimTrie::const_iterator begin() const;
|
||||
CClaimTrie::const_iterator end() const;
|
||||
CClaimTrie::const_iterator find(const std::string& name) const;
|
||||
void iterate(std::function<void(const std::string&, const CClaimTrieData&)> callback) const;
|
||||
|
||||
void dumpToLog(CClaimTrie::const_iterator it, bool diffFromBase = true) const;
|
||||
virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const;
|
||||
|
||||
protected:
|
||||
CClaimTrie* base;
|
||||
CClaimTrie 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(CClaimTrie::iterator& it);
|
||||
virtual bool recursiveCheckConsistency(CClaimTrie::const_iterator& it, std::string& failed) const;
|
||||
|
||||
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,8 +548,6 @@ 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;
|
||||
@@ -496,7 +582,6 @@ 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;
|
||||
|
||||
@@ -511,16 +596,25 @@ private:
|
||||
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);
|
||||
void insertRowsFromQueue(std::vector<T>& result, const std::string& name) const;
|
||||
|
||||
template <typename T>
|
||||
typename queueNameType::value_type* getQueueCacheNameRow(const std::string& name, bool createIfNotExists = false);
|
||||
std::vector<queueEntryType<T>>* getQueueCacheRow(int nHeight, bool createIfNotExists);
|
||||
|
||||
template <typename T>
|
||||
typename expirationQueueType::value_type* getExpirationQueueCacheRow(int nHeight, bool createIfNotExists = false);
|
||||
COptional<const std::vector<queueEntryType<T>>> getQueueCacheRow(int nHeight) const;
|
||||
|
||||
template <typename T>
|
||||
bool haveInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight);
|
||||
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 +662,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 +708,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 +720,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 +731,26 @@ 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;
|
||||
|
||||
bool allowSupportMetadata() const;
|
||||
|
||||
protected:
|
||||
uint256 recursiveComputeMerkleHash(CClaimTrie::iterator& it) override;
|
||||
bool recursiveCheckConsistency(CClaimTrie::const_iterator& it, std::string& failed) const override;
|
||||
|
||||
private:
|
||||
void copyAllBaseToCache();
|
||||
};
|
||||
|
||||
typedef CClaimTrieCacheHashFork CClaimTrieCache;
|
||||
|
||||
#endif // BITCOIN_CLAIMTRIE_H
|
||||
+259
-18
@@ -1,13 +1,14 @@
|
||||
|
||||
#include <consensus/merkle.h>
|
||||
#include <chainparams.h>
|
||||
#include <claimtrie.h>
|
||||
#include <hash.h>
|
||||
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <boost/foreach.hpp>
|
||||
#include <boost/locale.hpp>
|
||||
#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 +44,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 +78,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 +172,43 @@ 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) {
|
||||
for (auto it = base->cbegin(); it != base->cend(); ++it) {
|
||||
const std::string normalized = normalizeClaimName(it.key(), true);
|
||||
if (normalized == it.key())
|
||||
continue;
|
||||
|
||||
auto supports = getSupportsForName(it.key());
|
||||
auto& name = it.key();
|
||||
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 +239,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 +253,229 @@ 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 TIterator>
|
||||
uint256 recursiveBinaryTreeHash(TIterator& it, const iCbType<TIterator>& process)
|
||||
{
|
||||
std::vector<uint256> childHashes;
|
||||
for (auto& child : it.children())
|
||||
childHashes.emplace_back(process(child));
|
||||
|
||||
std::vector<uint256> claimHashes;
|
||||
if (!it->empty())
|
||||
claimHashes = getClaimHashes(it.data());
|
||||
else if (!it.hasChildren())
|
||||
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());
|
||||
}
|
||||
|
||||
uint256 CClaimTrieCacheHashFork::recursiveComputeMerkleHash(CClaimTrie::iterator& it)
|
||||
{
|
||||
if (nNextHeight < Params().GetConsensus().nAllClaimsInMerkleForkHeight)
|
||||
return CClaimTrieCacheNormalizationFork::recursiveComputeMerkleHash(it);
|
||||
|
||||
using iterator = CClaimTrie::iterator;
|
||||
iCbType<iterator> process = [&process](iterator& it) -> uint256 {
|
||||
if (it->hash.IsNull())
|
||||
it->hash = recursiveBinaryTreeHash(it, process);
|
||||
assert(!it->hash.IsNull());
|
||||
return it->hash;
|
||||
};
|
||||
return process(it);
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheHashFork::recursiveCheckConsistency(CClaimTrie::const_iterator& it, std::string& failed) const
|
||||
{
|
||||
if (nNextHeight < Params().GetConsensus().nAllClaimsInMerkleForkHeight)
|
||||
return CClaimTrieCacheNormalizationFork::recursiveCheckConsistency(it, failed);
|
||||
|
||||
struct CRecursiveBreak {};
|
||||
using iterator = CClaimTrie::const_iterator;
|
||||
iCbType<iterator> process = [&failed, &process](iterator& it) -> uint256 {
|
||||
if (it->hash.IsNull() || it->hash != recursiveBinaryTreeHash(it, process)) {
|
||||
failed = it.key();
|
||||
throw CRecursiveBreak();
|
||||
}
|
||||
return it->hash;
|
||||
};
|
||||
|
||||
try {
|
||||
process(it);
|
||||
} catch (const CRecursiveBreak&) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
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 CClaimTrie&>(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()
|
||||
{
|
||||
for (auto it = base->cbegin(); it != base->cend(); ++it)
|
||||
if (nodesAlreadyCached.insert(it.key()).second)
|
||||
nodesToAddOrUpdate.insert(it.key(), it.data());
|
||||
|
||||
for (auto it = nodesToAddOrUpdate.begin(); it != nodesToAddOrUpdate.end(); ++it)
|
||||
it->hash.SetNull();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheHashFork::allowSupportMetadata() const
|
||||
{
|
||||
return nNextHeight >= Params().GetConsensus().nAllClaimsInMerkleForkHeight;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+32
-14
@@ -15,6 +15,7 @@
|
||||
#include <util.h>
|
||||
#include <utilmoneystr.h>
|
||||
#include <utilstrencodings.h>
|
||||
#include <nameclaim.h>
|
||||
|
||||
UniValue ValueFromAmount(const CAmount& amount)
|
||||
{
|
||||
@@ -147,12 +148,20 @@ void ScriptToUniv(const CScript& script, UniValue& out, bool include_address)
|
||||
out.pushKV("hex", HexStr(script.begin(), script.end()));
|
||||
|
||||
std::vector<std::vector<unsigned char>> solns;
|
||||
txnouttype type;
|
||||
Solver(script, type, solns);
|
||||
out.pushKV("type", GetTxnOutputType(type));
|
||||
txnouttype type; int claimOp;
|
||||
auto stripped = StripClaimScriptPrefix(script, claimOp);
|
||||
Solver(stripped, type, solns);
|
||||
if (claimOp >= 0) {
|
||||
out.pushKV("isclaim", UniValue(claimOp == OP_CLAIM_NAME || claimOp == OP_UPDATE_CLAIM));
|
||||
out.pushKV("issupport", UniValue(claimOp == OP_SUPPORT_CLAIM));
|
||||
out.pushKV("subtype", GetTxnOutputType(type));
|
||||
out.pushKV("type", GetTxnOutputType(TX_NONSTANDARD)); // trying to keep backwards compatibility
|
||||
}
|
||||
else
|
||||
out.pushKV("type", GetTxnOutputType(type)); // trying to keep backwards compatibility
|
||||
|
||||
CTxDestination address;
|
||||
if (include_address && ExtractDestination(script, address)) {
|
||||
if (include_address && ExtractDestination(stripped, address)) {
|
||||
out.pushKV("address", EncodeDestination(address));
|
||||
}
|
||||
}
|
||||
@@ -168,19 +177,28 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey,
|
||||
if (fIncludeHex)
|
||||
out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
|
||||
|
||||
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
|
||||
int claimOp;
|
||||
auto stripped = StripClaimScriptPrefix(scriptPubKey, claimOp);
|
||||
auto extracted = ExtractDestinations(stripped, type, addresses, nRequired);
|
||||
if (extracted)
|
||||
out.pushKV("reqSigs", nRequired);
|
||||
|
||||
if (claimOp >= 0) {
|
||||
out.pushKV("isclaim", UniValue(claimOp == OP_CLAIM_NAME || claimOp == OP_UPDATE_CLAIM));
|
||||
out.pushKV("issupport", UniValue(claimOp == OP_SUPPORT_CLAIM));
|
||||
out.pushKV("subtype", GetTxnOutputType(type));
|
||||
out.pushKV("type", GetTxnOutputType(TX_NONSTANDARD));
|
||||
}
|
||||
else
|
||||
out.pushKV("type", GetTxnOutputType(type));
|
||||
return;
|
||||
}
|
||||
|
||||
out.pushKV("reqSigs", nRequired);
|
||||
out.pushKV("type", GetTxnOutputType(type));
|
||||
|
||||
UniValue a(UniValue::VARR);
|
||||
for (const CTxDestination& addr : addresses) {
|
||||
a.push_back(EncodeDestination(addr));
|
||||
if (extracted) {
|
||||
UniValue a(UniValue::VARR);
|
||||
for (const CTxDestination &addr : addresses) {
|
||||
a.push_back(EncodeDestination(addr));
|
||||
}
|
||||
out.pushKV("addresses", a);
|
||||
}
|
||||
out.pushKV("addresses", a);
|
||||
}
|
||||
|
||||
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags)
|
||||
|
||||
+14
-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,8 +181,16 @@ CDBWrapper::~CDBWrapper()
|
||||
options.env = nullptr;
|
||||
}
|
||||
|
||||
bool CDBWrapper::Sync() {
|
||||
CDBBatch batch(*this);
|
||||
return WriteBatch(batch, true);
|
||||
}
|
||||
|
||||
bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
|
||||
{
|
||||
if (!pdb)
|
||||
return false;
|
||||
|
||||
const bool log_memory = LogAcceptCategory(BCLog::LEVELDB);
|
||||
double mem_before = 0;
|
||||
if (log_memory) {
|
||||
|
||||
+102
-104
@@ -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.
|
||||
@@ -222,7 +151,7 @@ public:
|
||||
* with a zero'd byte array.
|
||||
*/
|
||||
CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory = false, bool fWipe = false, bool obfuscate = false);
|
||||
~CDBWrapper();
|
||||
virtual ~CDBWrapper();
|
||||
|
||||
CDBWrapper(const CDBWrapper&) = delete;
|
||||
/* CDBWrapper& operator=(const CDBWrapper&) = delete; */
|
||||
@@ -230,13 +159,13 @@ 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);
|
||||
assert(ssKey.empty());
|
||||
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 +183,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 +204,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 +217,7 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Sync()
|
||||
{
|
||||
CDBBatch batch(*this);
|
||||
return WriteBatch(batch, true);
|
||||
}
|
||||
bool Sync();
|
||||
|
||||
CDBIterator *NewIterator()
|
||||
{
|
||||
@@ -319,8 +233,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 +252,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 +263,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
|
||||
@@ -28,6 +28,8 @@ protected:
|
||||
DB(const fs::path& path, size_t n_cache_size,
|
||||
bool f_memory = false, bool f_wipe = false, bool f_obfuscate = false);
|
||||
|
||||
~DB() override {}
|
||||
|
||||
/// Read block locator of the chain that the txindex is in sync with.
|
||||
bool ReadBestBlock(CBlockLocator& locator) const;
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ class TxIndex::DB : public BaseIndex::DB
|
||||
{
|
||||
public:
|
||||
explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false);
|
||||
~DB() override {}
|
||||
|
||||
/// Read the disk location of the transaction data with the given hash. Returns false if the
|
||||
/// transaction hash is not indexed.
|
||||
|
||||
+9
-1
@@ -22,6 +22,7 @@
|
||||
#include <httprpc.h>
|
||||
#include <index/txindex.h>
|
||||
#include <key.h>
|
||||
#include <lbry.h>
|
||||
#include <validation.h>
|
||||
#include <miner.h>
|
||||
#include <netbase.h>
|
||||
@@ -370,6 +371,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);
|
||||
@@ -397,6 +399,7 @@ void SetupServerArgs()
|
||||
hidden_args.emplace_back("-sysperms");
|
||||
#endif
|
||||
gArgs.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), false, OptionsCategory::OPTIONS);
|
||||
gArgs.AddArg("-memfile=<GiB>", "Use a memory mapped file for the claimtrie allocations (default: use RAM instead)", false, OptionsCategory::OPTIONS);
|
||||
|
||||
gArgs.AddArg("-addnode=<ip>", "Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.", false, OptionsCategory::CONNECTION);
|
||||
gArgs.AddArg("-banscore=<n>", strprintf("Threshold for disconnecting misbehaving peers (default: %u)", DEFAULT_BANSCORE_THRESHOLD), false, OptionsCategory::CONNECTION);
|
||||
@@ -1440,6 +1443,8 @@ bool AppInitMain()
|
||||
LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
|
||||
LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
|
||||
|
||||
g_memfileSize = gArgs.GetArg("-memfile", 0u);
|
||||
|
||||
bool fLoaded = false;
|
||||
while (!fLoaded && !ShutdownRequested()) {
|
||||
bool fReset = fReindex;
|
||||
@@ -1461,7 +1466,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 CClaimTrie(false, fReindex || fReindexChainState, 32, trieCacheMB);
|
||||
|
||||
if (fReset) {
|
||||
pblocktree->WriteReindexing(true);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
uint32_t g_memfileSize = 0;
|
||||
|
||||
unsigned int CalculateLbryNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
|
||||
{
|
||||
if (params.fPowNoRetargeting)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <chain.h>
|
||||
#include <chainparams.h>
|
||||
|
||||
extern uint32_t g_memfileSize;
|
||||
unsigned int CalculateLbryNextWorkRequired(const CBlockIndex* pindexLast, int64_t nLastRetargetTime, const Consensus::Params& params);
|
||||
|
||||
#endif
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -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,8 +207,8 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
|
||||
|
||||
CValidationState state;
|
||||
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
|
||||
if (!trieCache.empty() && trieCache.checkConsistency())
|
||||
trieCache.dumpToLog(trieCache.begin());
|
||||
if (!trieCache.empty())
|
||||
trieCache.dumpToLog(trieCache.find({}));
|
||||
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
|
||||
}
|
||||
int64_t nTime2 = GetTimeMicros();
|
||||
|
||||
+38
-22
@@ -1,9 +1,6 @@
|
||||
#include <boost/foreach.hpp>
|
||||
#include "nameclaim.h"
|
||||
#include "hash.h"
|
||||
#include "util.h"
|
||||
#include "claimtrie.h"
|
||||
|
||||
|
||||
std::vector<unsigned char> uint32_t_to_vch(uint32_t n)
|
||||
{
|
||||
@@ -21,25 +18,35 @@ uint32_t vch_to_uint32_t(std::vector<unsigned char>& vchN)
|
||||
uint32_t n;
|
||||
static const size_t uint32Size = sizeof(uint32_t);
|
||||
if (vchN.size() != uint32Size) {
|
||||
LogPrintf("%s() : a vector<unsigned char> with size other than 4 has been given", __func__);
|
||||
LogPrintf("%s() : a vector<unsigned char> with size other than 4 has been given\n", __func__);
|
||||
return 0;
|
||||
}
|
||||
n = vchN[0] << 24 | vchN[1] << 16 | vchN[2] << 8 | vchN[3];
|
||||
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, std::string value, 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;
|
||||
CScript ret;
|
||||
if (value.empty())
|
||||
ret = CScript() << OP_SUPPORT_CLAIM << vchName << vchClaimId << OP_2DROP << OP_DROP;
|
||||
else {
|
||||
std::vector<unsigned char> vchValue(value.begin(), value.end());
|
||||
ret = CScript() << OP_SUPPORT_CLAIM << vchName << vchClaimId << vchValue << OP_2DROP << OP_2DROP;
|
||||
}
|
||||
if (fakeSuffix) ret.push_back(OP_TRUE);
|
||||
return ret;
|
||||
}
|
||||
|
||||
CScript UpdateClaimScript(std::string name, uint160 claimId, std::string value)
|
||||
@@ -50,14 +57,15 @@ CScript UpdateClaimScript(std::string name, uint160 claimId, std::string value)
|
||||
return CScript() << OP_UPDATE_CLAIM << vchName << vchClaimId << vchValue << OP_2DROP << OP_2DROP << OP_TRUE;
|
||||
}
|
||||
|
||||
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, bool allowSupportMetadata)
|
||||
{
|
||||
CScript::const_iterator pc = scriptIn.begin();
|
||||
return DecodeClaimScript(scriptIn, op, vvchParams, pc);
|
||||
return DecodeClaimScript(scriptIn, op, vvchParams, pc, allowSupportMetadata);
|
||||
}
|
||||
|
||||
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams, CScript::const_iterator& pc)
|
||||
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams, CScript::const_iterator& pc, bool allowSupportMetadata)
|
||||
{
|
||||
op = -1;
|
||||
opcodetype opcode;
|
||||
if (!scriptIn.GetOp(pc, opcode))
|
||||
{
|
||||
@@ -78,6 +86,7 @@ bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector
|
||||
// OP_CLAIM_NAME vchName vchValue OP_2DROP OP_DROP pubkeyscript
|
||||
// OP_UPDATE_CLAIM vchName vchClaimId vchValue OP_2DROP OP_2DROP pubkeyscript
|
||||
// OP_SUPPORT_CLAIM vchName vchClaimId OP_2DROP OP_DROP pubkeyscript
|
||||
// OP_SUPPORT_CLAIM vchName vchClaimId vchValue OP_2DROP OP_2DROP pubkeyscript
|
||||
// All others are invalid.
|
||||
|
||||
if (!scriptIn.GetOp(pc, opcode, vchParam1) || opcode < 0 || opcode > OP_PUSHDATA4)
|
||||
@@ -95,35 +104,42 @@ bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (op == OP_UPDATE_CLAIM)
|
||||
|
||||
if (!scriptIn.GetOp(pc, opcode, vchParam3))
|
||||
{
|
||||
if (!scriptIn.GetOp(pc, opcode, vchParam3) || opcode < 0 || opcode > OP_PUSHDATA4)
|
||||
return false;
|
||||
}
|
||||
auto last_drop = OP_DROP;
|
||||
if (opcode >= 0 && opcode <= OP_PUSHDATA4 && op != OP_CLAIM_NAME)
|
||||
{
|
||||
if (!scriptIn.GetOp(pc, opcode))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
last_drop = OP_2DROP;
|
||||
}
|
||||
if (!scriptIn.GetOp(pc, opcode) || opcode != OP_2DROP)
|
||||
else if (op == OP_UPDATE_CLAIM)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!scriptIn.GetOp(pc, opcode))
|
||||
if (opcode != OP_2DROP)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if ((op == OP_CLAIM_NAME || op == OP_SUPPORT_CLAIM) && opcode != OP_DROP)
|
||||
if (!scriptIn.GetOp(pc, opcode) || opcode != last_drop)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if ((op == OP_UPDATE_CLAIM) && opcode != OP_2DROP)
|
||||
if (op == OP_SUPPORT_CLAIM && last_drop == OP_2DROP && !allowSupportMetadata)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
vvchParams.push_back(vchParam1);
|
||||
vvchParams.push_back(vchParam2);
|
||||
if (op == OP_UPDATE_CLAIM)
|
||||
vvchParams.push_back(std::move(vchParam1));
|
||||
vvchParams.push_back(std::move(vchParam2));
|
||||
if (last_drop == OP_2DROP)
|
||||
{
|
||||
vvchParams.push_back(vchParam3);
|
||||
vvchParams.push_back(std::move(vchParam3));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -184,7 +200,7 @@ CAmount CalcMinClaimTrieFee(const CTransaction& tx, const CAmount &minFeePerName
|
||||
}
|
||||
|
||||
CAmount min_fee = 0;
|
||||
BOOST_FOREACH(const CTxOut& txout, tx.vout)
|
||||
for (const CTxOut& txout: tx.vout)
|
||||
{
|
||||
int op;
|
||||
std::vector<std::vector<unsigned char> > vvchParams;
|
||||
|
||||
+5
-5
@@ -11,7 +11,7 @@
|
||||
// This is the minimum claim fee per character in the name of an OP_CLAIM_NAME command that must
|
||||
// be attached to transactions for it to be accepted into the memory pool.
|
||||
// Rationale: current implementation of the claim trie uses more memory for longer name claims
|
||||
// due to the fact that each chracater is assigned a trie node regardless of whether it contains
|
||||
// due to the fact that each character is assigned a trie node regardless of whether it contains
|
||||
// any claims or not. In the future, we can switch to a radix tree implementation where
|
||||
// empty nodes do not take up any memory and the minimum fee can be priced on a per claim
|
||||
// basis.
|
||||
@@ -25,11 +25,11 @@
|
||||
// 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, std::string value="", 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);
|
||||
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams, bool allowSupportMetadata=true);
|
||||
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams, CScript::const_iterator& pc, bool allowSupportMetadata=true);
|
||||
CScript StripClaimScriptPrefix(const CScript& scriptIn);
|
||||
CScript StripClaimScriptPrefix(const CScript& scriptIn, int& op);
|
||||
uint160 ClaimIdHash(const uint256& txhash, uint32_t nOut);
|
||||
|
||||
@@ -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(StripClaimScriptPrefix(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(StripClaimScriptPrefix(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;
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ static const unsigned int MAX_STANDARD_P2WSH_SCRIPT_SIZE = 3600;
|
||||
* standard and should be done with care and ideally rarely. It makes sense to
|
||||
* only increase the dust limit after prior releases were already not creating
|
||||
* outputs below the new threshold */
|
||||
static const unsigned int DUST_RELAY_TX_FEE = 3000;
|
||||
static const unsigned int DUST_RELAY_TX_FEE = 1000;
|
||||
/**
|
||||
* Standard script verification flags that standard transactions will comply
|
||||
* with. However scripts violating these flags may still be present in valid
|
||||
|
||||
+148
-63
@@ -1,6 +1,79 @@
|
||||
|
||||
#include "prefixtrie.h"
|
||||
#include "claimtrie.h"
|
||||
#include <claimtrie.h>
|
||||
#include <fs.h>
|
||||
#include <lbry.h>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <prefixtrie.h>
|
||||
|
||||
#include <boost/interprocess/allocators/private_node_allocator.hpp>
|
||||
#include <boost/interprocess/indexes/null_index.hpp>
|
||||
#include <boost/interprocess/managed_mapped_file.hpp>
|
||||
|
||||
namespace bip = boost::interprocess;
|
||||
|
||||
typedef bip::basic_managed_mapped_file <
|
||||
char,
|
||||
bip::rbtree_best_fit<bip::null_mutex_family, bip::offset_ptr<void>>,
|
||||
bip::null_index
|
||||
> managed_mapped_file;
|
||||
|
||||
template <typename T>
|
||||
using node_allocator = bip::private_node_allocator<T, managed_mapped_file::segment_manager>;
|
||||
|
||||
static managed_mapped_file::segment_manager* segmentManager()
|
||||
{
|
||||
struct CSharedMemoryFile
|
||||
{
|
||||
CSharedMemoryFile() : file(GetDataDir() / "shared.mem")
|
||||
{
|
||||
fs::remove(file);
|
||||
auto size = (uint64_t)g_memfileSize * 1024ULL * 1024ULL * 1024ULL;
|
||||
// using string() to remove w_char filename encoding on Windows
|
||||
menaged_file.reset(new managed_mapped_file(bip::create_only, file.string().c_str(), size));
|
||||
}
|
||||
~CSharedMemoryFile()
|
||||
{
|
||||
menaged_file.reset();
|
||||
fs::remove(file);
|
||||
}
|
||||
managed_mapped_file::segment_manager* segmentManager()
|
||||
{
|
||||
return menaged_file->get_segment_manager();
|
||||
}
|
||||
const fs::path file;
|
||||
std::unique_ptr<managed_mapped_file> menaged_file;
|
||||
};
|
||||
static CSharedMemoryFile shem;
|
||||
return shem.segmentManager();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
static node_allocator<T>& nodeAllocator()
|
||||
{
|
||||
static node_allocator<T> allocator(segmentManager());
|
||||
return allocator;
|
||||
}
|
||||
|
||||
template <typename T, class... Args>
|
||||
static std::shared_ptr<T> nodeAllocate(Args&&... args)
|
||||
{
|
||||
return std::allocate_shared<T>(nodeAllocator<T>(), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename T, class... Args>
|
||||
static std::shared_ptr<T> allocateShared(Args&&... args)
|
||||
{
|
||||
static auto allocate = g_memfileSize ? nodeAllocate<T, Args...> : std::make_shared<T, Args...>;
|
||||
try {
|
||||
return allocate(std::forward<Args>(args)...);
|
||||
}
|
||||
catch (const bip::bad_alloc&) {
|
||||
allocate = std::make_shared<T, Args...>; // in case we fill up the memfile
|
||||
LogPrint(BCLog::BENCH, "WARNING: The memfile is full; reverting to the RAM allocator for %s.\n", typeid(T).name());
|
||||
return allocate(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
@@ -18,7 +91,7 @@ typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>& CPrefixTrie<TKey,
|
||||
stack.clear();
|
||||
stack.reserve(o.stack.size());
|
||||
for (auto& i : o.stack)
|
||||
stack.push_back(Bookmark{i.name, i.parent, i.it, i.end});
|
||||
stack.push_back(Bookmark{i.name, i.it, i.end});
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -48,7 +121,7 @@ typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>& CPrefixTrie<TKey,
|
||||
if (!shared->children.empty()) {
|
||||
auto& children = shared->children;
|
||||
auto it = children.begin();
|
||||
stack.emplace_back(Bookmark{name, shared, it, children.end()});
|
||||
stack.emplace_back(Bookmark{name, it, children.end()});
|
||||
auto& postfix = it->first;
|
||||
name.insert(name.end(), postfix.begin(), postfix.end());
|
||||
node = it->second;
|
||||
@@ -106,18 +179,30 @@ bool CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator!=(const Iterator& o)
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::reference CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator*() const
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::reference CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator*()
|
||||
{
|
||||
assert(!node.expired());
|
||||
return TPair(name, *(node.lock()->data));
|
||||
return reference{name, data()};
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::pointer CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator->() const
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::const_reference CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator*() const
|
||||
{
|
||||
assert(!node.expired());
|
||||
return node.lock()->data.get();
|
||||
return const_reference{name, data()};
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::pointer CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator->()
|
||||
{
|
||||
return &(data());
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
template <bool IsConst>
|
||||
typename CPrefixTrie<TKey, TData>::template Iterator<IsConst>::const_pointer CPrefixTrie<TKey, TData>::Iterator<IsConst>::operator->() const
|
||||
{
|
||||
return &(data());
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -129,18 +214,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>::data_reference 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 +261,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 +292,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)
|
||||
{
|
||||
@@ -237,21 +327,20 @@ 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>();
|
||||
it = children.emplace(key, allocateShared<Node>()).first;
|
||||
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), allocateShared<Node>()).first;
|
||||
it->second->children.emplace(std::move(postfix), std::move(nodes));
|
||||
if (key.size() == count)
|
||||
return it->second;
|
||||
it->second->data = allocateShared<TData>();
|
||||
}
|
||||
return insert(TKey(key.begin() + count, key.end()), it->second);
|
||||
}
|
||||
@@ -268,7 +357,7 @@ void CPrefixTrie<TKey, TData>::erase(const TKey& key, std::shared_ptr<Node>& nod
|
||||
if (!find(key, node, cb))
|
||||
return;
|
||||
|
||||
nodes.back().second->data = std::make_shared<TData>();
|
||||
nodes.back().second->data = allocateShared<TData>();
|
||||
for (; nodes.size() > 1; nodes.pop_back()) {
|
||||
// if we have only one child and no data ourselves, bring them up to our level
|
||||
auto& cNode = nodes.back().second;
|
||||
@@ -281,7 +370,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;
|
||||
@@ -299,9 +388,9 @@ void CPrefixTrie<TKey, TData>::erase(const TKey& key, std::shared_ptr<Node>& nod
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
CPrefixTrie<TKey, TData>::CPrefixTrie() : size(0), root(std::make_shared<Node>())
|
||||
CPrefixTrie<TKey, TData>::CPrefixTrie() : size(0), root(allocateShared<Node>())
|
||||
{
|
||||
root->data = std::make_shared<TData>();
|
||||
root->data = allocateShared<TData>();
|
||||
}
|
||||
|
||||
template <typename TKey, typename TData>
|
||||
@@ -309,7 +398,7 @@ template <typename TDataUni>
|
||||
typename CPrefixTrie<TKey, TData>::iterator CPrefixTrie<TKey, TData>::insert(const TKey& key, TDataUni&& data)
|
||||
{
|
||||
auto& node = key.empty() ? root : insert(key, root);
|
||||
node->data = std::make_shared<TData>(std::forward<TDataUni>(data));
|
||||
node->data = allocateShared<TData>(std::forward<TDataUni>(data));
|
||||
return key.empty() ? begin() : iterator{key, node};
|
||||
}
|
||||
|
||||
@@ -333,9 +422,9 @@ typename CPrefixTrie<TKey, TData>::iterator CPrefixTrie<TKey, TData>::insert(CPr
|
||||
auto name = it.key();
|
||||
name.insert(name.end(), key.begin(), key.end());
|
||||
auto& node = insert(key, shared);
|
||||
copy = iterator{name, node};
|
||||
copy = iterator{std::move(name), node};
|
||||
}
|
||||
copy.node.lock()->data = std::make_shared<TData>(std::forward<TDataUni>(data));
|
||||
copy.node.lock()->data = allocateShared<TData>(std::forward<TDataUni>(data));
|
||||
return copy;
|
||||
}
|
||||
|
||||
@@ -386,21 +475,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>
|
||||
@@ -408,7 +493,7 @@ bool CPrefixTrie<TKey, TData>::erase(const TKey& key)
|
||||
{
|
||||
auto size_was = height();
|
||||
if (key.empty()) {
|
||||
root->data = std::make_shared<TData>();
|
||||
root->data = allocateShared<TData>();
|
||||
} else {
|
||||
erase(key, root);
|
||||
}
|
||||
@@ -419,7 +504,7 @@ template <typename TKey, typename TData>
|
||||
void CPrefixTrie<TKey, TData>::clear()
|
||||
{
|
||||
size = 0;
|
||||
root->data = std::make_shared<TData>();
|
||||
root->data = allocateShared<TData>();
|
||||
root->children.clear();
|
||||
}
|
||||
|
||||
@@ -444,7 +529,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 +541,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 +553,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;
|
||||
|
||||
+39
-10
@@ -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,13 +21,13 @@ 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;
|
||||
Node(const Node&) = delete;
|
||||
Node(Node&& o) noexcept = default;
|
||||
Node& operator=(Node&& o) noexcept = default;
|
||||
Node& operator=(Node&&) noexcept = default;
|
||||
Node& operator=(const Node&) = delete;
|
||||
std::shared_ptr<TData> data;
|
||||
};
|
||||
@@ -38,15 +42,15 @@ class CPrefixTrie
|
||||
friend class CPrefixTrie<TKey, TData>;
|
||||
|
||||
using TKeyRef = std::reference_wrapper<const TKey>;
|
||||
using TDataRef = std::reference_wrapper<TData>;
|
||||
using TDataRef = std::reference_wrapper<typename std::conditional<IsConst, const TData, TData>::type>;
|
||||
using TPair = std::pair<TKeyRef, TDataRef>;
|
||||
using ConstTPair = std::pair<TKeyRef, const TData>;
|
||||
|
||||
TKey name;
|
||||
std::weak_ptr<Node> node;
|
||||
|
||||
struct Bookmark {
|
||||
TKey name;
|
||||
std::weak_ptr<Node> parent;
|
||||
typename TChildren::iterator it;
|
||||
typename TChildren::iterator end;
|
||||
};
|
||||
@@ -56,12 +60,15 @@ class CPrefixTrie
|
||||
public:
|
||||
// Iterator traits
|
||||
using value_type = TPair;
|
||||
using const_pointer = const TData* const;
|
||||
using const_reference = ConstTPair;
|
||||
using data_reference = typename std::conditional<IsConst, const TData&, TData&>::type;
|
||||
using pointer = typename std::conditional<IsConst, const TData* const, TData* const>::type;
|
||||
using reference = typename std::conditional<IsConst, const TPair, TPair>::type;
|
||||
using reference = typename std::conditional<IsConst, ConstTPair, TPair>::type;
|
||||
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;
|
||||
@@ -85,12 +92,15 @@ class CPrefixTrie
|
||||
bool operator==(const Iterator& o) const;
|
||||
bool operator!=(const Iterator& o) const;
|
||||
|
||||
reference operator*() const;
|
||||
pointer operator->() const;
|
||||
reference operator*();
|
||||
const_reference operator*() const;
|
||||
|
||||
pointer operator->();
|
||||
const_pointer operator->() const;
|
||||
|
||||
const TKey& key() const;
|
||||
|
||||
TData& data();
|
||||
data_reference data();
|
||||
const TData& data() const;
|
||||
|
||||
std::size_t depth() const;
|
||||
@@ -111,6 +121,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);
|
||||
|
||||
@@ -136,7 +149,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 +207,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
|
||||
@@ -17,7 +17,7 @@ static const struct {
|
||||
} network_styles[] = {
|
||||
{"lbrycrd", QAPP_APP_NAME_DEFAULT, 0, 0, ""},
|
||||
{"lbrycrdtest", QAPP_APP_NAME_TESTNET, 70, 30, QT_TRANSLATE_NOOP("SplashScreen", "[testnet]")},
|
||||
{"regtest", QAPP_APP_NAME_REGTEST, 160, 30, "[regtest]"}
|
||||
{"lbrycrdreg", QAPP_APP_NAME_REGTEST, 160, 30, "[regtest]"}
|
||||
};
|
||||
static const unsigned network_styles_count = sizeof(network_styles)/sizeof(*network_styles);
|
||||
|
||||
|
||||
@@ -228,11 +228,11 @@ void PaymentServer::ipcParseCommandLine(interfaces::Node& node, int argc, char*
|
||||
PaymentRequestPlus request;
|
||||
if (readPaymentRequestFromFile(arg, request))
|
||||
{
|
||||
if (request.getDetails().network() == "lbrycrd")
|
||||
if (request.getDetails().network() == CBaseChainParams::MAIN)
|
||||
{
|
||||
node.selectParams(CBaseChainParams::MAIN);
|
||||
}
|
||||
else if (request.getDetails().network() == "lbrycrdtest")
|
||||
else if (request.getDetails().network() == CBaseChainParams::TESTNET)
|
||||
{
|
||||
node.selectParams(CBaseChainParams::TESTNET);
|
||||
}
|
||||
|
||||
+20
-7
@@ -1310,16 +1310,18 @@ static UniValue getchaintips(const JSONRPCRequest& request)
|
||||
"\nResult:\n"
|
||||
"[\n"
|
||||
" {\n"
|
||||
" \"height\": xxxx, (numeric) height of the chain tip\n"
|
||||
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
|
||||
" \"branchlen\": 0 (numeric) zero for main chain\n"
|
||||
" \"status\": \"active\" (string) \"active\" for the main chain\n"
|
||||
" \"height\": xxxx, (numeric) height of the chain tip\n"
|
||||
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
|
||||
" \"branchlen\": 0 (numeric) zero for main chain\n"
|
||||
" \"status\": \"active\" (string) \"active\" for the main chain\n"
|
||||
" },\n"
|
||||
" {\n"
|
||||
" \"height\": xxxx,\n"
|
||||
" \"hash\": \"xxxx\",\n"
|
||||
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
|
||||
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
|
||||
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
|
||||
" \"branchhash\": \"xxxx\", (string) hash of the historical block where we branched\n"
|
||||
" \"branchhashNext\": \"xxxx\", (string) block hash of the first block down this chain\n"
|
||||
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
|
||||
" }\n"
|
||||
"]\n"
|
||||
"Possible values for status:\n"
|
||||
@@ -1372,8 +1374,19 @@ static UniValue getchaintips(const JSONRPCRequest& request)
|
||||
obj.pushKV("height", block->nHeight);
|
||||
obj.pushKV("hash", block->phashBlock->GetHex());
|
||||
|
||||
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
|
||||
// not use ForkAt method because we need the previous one as well
|
||||
const CBlockIndex *forkAt = block, *forkPrev = block;
|
||||
while (forkAt && !chainActive.Contains(forkAt)) {
|
||||
forkPrev = forkAt;
|
||||
forkAt = forkAt->pprev;
|
||||
}
|
||||
|
||||
const int branchLen = block->nHeight - forkAt->nHeight;
|
||||
obj.pushKV("branchlen", branchLen);
|
||||
if (forkAt != forkPrev) {
|
||||
obj.pushKV("branchhash", forkAt->phashBlock->GetHex());
|
||||
obj.pushKV("branchhashNext", forkPrev->phashBlock->GetHex());
|
||||
}
|
||||
|
||||
std::string status;
|
||||
if (chainActive.Contains(block)) {
|
||||
|
||||
@@ -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("getclaimsintrie ( \"" T_BLOCKHASH R"(" )
|
||||
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("getnamesintrie ( \"" T_BLOCKHASH R"(" )
|
||||
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("getvalueforname \"" T_NAME "\" ( \"" T_BLOCKHASH "\" \"" T_CLAIMID R"(" )
|
||||
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("getclaimsforname \"" T_NAME "\" ( \"" T_BLOCKHASH R"(" )
|
||||
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("getclaimbyid \"" T_CLAIMID R"("
|
||||
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("gettotalvalueofclaims ( " T_CONTROLLINGONLY R"( )
|
||||
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("getclaimsfortx \"" T_TXID R"("
|
||||
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("getnameproof \"" T_NAME "\" ( \"" T_BLOCKHASH "\" \"" T_CLAIMID R"(" )
|
||||
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("checknormalization \"" T_NAME R"("
|
||||
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("getclaimbybid \"" T_NAME "\" ( " T_BID " \"" T_BLOCKHASH R"(" )
|
||||
Get a claim by bid
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_BID, " (numeric, optional) bid number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
CLAIM_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCLAIMBYSEQ
|
||||
S1("getclaimbyseq \"" T_NAME "\" ( " T_SEQUENCE " \"" T_BLOCKHASH R"(" )
|
||||
Get a claim by sequence
|
||||
Arguments:)")
|
||||
S3("1. ", T_NAME, NAME_TEXT)
|
||||
S3("2. ", T_SEQUENCE, " (numeric, optional) sequence number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
CLAIM_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCLAIMPROOFBYBID
|
||||
S1("getclaimproofbyid \"" T_NAME "\" ( " T_BID " \"" T_BLOCKHASH R"(" )
|
||||
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, optional) bid number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
PROOF_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCLAIMPROOFBYSEQ
|
||||
S1("getclaimproofbyseq \"" T_NAME "\" ( " T_SEQUENCE " \"" T_BLOCKHASH R"(" )
|
||||
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, optional) sequence number")
|
||||
S3("3. ", T_BLOCKHASH, BLOCKHASH_TEXT)
|
||||
S1("Result: [")
|
||||
PROOF_OUTPUT
|
||||
"]",
|
||||
|
||||
// GETCHANGESINBLOCK
|
||||
S1("getchangesinblock ( \"" T_BLOCKHASH R"(" )
|
||||
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
|
||||
+622
-609
File diff suppressed because it is too large.
Load diff
@@ -80,6 +80,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
|
||||
{ "scantxoutset", 1, "scanobjects" },
|
||||
{ "addmultisigaddress", 0, "nrequired" },
|
||||
{ "addmultisigaddress", 1, "keys" },
|
||||
{ "addtimelockedaddress", 0, "timelock" },
|
||||
{ "createmultisig", 0, "nrequired" },
|
||||
{ "createmultisig", 1, "keys" },
|
||||
{ "listunspent", 0, "minconf" },
|
||||
@@ -171,6 +172,15 @@ 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"},
|
||||
{ "gettotalvalueofclaims", 0, "controlling_only"},
|
||||
};
|
||||
|
||||
class CRPCConvertTable
|
||||
|
||||
+7
-6
@@ -451,7 +451,7 @@ static UniValue getblocktemplate(const JSONRPCRequest& request)
|
||||
if (strMode != "template")
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
|
||||
|
||||
if (Params().NetworkIDString() != "lbrycrdreg") // who should own this constant?
|
||||
if (Params().NetworkIDString() == CBaseChainParams::MAIN)
|
||||
{
|
||||
if (!g_connman)
|
||||
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
|
||||
@@ -585,7 +585,7 @@ static UniValue getblocktemplate(const JSONRPCRequest& request)
|
||||
|
||||
UniValue entry(UniValue::VOBJ);
|
||||
|
||||
entry.pushKV("data", EncodeHexTx(tx));
|
||||
entry.pushKV("data", EncodeHexTx(tx, fSupportsSegwit ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS));
|
||||
entry.pushKV("txid", txHash.GetHex());
|
||||
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
|
||||
|
||||
@@ -621,9 +621,6 @@ static UniValue getblocktemplate(const JSONRPCRequest& request)
|
||||
aMutable.push_back("time");
|
||||
aMutable.push_back("transactions");
|
||||
aMutable.push_back("prevblock");
|
||||
aMutable.push_back("submit/coinbase");
|
||||
|
||||
result.pushKV("capabilities", aCaps);
|
||||
|
||||
UniValue aRules(UniValue::VARR);
|
||||
UniValue vbavailable(UniValue::VOBJ);
|
||||
@@ -655,7 +652,10 @@ static UniValue getblocktemplate(const JSONRPCRequest& request)
|
||||
{
|
||||
// Add to rules only
|
||||
const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
|
||||
aRules.push_back(gbt_vb_name(pos));
|
||||
if (pos == Consensus::DEPLOYMENT_SEGWIT && !fSupportsSegwit)
|
||||
aCaps.push_back(gbt_vb_name(pos));
|
||||
else
|
||||
aRules.push_back(gbt_vb_name(pos));
|
||||
if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
|
||||
// Not supported by the client; make sure it's safe to proceed
|
||||
if (!vbinfo.gbt_force) {
|
||||
@@ -667,6 +667,7 @@ static UniValue getblocktemplate(const JSONRPCRequest& request)
|
||||
}
|
||||
}
|
||||
}
|
||||
result.pushKV("capabilities", aCaps);
|
||||
result.pushKV("version", pblock->nVersion);
|
||||
result.pushKV("rules", aRules);
|
||||
result.pushKV("vbavailable", vbavailable);
|
||||
|
||||
@@ -549,14 +549,15 @@ static UniValue decoderawtransaction(const JSONRPCRequest& request)
|
||||
" ],\n"
|
||||
" \"vout\" : [ (array of json objects)\n"
|
||||
" {\n"
|
||||
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
|
||||
" \"n\" : n, (numeric) index\n"
|
||||
" \"scriptPubKey\" : { (json object)\n"
|
||||
" \"asm\" : \"asm\", (string) the asm\n"
|
||||
" \"hex\" : \"hex\", (string) the hex\n"
|
||||
" \"reqSigs\" : n, (numeric) The required sigs\n"
|
||||
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
|
||||
" \"addresses\" : [ (json array of string)\n"
|
||||
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
|
||||
" \"n\" : n, (numeric) index\n"
|
||||
" \"scriptPubKey\" : { (json object)\n"
|
||||
" \"asm\" : \"asm\", (string) the asm\n"
|
||||
" \"hex\" : \"hex\", (string) the hex\n"
|
||||
" \"reqSigs\" : n, (numeric) The required sigs\n"
|
||||
" \"subtype\" : \"pubkeyhash\", (numeric) For claims and supports, this represents the type of suffix\n"
|
||||
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
|
||||
" \"addresses\" : [ (json array of string)\n"
|
||||
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) lbry address\n"
|
||||
" ,...\n"
|
||||
" ]\n"
|
||||
@@ -1757,7 +1758,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>
|
||||
@@ -1490,6 +1491,11 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
|
||||
return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
|
||||
}
|
||||
|
||||
int claimOp;
|
||||
const CScript& strippedScriptPubKey = StripClaimScriptPrefix(scriptPubKey, claimOp);
|
||||
if (claimOp >= 0) // lbryum used to violate this rule with an off-by-1 at len == 255 (and its not very important)
|
||||
flags &= ~SCRIPT_VERIFY_MINIMALDATA;
|
||||
|
||||
std::vector<std::vector<unsigned char> > stack, stackCopy;
|
||||
if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
|
||||
// serror is set
|
||||
@@ -1505,10 +1511,11 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
|
||||
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
|
||||
|
||||
// Bare witness programs
|
||||
|
||||
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 +1531,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;
|
||||
|
||||
@@ -133,9 +133,9 @@ const char* GetOpName(opcodetype opcode)
|
||||
case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
|
||||
case OP_NOP4 : return "OP_NOP4";
|
||||
case OP_NOP5 : return "OP_NOP5";
|
||||
case OP_NOP6 : return "OP_NOP6";
|
||||
case OP_NOP7 : return "OP_NOP7";
|
||||
case OP_NOP8 : return "OP_NOP8";
|
||||
case OP_NOP6 : return "OP_CLAIM_NAME";
|
||||
case OP_NOP7 : return "OP_SUPPORT_CLAIM";
|
||||
case OP_NOP8 : return "OP_UPDATE_CLAIM";
|
||||
case OP_NOP9 : return "OP_NOP9";
|
||||
case OP_NOP10 : return "OP_NOP10";
|
||||
|
||||
|
||||
+20
-6
@@ -6,13 +6,12 @@
|
||||
#include <script/sign.h>
|
||||
|
||||
#include <key.h>
|
||||
#include <nameclaim.h>
|
||||
#include <policy/policy.h>
|
||||
#include <primitives/transaction.h>
|
||||
#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) {}
|
||||
@@ -88,6 +87,21 @@ static bool CreateSig(const BaseSignatureCreator& creator, SignatureData& sigdat
|
||||
return false;
|
||||
}
|
||||
|
||||
static CScript StripTimelockPrefix(const CScript& script) {
|
||||
auto it = script.begin();
|
||||
opcodetype op;
|
||||
if (!script.GetOp(it, op))
|
||||
return script;
|
||||
|
||||
if (!script.GetOp(it, op) || (op != OP_CHECKLOCKTIMEVERIFY && op != OP_CHECKSEQUENCEVERIFY))
|
||||
return script;
|
||||
|
||||
if (!script.GetOp(it, op) || op != OP_DROP)
|
||||
return script;
|
||||
|
||||
return CScript(it, script.end());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign scriptPubKey using signature made with creator.
|
||||
* Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
|
||||
@@ -102,10 +116,10 @@ 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))
|
||||
auto stripped = StripClaimScriptPrefix(scriptPubKey);
|
||||
stripped = StripTimelockPrefix(stripped);
|
||||
if (!Solver(stripped, whichTypeRet, vSolutions))
|
||||
return false;
|
||||
|
||||
switch (whichTypeRet)
|
||||
@@ -353,7 +367,7 @@ SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nI
|
||||
// Get scripts
|
||||
txnouttype script_type;
|
||||
std::vector<std::vector<unsigned char>> solutions;
|
||||
Solver(txout.scriptPubKey, script_type, solutions);
|
||||
Solver(StripClaimScriptPrefix(txout.scriptPubKey), script_type, solutions);
|
||||
SigVersion sigversion = SigVersion::BASE;
|
||||
CScript next_script = txout.scriptPubKey;
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
|
||||
{
|
||||
std::vector<valtype> vSolutions;
|
||||
txnouttype whichType;
|
||||
if (!Solver(scriptPubKey, whichType, vSolutions))
|
||||
if (!Solver(StripClaimScriptPrefix(scriptPubKey), whichType, vSolutions))
|
||||
return false;
|
||||
|
||||
if (whichType == TX_PUBKEY)
|
||||
@@ -214,9 +214,8 @@ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::
|
||||
addressRet.clear();
|
||||
typeRet = TX_NONSTANDARD;
|
||||
std::vector<valtype> vSolutions;
|
||||
if (!Solver(scriptPubKey, typeRet, vSolutions))
|
||||
return false;
|
||||
if (typeRet == TX_NULL_DATA){
|
||||
auto solved = Solver(scriptPubKey, typeRet, vSolutions);
|
||||
if (!solved || typeRet == TX_NULL_DATA){
|
||||
// This is data, not addresses
|
||||
return false;
|
||||
}
|
||||
|
||||
+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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@
|
||||
#include <uint256.h>
|
||||
#include <validation.h>
|
||||
|
||||
#include <test/claimtriefixture.h>
|
||||
#include <test/test_bitcoin.h>
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <boost/scope_exit.hpp>
|
||||
@@ -42,23 +43,6 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
CMutableTransaction BuildTransaction(const uint256& prevhash)
|
||||
{
|
||||
CMutableTransaction tx;
|
||||
tx.nVersion = 1;
|
||||
tx.nLockTime = 0;
|
||||
tx.vin.resize(1);
|
||||
tx.vout.resize(1);
|
||||
tx.vin[0].prevout.hash = prevhash;
|
||||
tx.vin[0].prevout.n = 0;
|
||||
tx.vin[0].scriptSig = CScript();
|
||||
tx.vin[0].nSequence = std::numeric_limits<unsigned int>::max();
|
||||
tx.vout[0].scriptPubKey = CScript();
|
||||
tx.vout[0].nValue = 0;
|
||||
|
||||
return tx;
|
||||
}
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(claimtriecache_tests, RegTestingSetup)
|
||||
|
||||
BOOST_AUTO_TEST_CASE(merkle_hash_single_test)
|
||||
@@ -200,7 +184,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 +194,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 +215,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 +281,12 @@ 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);
|
||||
auto hit = pclaimTrie->find("");
|
||||
BOOST_CHECK(hit);
|
||||
BOOST_CHECK_EQUAL(hit.children().size(), 1U);
|
||||
BOOST_CHECK(hit = pclaimTrie->find("test"));
|
||||
BOOST_CHECK_EQUAL(hit.children().size(), 0U);
|
||||
BOOST_CHECK_EQUAL(hit.data().claims.size(), 1);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(trie_stays_consistent_test)
|
||||
@@ -345,7 +311,7 @@ BOOST_AUTO_TEST_CASE(trie_stays_consistent_test)
|
||||
cache.flush();
|
||||
BOOST_CHECK(cache.checkConsistency());
|
||||
}
|
||||
BOOST_CHECK_EQUAL(trie.height(), 0);
|
||||
BOOST_CHECK(trie.empty());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(takeover_workaround_triggers)
|
||||
@@ -394,9 +360,91 @@ 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_AUTO_TEST_CASE(claimtrienode_serialize_unserialize)
|
||||
{
|
||||
CDataStream ss(SER_DISK, 0);
|
||||
|
||||
uint160 hash160;
|
||||
|
||||
CClaimTrieData n1;
|
||||
CClaimTrieData n2;
|
||||
CClaimValue throwaway;
|
||||
|
||||
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);
|
||||
|
||||
n1.insertClaim(v1);
|
||||
BOOST_CHECK(n1 != n2);
|
||||
ss << n1;
|
||||
ss >> n2;
|
||||
BOOST_CHECK_EQUAL(n1, n2);
|
||||
|
||||
n1.insertClaim(v2);
|
||||
BOOST_CHECK(n1 != n2);
|
||||
ss << n1;
|
||||
ss >> n2;
|
||||
BOOST_CHECK_EQUAL(n1, n2);
|
||||
|
||||
n1.removeClaim(v1.outPoint, throwaway);
|
||||
BOOST_CHECK(n1 != n2);
|
||||
ss << n1;
|
||||
ss >> n2;
|
||||
BOOST_CHECK_EQUAL(n1, n2);
|
||||
|
||||
n1.removeClaim(v2.outPoint, throwaway);
|
||||
BOOST_CHECK(n1 != n2);
|
||||
ss << n1;
|
||||
ss >> n2;
|
||||
BOOST_CHECK_EQUAL(n1, n2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claimtrienode_remove_invalid_claim)
|
||||
{
|
||||
uint160 hash160;
|
||||
|
||||
CClaimTrieData n1;
|
||||
CClaimTrieData n2;
|
||||
CClaimValue throwaway;
|
||||
|
||||
CClaimValue v1(COutPoint(uint256S("0000000000000000000000000000000000000000000000000000000000000001"), 0), hash160, 50, 0, 100);
|
||||
CClaimValue v2(COutPoint(uint256S("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"), 1), hash160, 100, 1, 101);
|
||||
|
||||
n1.insertClaim(v1);
|
||||
n2.insertClaim(v2);
|
||||
|
||||
bool invalidClaim = n2.removeClaim(v1.outPoint, throwaway);
|
||||
BOOST_CHECK_EQUAL(invalidClaim, false);
|
||||
|
||||
invalidClaim = n1.removeClaim(v2.outPoint, throwaway);
|
||||
BOOST_CHECK_EQUAL(invalidClaim, false);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
@@ -0,0 +1,803 @@
|
||||
// Copyright (c) 2015-2019 The LBRY Foundation
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://opensource.org/licenses/mit-license.php
|
||||
|
||||
#include <test/claimtriefixture.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(claimtrieexpirationfork_tests, RegTestingSetup)
|
||||
|
||||
/*
|
||||
expiration
|
||||
check claims expire and loses claim
|
||||
check claims expire and is not updateable (may be changed in future soft fork)
|
||||
check supports expire and can cause supported bid to lose claim
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(claimtrie_expire_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setExpirationForkHeight(1000000, 5, 1000000);
|
||||
|
||||
// check claims expire and loses claim
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(),"test", "one", 2);
|
||||
fixture.IncrementBlocks(fixture.expirationTime());
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx1));
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(),"test", "one", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx2));
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx1));
|
||||
fixture.DecrementBlocks(fixture.expirationTime());
|
||||
|
||||
// check claims expire and is not updateable (may be changed in future soft fork)
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(),"test", "one", 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx3));
|
||||
fixture.IncrementBlocks(fixture.expirationTime());
|
||||
CMutableTransaction u1 = fixture.MakeUpdate(tx3, "test", "two", ClaimIdHash(tx3.GetHash(), 0), 2);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",u1));
|
||||
|
||||
fixture.DecrementBlocks(fixture.expirationTime());
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx3));
|
||||
fixture.DecrementBlocks(1);
|
||||
|
||||
// check supports expire and can cause supported bid to lose claim
|
||||
CMutableTransaction tx4 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 1);
|
||||
CMutableTransaction tx5 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 2);
|
||||
CMutableTransaction s1 = fixture.MakeSupport(fixture.GetCoinbase(), tx4, "test", 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx4));
|
||||
CMutableTransaction u2 = fixture.MakeUpdate(tx4, "test", "two", ClaimIdHash(tx4.GetHash(),0), 1);
|
||||
CMutableTransaction u3 = fixture.MakeUpdate(tx5, "test", "two", ClaimIdHash(tx5.GetHash(),0), 2);
|
||||
fixture.IncrementBlocks(fixture.expirationTime());
|
||||
BOOST_CHECK(fixture.is_best_claim("test", u3));
|
||||
fixture.DecrementBlocks(fixture.expirationTime());
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx4));
|
||||
fixture.DecrementBlocks(1);
|
||||
|
||||
// check updated claims will extend expiration
|
||||
CMutableTransaction tx6 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx6));
|
||||
CMutableTransaction u4 = fixture.MakeUpdate(tx6, "test", "two", ClaimIdHash(tx6.GetHash(), 0), 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", u4));
|
||||
fixture.IncrementBlocks(fixture.expirationTime()-1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", u4));
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test", u4));
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", u4));
|
||||
fixture.DecrementBlocks(fixture.expirationTime());
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx6));
|
||||
}
|
||||
|
||||
/*
|
||||
claim expiration for hard fork
|
||||
check claims do not expire post ExpirationForkHeight
|
||||
check supports work post ExpirationForkHeight
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(hardfork_claim_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setExpirationForkHeight(7, 3, 6);
|
||||
|
||||
// First create a claim and make sure it expires pre-fork
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(),"test","one",3);
|
||||
fixture.IncrementBlocks(4);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",tx1));
|
||||
fixture.DecrementBlocks(3);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx1));
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",tx1));
|
||||
|
||||
// Create a claim 1 block before the fork height that will expire after the fork height
|
||||
fixture.IncrementBlocks(1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(),"test2","one",3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 3);
|
||||
|
||||
// Disable future expirations and fast-forward past the fork height
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 6);
|
||||
// make sure decrementing to before the fork height will apppropriately set back the
|
||||
// expiration time to the original expiraiton time
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 6);
|
||||
|
||||
// make sure that claim created 1 block before the fork expires as expected
|
||||
// at the extended expiration times
|
||||
BOOST_CHECK(fixture.is_best_claim("test2", tx2));
|
||||
fixture.IncrementBlocks(5);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test2", tx2));
|
||||
fixture.DecrementBlocks(5);
|
||||
BOOST_CHECK(fixture.is_best_claim("test2", tx2));
|
||||
|
||||
// This first claim is still expired since it's pre-fork, even
|
||||
// after fork activation
|
||||
BOOST_CHECK(!fixture.is_best_claim("test", tx1));
|
||||
|
||||
// This new claim created at the fork height cannot expire at original expiration
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(),"test","one",1);
|
||||
fixture.IncrementBlocks(1);
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx3));
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",tx1));
|
||||
fixture.DecrementBlocks(3);
|
||||
|
||||
// but it expires at the extended expiration, and not a single block below
|
||||
fixture.IncrementBlocks(6);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",tx3));
|
||||
fixture.DecrementBlocks(6);
|
||||
fixture.IncrementBlocks(5);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx3));
|
||||
fixture.DecrementBlocks(5);
|
||||
|
||||
// Ensure that we cannot update the original pre-fork expired claim
|
||||
CMutableTransaction u1 = fixture.MakeUpdate(tx1,"test","two",ClaimIdHash(tx1.GetHash(),0), 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",u1));
|
||||
|
||||
// Ensure that supports for the expired claim don't support it
|
||||
CMutableTransaction s1 = fixture.MakeSupport(fixture.GetCoinbase(),u1,"test",10);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",u1));
|
||||
|
||||
// Ensure that we can update the new post-fork claim
|
||||
CMutableTransaction u2 = fixture.MakeUpdate(tx3,"test","two",ClaimIdHash(tx3.GetHash(),0), 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",u2));
|
||||
|
||||
// Ensure that supports for the new post-fork claim
|
||||
CMutableTransaction s2 = fixture.MakeSupport(fixture.GetCoinbase(),u2,"test",3);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",u2));
|
||||
}
|
||||
|
||||
/*
|
||||
support expiration for hard fork
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(hardfork_support_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setExpirationForkHeight(2, 2, 4);
|
||||
|
||||
// Create claim and support it before the fork height
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 1);
|
||||
CMutableTransaction s1 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, "test", 2);
|
||||
// this claim will win without the support
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(),"test","one",2);
|
||||
fixture.IncrementBlocks(2);
|
||||
|
||||
// check that the claim expires as expected at the extended time, as does the support
|
||||
fixture.IncrementBlocks(2);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test",3));
|
||||
fixture.DecrementBlocks(2);
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test",tx1));
|
||||
fixture.DecrementBlocks(3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",tx1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test",3));
|
||||
fixture.DecrementBlocks(1);
|
||||
|
||||
// update the claims at fork
|
||||
fixture.DecrementBlocks(1);
|
||||
CMutableTransaction u1 = fixture.MakeUpdate(tx1, "test", "two", ClaimIdHash(tx1.GetHash(),0), 1);
|
||||
CMutableTransaction u2 = fixture.MakeUpdate(tx2, "test", "two", ClaimIdHash(tx2.GetHash(),0), 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK_EQUAL(Params().GetConsensus().nExtendedClaimExpirationForkHeight, chainActive.Height());
|
||||
|
||||
BOOST_CHECK(fixture.is_best_claim("test", u1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test",3));
|
||||
BOOST_CHECK(!fixture.is_claim_in_queue("test", tx1));
|
||||
BOOST_CHECK(!fixture.is_claim_in_queue("test", tx2));
|
||||
|
||||
// check that the support expires as expected
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", u2));
|
||||
fixture.DecrementBlocks(3);
|
||||
fixture.IncrementBlocks(2);
|
||||
BOOST_CHECK(fixture.is_best_claim("test",u1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test",3));
|
||||
}
|
||||
|
||||
/*
|
||||
activation_fall_through and supports_fall_through
|
||||
Tests for where claims/supports in queues would be undone properly in a decrement.
|
||||
See https://github.com/lbryio/lbrycrd/issues/243 for more details
|
||||
*/
|
||||
|
||||
BOOST_AUTO_TEST_CASE(activations_fall_through)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "1", 1);
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK_EQUAL(fixture.proportionalDelayFactor(), 1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "2", 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx1));
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
fixture.DecrementBlocks(3);
|
||||
fixture.Spend(tx1); // this will trigger early activation on tx2 claim
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
fixture.DecrementBlocks(1); //reorg the early activation
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx1));
|
||||
fixture.Spend(tx1);
|
||||
fixture.IncrementBlocks(1); // this should not cause tx2 to activate again and crash
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(supports_fall_through)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "1", 3);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "2", 1);
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "3", 2);
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK_EQUAL(fixture.proportionalDelayFactor(), 1);
|
||||
CMutableTransaction sx2 = fixture.MakeSupport(fixture.GetCoinbase(), tx2, "A", 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx1));
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
fixture.DecrementBlocks(3);
|
||||
fixture.Spend(tx1); // this will trigger early activation
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
fixture.DecrementBlocks(1); // reorg the early activation
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx1));
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx1)); //tx2 support should not be active
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx1)); //tx2 support should not be active
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2)); //tx2 support should be active now
|
||||
}
|
||||
|
||||
/*
|
||||
claim/support expiration for hard fork, but with checks for disk procedures
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(hardfork_disk_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setExpirationForkHeight(7, 3, 6);
|
||||
|
||||
// Check that incrementing to fork height, reseting to disk will get proper expiration time
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 3);
|
||||
fixture.IncrementBlocks(7, true);
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 6);
|
||||
fixture.ReadFromDisk(chainActive.Tip());
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 6);
|
||||
|
||||
// Create a claim and support 1 block before the fork height that will expire after the fork height.
|
||||
// Reset to disk, increment past the fork height and make sure we get
|
||||
// proper behavior
|
||||
fixture.DecrementBlocks(2);
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "test", "one", 1);
|
||||
CMutableTransaction s1 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, "test", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
fixture.ReadFromDisk(chainActive.Tip());
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK_EQUAL(fixture.expirationTime(), 6);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test",2));
|
||||
fixture.IncrementBlocks(2);
|
||||
BOOST_CHECK(fixture.is_best_claim("test", tx1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test",2));
|
||||
fixture.DecrementBlocks(2);
|
||||
fixture.IncrementBlocks(5);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test", tx1));
|
||||
|
||||
// Create a claim and support before the fork height, reset to disk, update the claim
|
||||
// increment past the fork height and make sure we get proper behavior
|
||||
fixture.DecrementBlocks();
|
||||
fixture.setExpirationForkHeight(3, 5, 6);
|
||||
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(),"test2","one",1);
|
||||
CMutableTransaction s2 = fixture.MakeSupport(fixture.GetCoinbase(),tx2,"test2",1);
|
||||
fixture.IncrementBlocks(1);
|
||||
fixture.ReadFromDisk(chainActive.Tip());
|
||||
CMutableTransaction u2 = fixture.MakeUpdate(tx2, "test2", "two", ClaimIdHash(tx2.GetHash(), 0), 1);
|
||||
// increment to fork
|
||||
fixture.IncrementBlocks(2);
|
||||
BOOST_CHECK(fixture.is_best_claim("test2", u2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test2",2));
|
||||
// increment to original expiration, should not be expired
|
||||
fixture.IncrementBlocks(2);
|
||||
BOOST_CHECK(fixture.is_best_claim("test2", u2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test2", 2));
|
||||
fixture.DecrementBlocks(2);
|
||||
// increment to extended expiration, should be expired and not one block before
|
||||
fixture.IncrementBlocks(5);
|
||||
BOOST_CHECK(!fixture.is_best_claim("test2", u2));
|
||||
fixture.DecrementBlocks(5);
|
||||
fixture.IncrementBlocks(4);
|
||||
BOOST_CHECK(fixture.is_best_claim("test2", u2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("test2", 1)); // the support expires one block before
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_expiration_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
std::string sName("atest");
|
||||
std::string sValue("testa");
|
||||
|
||||
int nThrowaway;
|
||||
|
||||
// set expiration time to 80 blocks after the block is created
|
||||
fixture.setExpirationForkHeight(1000000, 80, 1000000);
|
||||
|
||||
// create a claim. verify the expiration event has been scheduled.
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName, sValue, 10);
|
||||
COutPoint tx1OutPoint(tx1.GetHash(), 0);
|
||||
fixture.IncrementBlocks(1, true);
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// advance until the expiration event occurs. verify the expiration event occurs on time.
|
||||
|
||||
fixture.IncrementBlocks(79); // 80
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
fixture.IncrementBlocks(1); // 81
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// roll forward a bit and then roll back to before the expiration event. verify the claim is reinserted. verify the expiration event is scheduled again.
|
||||
fixture.IncrementBlocks(20); // 101
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
fixture.DecrementBlocks(21); // 80
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// advance until the expiration event occurs. verify the expiration event occurs on time.
|
||||
fixture.IncrementBlocks(1); // 81
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// roll back to before the expiration event. verify the claim is reinserted. verify the expiration event is scheduled again.
|
||||
fixture.DecrementBlocks(2); // 79
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// roll back some more.
|
||||
fixture.DecrementBlocks(39); // 40
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// spend the claim. verify the expiration event is removed.
|
||||
CMutableTransaction tx2 = fixture.Spend(tx1);
|
||||
fixture.IncrementBlocks(1); // 41
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// roll back the spend. verify the expiration event is returned.
|
||||
fixture.DecrementBlocks(1); // 40
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// advance until the expiration event occurs. verify the event occurs on time.
|
||||
fixture.IncrementBlocks(40); // 80
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
fixture.IncrementBlocks(1); // 81
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// spend the expired claim
|
||||
fixture.CommitTx(tx2);
|
||||
fixture.IncrementBlocks(1); // 82
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// undo the spend. verify everything remains empty.
|
||||
fixture.DecrementBlocks(1); // 81
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// roll back to before the expiration event. verify the claim is reinserted. verify the expiration event is scheduled again.
|
||||
fixture.DecrementBlocks(1); // 80
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// verify the expiration event happens at the right time again
|
||||
fixture.IncrementBlocks(1); // 81
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// roll back to before the expiration event. verify it gets reinserted and expiration gets scheduled.
|
||||
fixture.DecrementBlocks(1); // 80
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// roll all the way back. verify the claim is removed and the expiration event is removed.
|
||||
fixture.DecrementBlocks(); // 0
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
|
||||
// Make sure that when a claim expires, a lesser claim for the same name takes over
|
||||
|
||||
CClaimValue val;
|
||||
|
||||
// create one claim for the name
|
||||
fixture.CommitTx(tx1);
|
||||
fixture.IncrementBlocks(1, true); // 1
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// advance a little while and insert the second claim
|
||||
fixture.IncrementBlocks(4); // 5
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), sName, sValue, 5);
|
||||
COutPoint tx3OutPoint(tx3.GetHash(), 0);
|
||||
fixture.IncrementBlocks(1); // 6
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(!fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
// advance until tx3 is valid, ensure tx1 is winning
|
||||
fixture.IncrementBlocks(4); // 10
|
||||
|
||||
BOOST_CHECK(!fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.haveClaimInQueue(sName, tx3OutPoint, nThrowaway));
|
||||
|
||||
fixture.IncrementBlocks(1); // 11
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx1OutPoint);
|
||||
uint256 tx1MerkleHash = fixture.getMerkleHash();
|
||||
|
||||
// roll back to before tx3 is valid
|
||||
fixture.DecrementBlocks(1); // 10
|
||||
|
||||
// advance again until tx is valid
|
||||
fixture.IncrementBlocks(1); // 11
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx1OutPoint);
|
||||
BOOST_CHECK_EQUAL(tx1MerkleHash, fixture.getMerkleHash());
|
||||
|
||||
// advance until the expiration event occurs. verify the expiration event occurs on time.
|
||||
fixture.IncrementBlocks(69, true); // 80
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
|
||||
fixture.IncrementBlocks(1); // 81
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx3OutPoint);
|
||||
BOOST_CHECK(tx1MerkleHash != fixture.getMerkleHash());
|
||||
|
||||
// spend tx1
|
||||
fixture.CommitTx(tx2);
|
||||
fixture.IncrementBlocks(1); // 82
|
||||
|
||||
// roll back to when tx1 and tx3 are in the trie and tx1 is winning
|
||||
fixture.DecrementBlocks(); // 11
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.expirationQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx1OutPoint);
|
||||
BOOST_CHECK_EQUAL(tx1MerkleHash, fixture.getMerkleHash());
|
||||
|
||||
// roll all the way back
|
||||
fixture.DecrementBlocks();
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.expirationQueueEmpty());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(expiring_supports_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
std::string sName("atest");
|
||||
std::string sValue1("testa");
|
||||
std::string sValue2("testb");
|
||||
|
||||
CClaimValue val;
|
||||
std::vector<uint256> blocks_to_invalidate;
|
||||
|
||||
fixture.setExpirationForkHeight(1000000, 80, 1000000);
|
||||
|
||||
// to be active bid must have: a higher block number and current block >= (current height - block number) / 32
|
||||
|
||||
// Verify that supports expire
|
||||
|
||||
// Create a 1 LBC claim (tx1)
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName, sValue1, 1);
|
||||
fixture.IncrementBlocks(1); // 1, expires at 81
|
||||
|
||||
BOOST_CHECK(pcoinsTip->HaveCoin(COutPoint(tx1.GetHash(), 0)));
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
|
||||
// Create a 5 LBC support (tx3)
|
||||
CMutableTransaction tx3 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, sName, 5);
|
||||
fixture.IncrementBlocks(1); // 2, expires at 82
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
|
||||
// Advance some, then insert 5 LBC claim (tx2)
|
||||
fixture.IncrementBlocks(19); // 21
|
||||
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), sName, sValue2, 5);
|
||||
fixture.IncrementBlocks(1); // 22, activating in (22 - 2) / 1 = 20block (but not then active because support still holds tx1 up)
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(!fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
uint256 rootMerkleHash = fixture.getMerkleHash();
|
||||
|
||||
// Advance until tx2 is valid
|
||||
fixture.IncrementBlocks(20); // 42
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(!fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK_EQUAL(rootMerkleHash, fixture.getMerkleHash());
|
||||
|
||||
fixture.IncrementBlocks(1); // 43
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx1.GetHash());
|
||||
rootMerkleHash = fixture.getMerkleHash();
|
||||
|
||||
// Update tx1 so that it expires after tx3 expires
|
||||
uint160 claimId = ClaimIdHash(tx1.GetHash(), 0);
|
||||
CMutableTransaction tx4 = fixture.MakeUpdate(tx1, sName, sValue1, claimId, tx1.vout[0].nValue);
|
||||
|
||||
fixture.IncrementBlocks(1); // 104
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx4.GetHash());
|
||||
BOOST_CHECK(rootMerkleHash != fixture.getMerkleHash());
|
||||
|
||||
// Advance until the support expires
|
||||
fixture.IncrementBlocks(37); // 81
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
rootMerkleHash = fixture.getMerkleHash();
|
||||
|
||||
fixture.IncrementBlocks(1); // 82
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx2.GetHash());
|
||||
BOOST_CHECK(rootMerkleHash != fixture.getMerkleHash());
|
||||
rootMerkleHash = fixture.getMerkleHash();
|
||||
|
||||
// undo the block, make sure control goes back
|
||||
fixture.DecrementBlocks(1); // 81
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx4.GetHash());
|
||||
BOOST_CHECK(rootMerkleHash != fixture.getMerkleHash());
|
||||
|
||||
// redo the block, make sure it expires again
|
||||
fixture.IncrementBlocks(1); // 82
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx2.GetHash());
|
||||
rootMerkleHash = fixture.getMerkleHash();
|
||||
|
||||
// roll back some, spend the support, and make sure nothing unexpected
|
||||
// happens at the time the support should have expired
|
||||
|
||||
fixture.DecrementBlocks(19); // 63
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx4.GetHash());
|
||||
BOOST_CHECK(rootMerkleHash != fixture.getMerkleHash());
|
||||
|
||||
fixture.Spend(tx3);
|
||||
fixture.IncrementBlocks(1); // 64
|
||||
|
||||
blocks_to_invalidate.push_back(chainActive.Tip()->GetBlockHash());
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx2.GetHash());
|
||||
|
||||
fixture.IncrementBlocks(20); // 84
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx2.GetHash());
|
||||
|
||||
//undo the spend, and make sure it still expires on time
|
||||
|
||||
fixture.DecrementBlocks(21); // 63
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx4.GetHash());
|
||||
|
||||
fixture.IncrementBlocks(18); // 81
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(!fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx4.GetHash());
|
||||
|
||||
fixture.IncrementBlocks(1); // 82
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint.hash, tx2.GetHash());
|
||||
|
||||
// roll all the way back
|
||||
fixture.DecrementBlocks(82);
|
||||
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.supportEmpty());
|
||||
BOOST_CHECK(fixture.supportQueueEmpty());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(get_claim_by_id_test_3)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setExpirationForkHeight(1000000, 5, 1000000);
|
||||
const std::string name = "test";
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), name, "one", 1);
|
||||
uint160 claimId = ClaimIdHash(tx1.GetHash(), 0);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
CClaimValue claimValue;
|
||||
std::string claimName;
|
||||
BOOST_CHECK(getClaimById(claimId, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId);
|
||||
// make second claim with activation delay 1
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), name, "one", 2);
|
||||
uint160 claimId2 = ClaimIdHash(tx2.GetHash(), 0);
|
||||
|
||||
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(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(getClaimById(claimId2, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId2);
|
||||
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
// second claim has been deactivated via decrement
|
||||
// should still be accesible via claim id
|
||||
BOOST_CHECK(fixture.is_best_claim(name, tx1));
|
||||
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(getClaimById(claimId2, claimName, &claimValue));
|
||||
BOOST_CHECK_EQUAL(claimName, name);
|
||||
BOOST_CHECK_EQUAL(claimValue.claimId, claimId2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
@@ -0,0 +1,419 @@
|
||||
// Copyright (c) 2015-2019 The LBRY Foundation
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://opensource.org/licenses/mit-license.php
|
||||
|
||||
#include <functional>
|
||||
#include <test/claimtriefixture.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(claimtriefixture_tests, RegTestingSetup)
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claimtriefixture_noop)
|
||||
{
|
||||
BOOST_REQUIRE(true);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
CMutableTransaction BuildTransaction(const CTransaction& prev, uint32_t prevout, unsigned int numOutputs, int locktime)
|
||||
{
|
||||
CMutableTransaction tx;
|
||||
tx.nVersion = CTransaction::CURRENT_VERSION;
|
||||
tx.vin.resize(1);
|
||||
tx.vout.resize(numOutputs);
|
||||
tx.vin[0].prevout.hash = prev.GetHash();
|
||||
tx.vin[0].prevout.n = prevout;
|
||||
tx.vin[0].scriptSig = CScript();
|
||||
if (locktime != 0) {
|
||||
// Use a relative locktime for validity X blocks in the future
|
||||
tx.nLockTime = chainActive.Height() + locktime;
|
||||
tx.vin[0].nSequence = 0xffffffff - 1;
|
||||
} else {
|
||||
tx.nLockTime = 1 << 31; // Disable BIP68
|
||||
tx.vin[0].nSequence = std::numeric_limits<unsigned int>::max();
|
||||
}
|
||||
CAmount valuePerOutput = prev.vout[prevout].nValue;
|
||||
unsigned int numOutputsCopy = numOutputs;
|
||||
while ((numOutputsCopy = numOutputsCopy >> 1) > 0)
|
||||
valuePerOutput = valuePerOutput >> 1;
|
||||
|
||||
for (unsigned int i = 0; i < numOutputs; ++i) {
|
||||
tx.vout[i].scriptPubKey = CScript();
|
||||
tx.vout[i].nValue = valuePerOutput;
|
||||
}
|
||||
return tx;
|
||||
}
|
||||
|
||||
CMutableTransaction BuildTransaction(const uint256& prevhash)
|
||||
{
|
||||
CMutableTransaction tx;
|
||||
tx.nVersion = 1;
|
||||
tx.nLockTime = 0;
|
||||
tx.vin.resize(1);
|
||||
tx.vout.resize(1);
|
||||
tx.vin[0].prevout.hash = prevhash;
|
||||
tx.vin[0].prevout.n = 0;
|
||||
tx.vin[0].scriptSig = CScript();
|
||||
tx.vin[0].nSequence = std::numeric_limits<unsigned int>::max();
|
||||
tx.vout[0].scriptPubKey = CScript();
|
||||
tx.vout[0].nValue = 0;
|
||||
|
||||
return tx;
|
||||
}
|
||||
|
||||
BlockAssembler AssemblerForTest()
|
||||
{
|
||||
BlockAssembler::Options options;
|
||||
options.nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
|
||||
options.blockMinFeeRate = CFeeRate(0);
|
||||
return BlockAssembler(Params(), options);
|
||||
}
|
||||
|
||||
ClaimTrieChainFixture::ClaimTrieChainFixture() : CClaimTrieCache(pclaimTrie),
|
||||
unique_block_counter(0), normalization_original(-1), expirationForkHeight(-1), forkhash_original(-1)
|
||||
{
|
||||
fRequireStandard = false;
|
||||
BOOST_CHECK_EQUAL(nNextHeight, chainActive.Height() + 1);
|
||||
setNormalizationForkHeight(1000000);
|
||||
|
||||
gArgs.ForceSetArg("-limitancestorcount", "1000000");
|
||||
gArgs.ForceSetArg("-limitancestorsize", "1000000");
|
||||
gArgs.ForceSetArg("-limitdescendantcount", "1000000");
|
||||
gArgs.ForceSetArg("-limitdescendantsize", "1000000");
|
||||
|
||||
num_txs_for_next_block = 0;
|
||||
coinbase_txs_used = 0;
|
||||
unique_block_counter = 0;
|
||||
added_unchecked = false;
|
||||
// generate coinbases to spend
|
||||
CreateCoinbases(40, coinbase_txs);
|
||||
}
|
||||
|
||||
ClaimTrieChainFixture::~ClaimTrieChainFixture()
|
||||
{
|
||||
added_unchecked = false;
|
||||
DecrementBlocks(chainActive.Height());
|
||||
auto& consensus = const_cast<Consensus::Params&>(Params().GetConsensus());
|
||||
if (normalization_original >= 0)
|
||||
consensus.nNormalizedNameForkHeight = normalization_original;
|
||||
|
||||
if (expirationForkHeight >= 0) {
|
||||
consensus.nExtendedClaimExpirationForkHeight = expirationForkHeight;
|
||||
consensus.nExtendedClaimExpirationTime = extendedExpiration;
|
||||
consensus.nOriginalClaimExpirationTime = originalExpiration;
|
||||
}
|
||||
if (forkhash_original >= 0)
|
||||
consensus.nAllClaimsInMerkleForkHeight = forkhash_original;
|
||||
}
|
||||
|
||||
void ClaimTrieChainFixture::setExpirationForkHeight(int targetMinusCurrent, int64_t preForkExpirationTime, int64_t postForkExpirationTime)
|
||||
{
|
||||
int target = chainActive.Height() + targetMinusCurrent;
|
||||
auto& consensus = const_cast<Consensus::Params&>(Params().GetConsensus());
|
||||
if (expirationForkHeight < 0) {
|
||||
expirationForkHeight = consensus.nExtendedClaimExpirationForkHeight;
|
||||
originalExpiration = consensus.nOriginalClaimExpirationTime;
|
||||
extendedExpiration = consensus.nExtendedClaimExpirationTime;
|
||||
}
|
||||
consensus.nExtendedClaimExpirationForkHeight = target;
|
||||
consensus.nExtendedClaimExpirationTime = postForkExpirationTime;
|
||||
consensus.nOriginalClaimExpirationTime = preForkExpirationTime;
|
||||
setExpirationTime(targetMinusCurrent >= 0 ? preForkExpirationTime : postForkExpirationTime);
|
||||
}
|
||||
|
||||
void ClaimTrieChainFixture::setNormalizationForkHeight(int targetMinusCurrent)
|
||||
{
|
||||
int target = chainActive.Height() + targetMinusCurrent;
|
||||
auto& consensus = const_cast<Consensus::Params&>(Params().GetConsensus());
|
||||
if (normalization_original < 0)
|
||||
normalization_original = consensus.nNormalizedNameForkHeight;
|
||||
consensus.nNormalizedNameForkHeight = target;
|
||||
}
|
||||
|
||||
void ClaimTrieChainFixture::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 ClaimTrieChainFixture::CreateBlock(const std::unique_ptr<CBlockTemplate>& pblocktemplate)
|
||||
{
|
||||
CBlock* pblock = &pblocktemplate->block;
|
||||
{
|
||||
LOCK(cs_main);
|
||||
pblock->nVersion = 5;
|
||||
pblock->hashPrevBlock = chainActive.Tip()->GetBlockHash();
|
||||
pblock->nTime = chainActive.Tip()->GetBlockTime() + Params().GetConsensus().nPowTargetSpacing;
|
||||
CMutableTransaction txCoinbase(*pblock->vtx[0]);
|
||||
txCoinbase.vin[0].scriptSig = CScript() << int(chainActive.Height() + 1) << int(++unique_block_counter);
|
||||
txCoinbase.vout[0].nValue = GetBlockSubsidy(chainActive.Height() + 1, Params().GetConsensus());
|
||||
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
|
||||
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
|
||||
for (uint32_t i = 0;; ++i) {
|
||||
pblock->nNonce = i;
|
||||
if (CheckProofOfWork(pblock->GetPoWHash(), pblock->nBits, Params().GetConsensus()))
|
||||
break;
|
||||
}
|
||||
}
|
||||
auto success = ProcessNewBlock(Params(), std::make_shared<const CBlock>(*pblock), true, nullptr);
|
||||
return success && pblock->GetHash() == chainActive.Tip()->GetBlockHash();
|
||||
}
|
||||
|
||||
bool ClaimTrieChainFixture::CreateCoinbases(unsigned int num_coinbases, std::vector<CTransaction>& coinbases)
|
||||
{
|
||||
std::unique_ptr<CBlockTemplate> pblocktemplate;
|
||||
coinbases.clear();
|
||||
BOOST_CHECK(pblocktemplate = AssemblerForTest().CreateNewBlock(CScript() << OP_TRUE));
|
||||
BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 1);
|
||||
for (unsigned int i = 0; i < 100 + num_coinbases; ++i) {
|
||||
BOOST_CHECK(CreateBlock(pblocktemplate));
|
||||
if (coinbases.size() < num_coinbases)
|
||||
coinbases.push_back(std::move(*pblocktemplate->block.vtx[0]));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ClaimTrieChainFixture::CommitTx(const CMutableTransaction &tx, bool has_locktime)
|
||||
{
|
||||
num_txs_for_next_block++;
|
||||
if (has_locktime) {
|
||||
added_unchecked = true;
|
||||
TestMemPoolEntryHelper entry;
|
||||
LOCK(mempool.cs);
|
||||
mempool.addUnchecked(tx.GetHash(), entry.Fee(0).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
|
||||
} else {
|
||||
CValidationState state;
|
||||
CAmount txFeeRate = CAmount(0);
|
||||
LOCK(cs_main);
|
||||
BOOST_CHECK_EQUAL(AcceptToMemoryPool(mempool, state, MakeTransactionRef(tx), nullptr, nullptr, false, txFeeRate, false), true);
|
||||
}
|
||||
}
|
||||
|
||||
// spend a bid into some non claimtrie related unspent
|
||||
CMutableTransaction ClaimTrieChainFixture::Spend(const CTransaction &prev)
|
||||
{
|
||||
CMutableTransaction tx = BuildTransaction(prev, 0);
|
||||
tx.vout[0].scriptPubKey = CScript() << OP_TRUE;
|
||||
tx.vout[0].nValue = prev.vout[0].nValue;
|
||||
|
||||
CommitTx(tx);
|
||||
return tx;
|
||||
}
|
||||
|
||||
// make claim at the current block
|
||||
CMutableTransaction ClaimTrieChainFixture::MakeClaim(const CTransaction& prev, const std::string& name, const std::string& value, CAmount quantity, int locktime)
|
||||
{
|
||||
uint32_t prevout = prev.vout.size() - 1;
|
||||
while (prevout > 0 && prev.vout[prevout].nValue < quantity)
|
||||
--prevout;
|
||||
CMutableTransaction tx = BuildTransaction(prev, prevout, prev.vout[prevout].nValue > quantity ? 2 : 1, locktime);
|
||||
tx.vout[0].scriptPubKey = ClaimNameScript(name, value);
|
||||
tx.vout[0].nValue = quantity;
|
||||
if (tx.vout.size() > 1) {
|
||||
tx.vout[1].scriptPubKey = CScript() << OP_TRUE;
|
||||
tx.vout[1].nValue = prev.vout[prevout].nValue - quantity;
|
||||
}
|
||||
|
||||
CommitTx(tx, locktime != 0);
|
||||
return tx;
|
||||
}
|
||||
|
||||
CMutableTransaction ClaimTrieChainFixture::MakeClaim(const CTransaction& prev, const std::string& name, const std::string& value)
|
||||
{
|
||||
return MakeClaim(prev, name, value, prev.vout[0].nValue, 0);
|
||||
}
|
||||
|
||||
// make support at the current block
|
||||
CMutableTransaction ClaimTrieChainFixture::MakeSupport(const CTransaction &prev, const CTransaction &claimtx, const std::string& name, CAmount quantity)
|
||||
{
|
||||
uint32_t prevout = prev.vout.size() - 1;
|
||||
while (prevout > 0 && prev.vout[prevout].nValue < quantity)
|
||||
--prevout;
|
||||
|
||||
CMutableTransaction tx = BuildTransaction(prev, prevout, prev.vout[prevout].nValue > quantity ? 2 : 1);
|
||||
tx.vout[0].scriptPubKey = SupportClaimScript(name, ClaimIdHash(claimtx.GetHash(), 0));
|
||||
tx.vout[0].nValue = quantity;
|
||||
if (tx.vout.size() > 1) {
|
||||
tx.vout[1].scriptPubKey = CScript() << OP_TRUE;
|
||||
tx.vout[1].nValue = prev.vout[prevout].nValue - quantity;
|
||||
}
|
||||
|
||||
CommitTx(tx);
|
||||
return tx;
|
||||
}
|
||||
|
||||
// make update at the current block
|
||||
CMutableTransaction ClaimTrieChainFixture::MakeUpdate(const CTransaction &prev, const std::string& name, const std::string& value, const uint160& claimId, CAmount quantity)
|
||||
{
|
||||
CMutableTransaction tx = BuildTransaction(prev, 0);
|
||||
tx.vout[0].scriptPubKey = UpdateClaimScript(name, claimId, value);
|
||||
tx.vout[0].nValue = quantity;
|
||||
|
||||
CommitTx(tx);
|
||||
return tx;
|
||||
}
|
||||
|
||||
CTransaction ClaimTrieChainFixture::GetCoinbase()
|
||||
{
|
||||
return coinbase_txs.at(coinbase_txs_used++);
|
||||
}
|
||||
|
||||
// create i blocks
|
||||
void ClaimTrieChainFixture::IncrementBlocks(int num_blocks, bool mark)
|
||||
{
|
||||
if (mark)
|
||||
marks.push_back(chainActive.Height());
|
||||
|
||||
clear(); // clears the internal cache
|
||||
for (int i = 0; i < num_blocks; ++i) {
|
||||
CScript coinbase_scriptpubkey;
|
||||
coinbase_scriptpubkey << CScriptNum(chainActive.Height());
|
||||
std::unique_ptr<CBlockTemplate> pblocktemplate = AssemblerForTest().CreateNewBlock(coinbase_scriptpubkey);
|
||||
BOOST_CHECK(pblocktemplate != nullptr);
|
||||
if (!added_unchecked)
|
||||
BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), num_txs_for_next_block + 1);
|
||||
BOOST_CHECK_EQUAL(CreateBlock(pblocktemplate), true);
|
||||
num_txs_for_next_block = 0;
|
||||
nNextHeight = chainActive.Height() + 1;
|
||||
}
|
||||
setExpirationTime(Params().GetConsensus().GetExpirationTime(nNextHeight - 1));
|
||||
}
|
||||
|
||||
// disconnect i blocks from tip
|
||||
void ClaimTrieChainFixture::DecrementBlocks(int num_blocks)
|
||||
{
|
||||
clear(); // clears the internal cache
|
||||
CValidationState state;
|
||||
{
|
||||
LOCK(cs_main);
|
||||
CBlockIndex* pblockindex = chainActive[chainActive.Height() - num_blocks + 1];
|
||||
BOOST_CHECK_EQUAL(InvalidateBlock(state, Params(), pblockindex), true);
|
||||
}
|
||||
BOOST_CHECK_EQUAL(state.IsValid(), true);
|
||||
BOOST_CHECK_EQUAL(ActivateBestChain(state, Params()), true);
|
||||
mempool.clear();
|
||||
num_txs_for_next_block = 0;
|
||||
nNextHeight = chainActive.Height() + 1;
|
||||
setExpirationTime(Params().GetConsensus().GetExpirationTime(nNextHeight - 1));
|
||||
}
|
||||
|
||||
// decrement back to last mark
|
||||
void ClaimTrieChainFixture::DecrementBlocks()
|
||||
{
|
||||
int mark = marks.back();
|
||||
marks.pop_back();
|
||||
DecrementBlocks(chainActive.Height() - mark);
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
bool ClaimTrieChainFixture::keyTypeEmpty(uint8_t keyType)
|
||||
{
|
||||
boost::scoped_ptr<CDBIterator> pcursor(base->db->NewIterator());
|
||||
pcursor->SeekToFirst();
|
||||
|
||||
while (pcursor->Valid()) {
|
||||
std::pair<uint8_t, K> key;
|
||||
if (pcursor->GetKey(key))
|
||||
if (key.first == keyType)
|
||||
return false;
|
||||
pcursor->Next();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ClaimTrieChainFixture::queueEmpty()
|
||||
{
|
||||
for (const auto& claimQueue: claimQueueCache)
|
||||
if (!claimQueue.second.empty())
|
||||
return false;
|
||||
return keyTypeEmpty<int>(CLAIM_QUEUE_ROW);
|
||||
}
|
||||
|
||||
bool ClaimTrieChainFixture::expirationQueueEmpty()
|
||||
{
|
||||
for (const auto& expirationQueue: expirationQueueCache)
|
||||
if (!expirationQueue.second.empty())
|
||||
return false;
|
||||
return keyTypeEmpty<int>(CLAIM_EXP_QUEUE_ROW);
|
||||
}
|
||||
|
||||
bool ClaimTrieChainFixture::supportEmpty()
|
||||
{
|
||||
for (const auto& entry: supportCache)
|
||||
if (!entry.second.empty())
|
||||
return false;
|
||||
return supportCache.empty() && keyTypeEmpty<std::string>(SUPPORT);
|
||||
}
|
||||
|
||||
bool ClaimTrieChainFixture::supportQueueEmpty()
|
||||
{
|
||||
for (const auto& support: supportQueueCache)
|
||||
if (!support.second.empty())
|
||||
return false;
|
||||
return keyTypeEmpty<int>(SUPPORT_QUEUE_ROW);
|
||||
}
|
||||
|
||||
int ClaimTrieChainFixture::proportionalDelayFactor()
|
||||
{
|
||||
return base->nProportionalDelayFactor;
|
||||
}
|
||||
|
||||
boost::test_tools::predicate_result negativeResult(const std::function<void(boost::wrap_stringstream&)>& callback)
|
||||
{
|
||||
boost::test_tools::predicate_result res(false);
|
||||
callback(res.message());
|
||||
return res;
|
||||
}
|
||||
|
||||
boost::test_tools::predicate_result negativeResult(const std::string& message)
|
||||
{
|
||||
return negativeResult([&message](boost::wrap_stringstream& stream) {
|
||||
stream << message;
|
||||
});
|
||||
}
|
||||
|
||||
// is a claim in queue
|
||||
boost::test_tools::predicate_result ClaimTrieChainFixture::is_claim_in_queue(const std::string& name, const CTransaction &tx)
|
||||
{
|
||||
COutPoint outPoint(tx.GetHash(), 0);
|
||||
int validAtHeight;
|
||||
if (haveClaimInQueue(name, outPoint, validAtHeight))
|
||||
return true;
|
||||
return negativeResult("Is not a claim in queue");
|
||||
}
|
||||
|
||||
// check if tx is best claim based on outpoint
|
||||
boost::test_tools::predicate_result ClaimTrieChainFixture::is_best_claim(const std::string& name, const CTransaction &tx)
|
||||
{
|
||||
CClaimValue val;
|
||||
COutPoint outPoint(tx.GetHash(), 0);
|
||||
bool have_claim = haveClaim(name, outPoint);
|
||||
bool have_info = getInfoForName(name, val);
|
||||
if (have_claim && have_info && val.outPoint == outPoint)
|
||||
return true;
|
||||
return negativeResult("Is not best claim");
|
||||
}
|
||||
|
||||
// check effective quantity of best claim
|
||||
boost::test_tools::predicate_result ClaimTrieChainFixture::best_claim_effective_amount_equals(const std::string& name, CAmount amount)
|
||||
{
|
||||
CClaimValue val;
|
||||
bool have_info = getInfoForName(name, val);
|
||||
if (!have_info)
|
||||
return negativeResult("No claim found");
|
||||
CAmount effective_amount = getClaimsForName(name).find(val.claimId).effectiveAmount;
|
||||
if (effective_amount != amount)
|
||||
return negativeResult([amount, effective_amount](boost::wrap_stringstream& stream) {
|
||||
stream << amount << " != " << effective_amount;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t ClaimTrieChainFixture::getTotalNamesInTrie() const
|
||||
{
|
||||
return base->getTotalNamesInTrie();
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Copyright (c) 2015-2019 The LBRY Foundation
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://opensource.org/licenses/mit-license.php
|
||||
|
||||
#ifndef _CLAIMTRIEFIXTURE_H_
|
||||
#define _CLAIMTRIEFIXTURE_H_
|
||||
|
||||
#include <chainparams.h>
|
||||
#include <claimtrie.h>
|
||||
#include <coins.h>
|
||||
#include <consensus/merkle.h>
|
||||
#include <consensus/validation.h>
|
||||
#include <miner.h>
|
||||
#include <nameclaim.h>
|
||||
#include <policy/policy.h>
|
||||
#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>
|
||||
#include <txmempool.h>
|
||||
#include <validation.h>
|
||||
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <iostream>
|
||||
|
||||
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*);
|
||||
|
||||
CMutableTransaction BuildTransaction(const uint256& prevhash);
|
||||
CMutableTransaction BuildTransaction(const CTransaction& prev, uint32_t prevout=0, unsigned int numOutputs=1, int locktime=0);
|
||||
|
||||
BlockAssembler AssemblerForTest();
|
||||
|
||||
// Test Fixtures
|
||||
struct ClaimTrieChainFixture: public CClaimTrieCache
|
||||
{
|
||||
std::vector<CTransaction> coinbase_txs;
|
||||
std::vector<int> marks;
|
||||
int coinbase_txs_used;
|
||||
int unique_block_counter;
|
||||
int normalization_original;
|
||||
unsigned int num_txs_for_next_block;
|
||||
bool added_unchecked;
|
||||
|
||||
int64_t expirationForkHeight;
|
||||
int64_t originalExpiration;
|
||||
int64_t extendedExpiration;
|
||||
int64_t forkhash_original;
|
||||
|
||||
using CClaimTrieCache::getSupportsForName;
|
||||
|
||||
ClaimTrieChainFixture();
|
||||
|
||||
~ClaimTrieChainFixture();
|
||||
|
||||
void setExpirationForkHeight(int targetMinusCurrent, int64_t preForkExpirationTime, int64_t postForkExpirationTime);
|
||||
|
||||
void setNormalizationForkHeight(int targetMinusCurrent);
|
||||
|
||||
void setHashForkHeight(int targetMinusCurrent);
|
||||
|
||||
bool CreateBlock(const std::unique_ptr<CBlockTemplate>& pblocktemplate);
|
||||
|
||||
bool CreateCoinbases(unsigned int num_coinbases, std::vector<CTransaction>& coinbases);
|
||||
|
||||
void CommitTx(const CMutableTransaction &tx, bool has_locktime=false);
|
||||
|
||||
// spend a bid into some non claimtrie related unspent
|
||||
CMutableTransaction Spend(const CTransaction &prev);
|
||||
|
||||
// make claim at the current block
|
||||
CMutableTransaction MakeClaim(const CTransaction& prev, const std::string& name, const std::string& value, CAmount quantity, int locktime=0);
|
||||
|
||||
CMutableTransaction MakeClaim(const CTransaction& prev, const std::string& name, const std::string& value);
|
||||
|
||||
// make support at the current block
|
||||
CMutableTransaction MakeSupport(const CTransaction &prev, const CTransaction &claimtx, const std::string& name, CAmount quantity);
|
||||
|
||||
// make update at the current block
|
||||
CMutableTransaction MakeUpdate(const CTransaction &prev, const std::string& name, const std::string& value, const uint160& claimId, CAmount quantity);
|
||||
|
||||
CTransaction GetCoinbase();
|
||||
|
||||
// create i blocks
|
||||
void IncrementBlocks(int num_blocks, bool mark = false);
|
||||
|
||||
// disconnect i blocks from tip
|
||||
void DecrementBlocks(int num_blocks);
|
||||
|
||||
// decrement back to last mark
|
||||
void DecrementBlocks();
|
||||
|
||||
bool queueEmpty();
|
||||
|
||||
bool expirationQueueEmpty();
|
||||
|
||||
bool supportEmpty();
|
||||
|
||||
bool supportQueueEmpty();
|
||||
|
||||
int proportionalDelayFactor();
|
||||
|
||||
// is a claim in queue
|
||||
boost::test_tools::predicate_result is_claim_in_queue(const std::string& name, const CTransaction &tx);
|
||||
|
||||
// check if tx is best claim based on outpoint
|
||||
boost::test_tools::predicate_result is_best_claim(const std::string& name, const CTransaction &tx);
|
||||
|
||||
// check effective quantity of best claim
|
||||
boost::test_tools::predicate_result best_claim_effective_amount_equals(const std::string& name, CAmount amount);
|
||||
|
||||
std::size_t getTotalNamesInTrie() const;
|
||||
|
||||
private:
|
||||
template <typename K>
|
||||
bool keyTypeEmpty(uint8_t keyType);
|
||||
};
|
||||
|
||||
#endif // _CLAIMTRIEFIXTURE_H_
|
||||
@@ -0,0 +1,390 @@
|
||||
// Copyright (c) 2015-2019 The LBRY Foundation
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://opensource.org/licenses/mit-license.php
|
||||
|
||||
#include <test/claimtriefixture.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
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_FIXTURE_TEST_SUITE(claimtriehashfork_tests, RegTestingSetup)
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool verify_proof(const CClaimTrieProof proof, uint256 rootHash, const std::string& name)
|
||||
{
|
||||
uint256 previousComputedHash;
|
||||
std::string computedReverseName;
|
||||
bool verifiedValue = false;
|
||||
|
||||
for (auto itNodes = proof.nodes.rbegin(); itNodes != proof.nodes.rend(); ++itNodes) {
|
||||
bool foundChildInChain = false;
|
||||
std::vector<unsigned char> vchToHash;
|
||||
for (auto itChildren = itNodes->children.begin(); itChildren != itNodes->children.end(); ++itChildren) {
|
||||
vchToHash.push_back(itChildren->first);
|
||||
uint256 childHash;
|
||||
if (itChildren->second.IsNull()) {
|
||||
if (previousComputedHash.IsNull()) {
|
||||
return false;
|
||||
}
|
||||
if (foundChildInChain) {
|
||||
return false;
|
||||
}
|
||||
foundChildInChain = true;
|
||||
computedReverseName += itChildren->first;
|
||||
childHash = previousComputedHash;
|
||||
} else {
|
||||
childHash = itChildren->second;
|
||||
}
|
||||
vchToHash.insert(vchToHash.end(), childHash.begin(), childHash.end());
|
||||
}
|
||||
if (itNodes != proof.nodes.rbegin() && !foundChildInChain) {
|
||||
return false;
|
||||
}
|
||||
if (itNodes->hasValue) {
|
||||
uint256 valHash;
|
||||
if (itNodes->valHash.IsNull()) {
|
||||
if (itNodes != proof.nodes.rbegin()) {
|
||||
return false;
|
||||
}
|
||||
if (!proof.hasValue) {
|
||||
return false;
|
||||
}
|
||||
valHash = getValueHash(proof.outPoint,
|
||||
proof.nHeightOfLastTakeover);
|
||||
|
||||
verifiedValue = true;
|
||||
} else {
|
||||
valHash = itNodes->valHash;
|
||||
}
|
||||
vchToHash.insert(vchToHash.end(), valHash.begin(), valHash.end());
|
||||
} else if (proof.hasValue && itNodes == proof.nodes.rbegin()) {
|
||||
return false;
|
||||
}
|
||||
CHash256 hasher;
|
||||
std::vector<unsigned char> vchHash(hasher.OUTPUT_SIZE);
|
||||
hasher.Write(vchToHash.data(), vchToHash.size());
|
||||
hasher.Finalize(&(vchHash[0]));
|
||||
uint256 calculatedHash(vchHash);
|
||||
previousComputedHash = calculatedHash;
|
||||
}
|
||||
if (previousComputedHash != rootHash) {
|
||||
return false;
|
||||
}
|
||||
if (proof.hasValue && !verifiedValue) {
|
||||
return false;
|
||||
}
|
||||
std::string::reverse_iterator itComputedName = computedReverseName.rbegin();
|
||||
std::string::const_iterator itName = name.begin();
|
||||
for (; itName != name.end() && itComputedName != computedReverseName.rend(); ++itName, ++itComputedName) {
|
||||
if (*itName != *itComputedName) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return (!proof.hasValue || itName == name.end());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(value_proof_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
std::string sName1("a");
|
||||
std::string sValue1("testa");
|
||||
|
||||
std::string sName2("abc");
|
||||
std::string sValue2("testabc");
|
||||
|
||||
std::string sName3("abd");
|
||||
std::string sValue3("testabd");
|
||||
|
||||
std::string sName4("zyx");
|
||||
std::string sValue4("testzyx");
|
||||
|
||||
std::string sName5("zyxa");
|
||||
std::string sName6("omg");
|
||||
std::string sName7("");
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue1);
|
||||
COutPoint tx1OutPoint(tx1.GetHash(), 0);
|
||||
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), sName2, sValue2);
|
||||
COutPoint tx2OutPoint(tx2.GetHash(), 0);
|
||||
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), sName3, sValue3);
|
||||
COutPoint tx3OutPoint(tx3.GetHash(), 0);
|
||||
|
||||
CMutableTransaction tx4 = fixture.MakeClaim(fixture.GetCoinbase(), sName4, sValue4);
|
||||
COutPoint tx4OutPoint(tx4.GetHash(), 0);
|
||||
CClaimValue val;
|
||||
|
||||
// create a claim. verify the expiration event has been scheduled.
|
||||
fixture.IncrementBlocks(5, true);
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
BOOST_CHECK(fixture.getInfoForName(sName1, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx1OutPoint);
|
||||
BOOST_CHECK(fixture.getInfoForName(sName2, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx2OutPoint);
|
||||
BOOST_CHECK(fixture.getInfoForName(sName3, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx3OutPoint);
|
||||
BOOST_CHECK(fixture.getInfoForName(sName4, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx4OutPoint);
|
||||
|
||||
CClaimTrieProof proof;
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName1, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName1));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx1OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName2, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName2));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx2OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName3, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName3));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx3OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName4, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName4));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx4OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName5, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName5));
|
||||
BOOST_CHECK_EQUAL(proof.hasValue, false);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName6, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName6));
|
||||
BOOST_CHECK_EQUAL(proof.hasValue, false);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName7, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName7));
|
||||
BOOST_CHECK_EQUAL(proof.hasValue, false);
|
||||
|
||||
CMutableTransaction tx5 = fixture.MakeClaim(fixture.GetCoinbase(), sName7, sValue4);
|
||||
COutPoint tx5OutPoint(tx5.GetHash(), 0);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK(fixture.getInfoForName(sName7, val));
|
||||
BOOST_CHECK_EQUAL(val.outPoint, tx5OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName1, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName1));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx1OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName2, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName2));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx2OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName3, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName3));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx3OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName4, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName4));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx4OutPoint);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName5, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName5));
|
||||
BOOST_CHECK_EQUAL(proof.hasValue, false);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName6, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName6));
|
||||
BOOST_CHECK_EQUAL(proof.hasValue, false);
|
||||
|
||||
BOOST_CHECK(fixture.getProofForName(sName7, proof));
|
||||
BOOST_CHECK(verify_proof(proof, chainActive.Tip()->hashClaimTrie, sName7));
|
||||
BOOST_CHECK_EQUAL(proof.outPoint, tx5OutPoint);
|
||||
|
||||
fixture.DecrementBlocks();
|
||||
BOOST_CHECK(pclaimTrie->empty());
|
||||
BOOST_CHECK(fixture.queueEmpty());
|
||||
}
|
||||
|
||||
// Check that blocks with bogus calimtrie hash is rejected
|
||||
BOOST_AUTO_TEST_CASE(bogus_claimtrie_hash_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
std::string sName("test");
|
||||
std::string sValue1("test");
|
||||
|
||||
int orig_chain_height = chainActive.Height();
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName, sValue1, 1);
|
||||
|
||||
std::unique_ptr<CBlockTemplate> pblockTemp;
|
||||
BOOST_CHECK(pblockTemp = AssemblerForTest().CreateNewBlock(tx1.vout[0].scriptPubKey));
|
||||
pblockTemp->block.hashPrevBlock = chainActive.Tip()->GetBlockHash();
|
||||
pblockTemp->block.nVersion = 5;
|
||||
pblockTemp->block.nTime = chainActive.Tip()->GetBlockTime() + Params().GetConsensus().nPowTargetSpacing;
|
||||
CMutableTransaction txCoinbase(*pblockTemp->block.vtx[0]);
|
||||
txCoinbase.vin[0].scriptSig = CScript() << int(chainActive.Height() + 1) << 1;
|
||||
txCoinbase.vout[0].nValue = GetBlockSubsidy(chainActive.Height() + 1, Params().GetConsensus());
|
||||
pblockTemp->block.vtx[0] = MakeTransactionRef(std::move(txCoinbase));
|
||||
pblockTemp->block.hashMerkleRoot = BlockMerkleRoot(pblockTemp->block);
|
||||
//create bogus hash
|
||||
|
||||
uint256 bogusHashClaimTrie;
|
||||
bogusHashClaimTrie.SetHex("aaa");
|
||||
pblockTemp->block.hashClaimTrie = bogusHashClaimTrie;
|
||||
|
||||
for (uint32_t i = 0;; ++i) {
|
||||
pblockTemp->block.nNonce = i;
|
||||
if (CheckProofOfWork(pblockTemp->block.GetPoWHash(), pblockTemp->block.nBits, Params().GetConsensus())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
bool success = ProcessNewBlock(Params(), std::make_shared<const CBlock>(pblockTemp->block), true, nullptr);
|
||||
// will process , but will not be connected
|
||||
BOOST_CHECK(success);
|
||||
BOOST_CHECK(pblockTemp->block.GetHash() != chainActive.Tip()->GetBlockHash());
|
||||
BOOST_CHECK_EQUAL(orig_chain_height, chainActive.Height());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
@@ -0,0 +1,494 @@
|
||||
// Copyright (c) 2015-2019 The LBRY Foundation
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://opensource.org/licenses/mit-license.php
|
||||
|
||||
#include <test/claimtriefixture.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(claimtrienormalization_tests, RegTestingSetup)
|
||||
|
||||
/*
|
||||
normalization
|
||||
test normalization function indpendent from rest of the code
|
||||
*/
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalization_only)
|
||||
{
|
||||
CClaimTrieCache ccache(pclaimTrie);
|
||||
|
||||
// basic ASCII casing tests
|
||||
BOOST_CHECK_EQUAL("test", ccache.normalizeClaimName("TESt", true));
|
||||
BOOST_CHECK_EQUAL("test", ccache.normalizeClaimName("tesT", true));
|
||||
BOOST_CHECK_EQUAL("test", ccache.normalizeClaimName("TesT", true));
|
||||
BOOST_CHECK_EQUAL("test", ccache.normalizeClaimName("test", true));
|
||||
BOOST_CHECK_EQUAL("test this", ccache.normalizeClaimName("Test This", true));
|
||||
|
||||
// test invalid utf8 bytes are returned as is
|
||||
BOOST_CHECK_EQUAL("\xFF", ccache.normalizeClaimName("\xFF", true));
|
||||
BOOST_CHECK_EQUAL("\xC3\x28", ccache.normalizeClaimName("\xC3\x28", true));
|
||||
|
||||
// ohm sign unicode code point \x2126 should be transformed to equivalent
|
||||
// unicode code point \x03C9 , greek small letter omega
|
||||
BOOST_CHECK_EQUAL("\xCF\x89", ccache.normalizeClaimName("\xE2\x84\xA6", true));
|
||||
|
||||
// cyrillic capital ef code point \x0424 should be transformed to lower case
|
||||
// \x0444
|
||||
BOOST_CHECK_EQUAL("\xD1\x84", ccache.normalizeClaimName("\xD0\xA4", true));
|
||||
|
||||
// armenian capital ben code point \x0532 should be transformed to lower case
|
||||
// \x0562
|
||||
BOOST_CHECK_EQUAL("\xD5\xA2", ccache.normalizeClaimName("\xD4\xB2", true));
|
||||
|
||||
// japanese pbu code point \x3076 should be transformed by NFD decomposition
|
||||
// into \x3075 and \x3099
|
||||
BOOST_CHECK_EQUAL("\xE3\x81\xB5\xE3\x82\x99",
|
||||
ccache.normalizeClaimName("\xE3\x81\xB6", true));
|
||||
|
||||
// hangul ggwalg unicode code point \xAF51 should be transformed by NFD
|
||||
// decomposition into unicode code points \x1101 \x116A \x11B0
|
||||
// source: http://unicode.org/L2/L2009/09052-tr47.html
|
||||
BOOST_CHECK_EQUAL("\xE1\x84\x81\xE1\x85\xAA\xE1\x86\xB0",
|
||||
ccache.normalizeClaimName("\xEA\xBD\x91", true));
|
||||
}
|
||||
|
||||
/*
|
||||
normalization
|
||||
check claim name normalization before the fork
|
||||
check claim name normalization after the fork
|
||||
*/
|
||||
BOOST_AUTO_TEST_CASE(claimtriebranching_normalization)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
// check claim names are not normalized
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "normalizeTest", "one", 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizeTest", tx1));
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.getTotalNamesInTrie() == 0);
|
||||
fixture.CommitTx(tx1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizeTest", tx1));
|
||||
|
||||
CMutableTransaction tx2a = fixture.MakeClaim(fixture.GetCoinbase(), "Normalizetest", "one_a", 2);
|
||||
CMutableTransaction tx2 = fixture.MakeUpdate(tx2a, "Normalizetest", "one", ClaimIdHash(tx2a.GetHash(), 0), 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizeTest", tx1));
|
||||
BOOST_CHECK(fixture.is_best_claim("Normalizetest", tx2));
|
||||
|
||||
// Activate the fork (which rebuilds the existing claimtrie and
|
||||
// cache), flattening all previously existing name clashes due to
|
||||
// the normalization
|
||||
fixture.setNormalizationForkHeight(2);
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizeTest", tx1));
|
||||
BOOST_CHECK(fixture.is_best_claim("Normalizetest", tx2));
|
||||
|
||||
fixture.IncrementBlocks(1, true);
|
||||
|
||||
// Post-fork, tx1 (the previous winning claim) assumes all name
|
||||
// variants of what it originally was ...
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", tx1));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("normalizetest", 3));
|
||||
|
||||
BOOST_CHECK(!pclaimTrie->find("normalizeTest"));
|
||||
|
||||
// Check equivalence of normalized claim names
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", tx1)); // collapsed tx2
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "NORMALIZETEST", "one", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.is_best_claim("normalizetest", tx3));
|
||||
|
||||
CMutableTransaction s1 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, "NoRmAlIzEtEsT", 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
// Ensure that supports work for normalized claim names
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", tx1)); // effective amount is 5
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("normalizetest", 5));
|
||||
|
||||
CMutableTransaction tx4 = fixture.MakeClaim(fixture.GetCoinbase(), "foo", "bar", 1);
|
||||
CMutableTransaction s2 = fixture.MakeSupport(fixture.GetCoinbase(), tx4, "Foo", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("foo", tx4));
|
||||
|
||||
CMutableTransaction u1 = fixture.MakeUpdate(tx4, "foo", "baz", ClaimIdHash(tx4.GetHash(), 0), 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("foo", u1));
|
||||
|
||||
CMutableTransaction u2 = fixture.MakeUpdate(tx1, "nOrmalIzEtEst", "two", ClaimIdHash(tx1.GetHash(), 0), 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", u2));
|
||||
|
||||
// Add another set of unicode claims that will collapse after the fork
|
||||
CMutableTransaction tx5 = fixture.MakeClaim(fixture.GetCoinbase(), "Ame\u0301lie", "amelie", 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
CClaimValue nval1;
|
||||
fixture.getInfoForName("amélie", nval1);
|
||||
BOOST_CHECK(nval1.claimId == ClaimIdHash(tx5.GetHash(), 0));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("amélie", 2));
|
||||
|
||||
// Check equivalence of normalized claim names
|
||||
BOOST_CHECK(fixture.is_best_claim("amélie", tx5));
|
||||
|
||||
CMutableTransaction tx7 = fixture.MakeClaim(fixture.GetCoinbase(), "あてはまる", "jn1", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("あてはまる", tx7));
|
||||
|
||||
CMutableTransaction tx8 = fixture.MakeClaim(fixture.GetCoinbase(), "AÑEJO", "es1", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("añejo", tx8));
|
||||
|
||||
// Rewind to 1 block before the fork and be sure that the fork is no longer active
|
||||
fixture.DecrementBlocks();
|
||||
|
||||
// Now check that our old (non-normalized) claims are 'alive' again
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizeTest", tx1));
|
||||
BOOST_CHECK(!fixture.is_best_claim("Normalizetest", tx1)); // no longer equivalent
|
||||
BOOST_CHECK(fixture.is_best_claim("Normalizetest", tx2));
|
||||
|
||||
// Create new claim
|
||||
CMutableTransaction tx9 = fixture.MakeClaim(fixture.GetCoinbase(), "blah", "blah", 1);
|
||||
std::string invalidUtf8("\xFF\xFF");
|
||||
CMutableTransaction tx10 = fixture.MakeClaim(fixture.GetCoinbase(), invalidUtf8, "blah", 1); // invalid UTF8
|
||||
|
||||
// Roll forward to fork height again and check again that we're normalized
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(chainActive.Height() == Params().GetConsensus().nNormalizedNameForkHeight);
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", tx1)); // collapsed tx2
|
||||
BOOST_CHECK(fixture.is_best_claim(invalidUtf8, tx10));
|
||||
|
||||
// Rewind to 1 block before the fork and be sure that the fork is
|
||||
// no longer active
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("Normalizetest", tx2));
|
||||
|
||||
// Roll forward to fork height again and check again that we're normalized
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(chainActive.Height() == Params().GetConsensus().nNormalizedNameForkHeight);
|
||||
BOOST_CHECK(fixture.is_best_claim("normalizetest", tx1)); // collapsed tx2
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claimtriecache_normalization)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
std::string name = "Ame\u0301lie";
|
||||
|
||||
std::string name_upper = "Amélie";
|
||||
std::string name_normd = "amélie"; // this accented e is not actually the same as the one above; this has been "normalized"
|
||||
|
||||
BOOST_CHECK(name != name_upper);
|
||||
|
||||
// Add another set of unicode claims that will collapse after the fork
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), name, "amilie", 2);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), name_upper, "amelie", 2);
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), "amelie1", "amelie", 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
CClaimValue lookupClaim;
|
||||
std::string lookupName;
|
||||
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
|
||||
BOOST_CHECK(!fixture.getInfoForName(name_normd, nval1));
|
||||
|
||||
// Activate the fork (which rebuilds the existing claimtrie and
|
||||
// cache), flattening all previously existing name clashes due to
|
||||
// the normalization
|
||||
fixture.setNormalizationForkHeight(1);
|
||||
int currentHeight = chainActive.Height();
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
// Ok normalization fix the name problem
|
||||
BOOST_CHECK(fixture.getInfoForName(name_normd, nval1));
|
||||
BOOST_CHECK(nval1.nHeight == currentHeight);
|
||||
BOOST_CHECK(lookupClaim == nval1);
|
||||
|
||||
CCoinsViewCache coins(pcoinsTip.get());
|
||||
CClaimTrieCache trieCache(pclaimTrie);
|
||||
CBlockIndex* pindex = chainActive.Tip();
|
||||
CBlock block;
|
||||
int amelieValidHeight;
|
||||
BOOST_CHECK(trieCache.shouldNormalize());
|
||||
BOOST_CHECK(ReadBlockFromDisk(block, pindex, Params().GetConsensus()));
|
||||
BOOST_CHECK(g_chainstate.DisconnectBlock(block, pindex, coins, trieCache) == DisconnectResult::DISCONNECT_OK);
|
||||
BOOST_CHECK(!trieCache.shouldNormalize());
|
||||
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(!pclaimTrie->find(name));
|
||||
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));
|
||||
insertUndoType insertUndo;
|
||||
claimQueueRowType expireUndo;
|
||||
insertUndoType insertSupportUndo;
|
||||
supportQueueRowType expireSupportUndo;
|
||||
std::vector<std::pair<std::string, int> > takeoverHeightUndo;
|
||||
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->cbegin(); it != pclaimTrie->cend(); ++it)
|
||||
BOOST_CHECK(it.key() != name);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(undo_normalization_does_not_kill_claim_order)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setNormalizationForkHeight(5);
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "1", 1);
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "a", "3", 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "2", 2);
|
||||
fixture.IncrementBlocks(2);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
fixture.IncrementBlocks(3, true);
|
||||
BOOST_CHECK(fixture.is_best_claim("a", tx3));
|
||||
fixture.DecrementBlocks();
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalized_activations_fall_through)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setNormalizationForkHeight(5);
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "AB", "1", 1);
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(fixture.proportionalDelayFactor() == 1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "Ab", "2", 4);
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "aB", "2", 3);
|
||||
CMutableTransaction tx4 = fixture.MakeClaim(fixture.GetCoinbase(), "ab", "2", 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
BOOST_CHECK(fixture.is_best_claim("AB", tx1));
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(fixture.is_best_claim("ab", tx2));
|
||||
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").claimsNsupports.size() == 2U);
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("AB", tx1));
|
||||
fixture.Spend(tx1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("ab", tx2));
|
||||
|
||||
for (int i = 0; i < 7; ++i) {
|
||||
fixture.IncrementBlocks(i, true); // well into normalized teritory
|
||||
CMutableTransaction tx5 = fixture.MakeClaim(fixture.GetCoinbase(), "CD", "a", 1 + i);
|
||||
fixture.IncrementBlocks(3);
|
||||
CMutableTransaction tx6 = fixture.MakeClaim(fixture.GetCoinbase(), "Cd", "b", 2 + i);
|
||||
CMutableTransaction tx7 = fixture.MakeClaim(fixture.GetCoinbase(), "cD", "c", 3 + i);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("cd", tx5));
|
||||
fixture.Spend(tx5);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("cd", tx7));
|
||||
fixture.DecrementBlocks();
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalization_removal_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setNormalizationForkHeight(2);
|
||||
fixture.IncrementBlocks(3);
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "AB", "1", 1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "Ab", "2", 2);
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "aB", "3", 3);
|
||||
CMutableTransaction sx1 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, "AB", 1);
|
||||
CMutableTransaction sx2 = fixture.MakeSupport(fixture.GetCoinbase(), tx2, "Ab", 1);
|
||||
|
||||
CClaimTrieCache cache(pclaimTrie);
|
||||
int height = chainActive.Height() + 1;
|
||||
cache.addClaim("AB", COutPoint(tx1.GetHash(), 0), ClaimIdHash(tx1.GetHash(), 0), 1, height);
|
||||
cache.addClaim("Ab", COutPoint(tx2.GetHash(), 0), ClaimIdHash(tx2.GetHash(), 0), 2, height);
|
||||
cache.addClaim("aB", COutPoint(tx3.GetHash(), 0), ClaimIdHash(tx3.GetHash(), 0), 3, height);
|
||||
cache.addSupport("AB", COutPoint(sx1.GetHash(), 0), 1, ClaimIdHash(tx1.GetHash(), 0), height);
|
||||
cache.addSupport("Ab", COutPoint(sx2.GetHash(), 0), 1, ClaimIdHash(tx2.GetHash(), 0), height);
|
||||
insertUndoType insertUndo;
|
||||
claimQueueRowType expireUndo;
|
||||
insertUndoType insertSupportUndo;
|
||||
supportQueueRowType expireSupportUndo;
|
||||
std::vector<std::pair<std::string, int> > takeoverHeightUndo;
|
||||
BOOST_CHECK(cache.incrementBlock(insertUndo, expireUndo, insertSupportUndo, expireSupportUndo, takeoverHeightUndo));
|
||||
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));
|
||||
BOOST_CHECK(cache.undoAddSupport("Ab", COutPoint(sx2.GetHash(), 0), height));
|
||||
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").claimsNsupports.size() == 0U);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalization_does_not_kill_supports)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setNormalizationForkHeight(3);
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "1", 1);
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx1, "A", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 2));
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx1, "A", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 3));
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx1, "A", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("a", 4));
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx1, "A", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("a", 5));
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("a", 4));
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 3));
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 2));
|
||||
fixture.IncrementBlocks(5);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("a", 3));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalization_does_not_fail_on_spend)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setNormalizationForkHeight(2);
|
||||
|
||||
std::string sName1("testN");
|
||||
std::string sName2("testn");
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, "1", 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim(sName1, tx1));
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, "2", 2);
|
||||
CMutableTransaction tx1s = fixture.MakeSupport(fixture.GetCoinbase(), tx1, sName1, 2);
|
||||
fixture.IncrementBlocks(2, true);
|
||||
BOOST_CHECK(fixture.is_best_claim(sName2, tx1));
|
||||
|
||||
CMutableTransaction tx3 = fixture.Spend(tx1); // abandon the claim
|
||||
CMutableTransaction tx3s = fixture.Spend(tx1s);
|
||||
fixture.IncrementBlocks(2);
|
||||
BOOST_CHECK(fixture.is_best_claim(sName2, tx2));
|
||||
fixture.DecrementBlocks();
|
||||
BOOST_CHECK(fixture.is_best_claim(sName1, tx1));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalization_does_not_kill_sort_order)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
fixture.setNormalizationForkHeight(2);
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "1", 1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "2", 2);
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "a", "3", 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
BOOST_CHECK(fixture.is_best_claim("a", tx3));
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.is_best_claim("A", tx2));
|
||||
BOOST_CHECK(fixture.is_best_claim("a", tx3));
|
||||
BOOST_CHECK(fixture.getClaimsForName("a").claimsNsupports.size() == 3U);
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.is_best_claim("A", tx2));
|
||||
BOOST_CHECK(fixture.is_best_claim("a", tx3));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(normalization_does_not_kill_expirations)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
auto& consensus = Params().GetConsensus();
|
||||
fixture.setExpirationForkHeight(consensus.nExtendedClaimExpirationForkHeight, 3, consensus.nExtendedClaimExpirationTime);
|
||||
fixture.setNormalizationForkHeight(4);
|
||||
// need to see that claims expiring on the frame when we normalize aren't kept
|
||||
// need to see that supports expiring on the frame when we normalize aren't kept
|
||||
// need to see that claims & supports carried through the normalization fork do expire
|
||||
// and that they come back correctly when we roll backwards
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), "A", "1", 1);
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx1, "A", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 2));
|
||||
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), "B", "1", 1);
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx2, "B", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("B", 2));
|
||||
|
||||
CMutableTransaction tx3 = fixture.MakeClaim(fixture.GetCoinbase(), "C", "1", 1);
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx3, "C", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("B", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("C", 2));
|
||||
|
||||
CMutableTransaction tx4 = fixture.MakeClaim(fixture.GetCoinbase(), "D", "1", 1);
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx4, "D", 1);
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("a", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("b", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("c", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("d", 2));
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("a", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("b", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("c", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("d", 2));
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("a", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("b", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("c", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("d", 2));
|
||||
|
||||
fixture.IncrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("a", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("b", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("c", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("d", 2));
|
||||
|
||||
fixture.DecrementBlocks(2);
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("a", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("b", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("c", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("d", 2));
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("a", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("b", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("c", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("d", 2));
|
||||
|
||||
fixture.DecrementBlocks(1);
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("A", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("B", 2));
|
||||
BOOST_CHECK(fixture.best_claim_effective_amount_equals("C", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("d", 2));
|
||||
|
||||
fixture.IncrementBlocks(3);
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("a", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("b", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("c", 2));
|
||||
BOOST_CHECK(!fixture.best_claim_effective_amount_equals("d", 2)); // (not re-added)
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
@@ -0,0 +1,407 @@
|
||||
// Copyright (c) 2015-2019 The LBRY Foundation
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://opensource.org/licenses/mit-license.php
|
||||
|
||||
#include <test/claimtriefixture.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
extern void ValidatePairs(CClaimTrieCache& cache, const std::vector<std::pair<bool, uint256>>& pairs, uint256 claimHash);
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(claimtrierpc_tests, RegTestingSetup)
|
||||
|
||||
BOOST_AUTO_TEST_CASE(getnamesintrie_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
std::string sName1("test");
|
||||
std::string sValue1("test");
|
||||
|
||||
uint256 blockHash = chainActive.Tip()->GetBlockHash();
|
||||
|
||||
fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue1, 42);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
rpcfn_type getnamesintrie = tableRPC["getnamesintrie"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
|
||||
UniValue results = getnamesintrie(req);
|
||||
BOOST_CHECK_EQUAL(results.size(), 1U);
|
||||
|
||||
req.params.push_back(blockHash.GetHex());
|
||||
|
||||
results = getnamesintrie(req);
|
||||
BOOST_CHECK_EQUAL(results.size(), 0U);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(getvalueforname_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
std::string sName1("testN");
|
||||
std::string sValue1("testV");
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue1, 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
uint256 blockHash = chainActive.Tip()->GetBlockHash();
|
||||
|
||||
fixture.MakeSupport(fixture.GetCoinbase(), tx1, sName1, 3);
|
||||
fixture.IncrementBlocks(10);
|
||||
|
||||
rpcfn_type getvalueforname = tableRPC["getvalueforname"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(sName1));
|
||||
|
||||
UniValue results = getvalueforname(req);
|
||||
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[T_AMOUNT].get_int(), 2);
|
||||
BOOST_CHECK_EQUAL(results[T_EFFECTIVEAMOUNT].get_int(), 2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(getclaimsforname_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
std::string sName1("testN");
|
||||
std::string sValue1("test1");
|
||||
std::string sValue2("test2");
|
||||
|
||||
int height = chainActive.Height();
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue1, 2);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
uint256 blockHash = chainActive.Tip()->GetBlockHash();
|
||||
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue2, 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
rpcfn_type getclaimsforname = tableRPC["getclaimsforname"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(sName1));
|
||||
|
||||
UniValue results = getclaimsforname(req);
|
||||
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[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 2U);
|
||||
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[T_CLAIMS];
|
||||
BOOST_CHECK_EQUAL(claims.size(), 1U);
|
||||
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)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
std::string sName1("testN");
|
||||
std::string sValue1("test1");
|
||||
std::string sValue2("test2");
|
||||
|
||||
int height = chainActive.Height();
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue1, 1);
|
||||
fixture.IncrementBlocks(2);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue2, 2);
|
||||
fixture.IncrementBlocks(3);
|
||||
|
||||
uint256 blockHash = chainActive.Tip()->GetBlockHash();
|
||||
|
||||
CMutableTransaction tx3 = fixture.MakeSupport(fixture.GetCoinbase(), tx1, sValue1, 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
rpcfn_type getclaimsforname = tableRPC["getclaimsforname"]->actor;
|
||||
rpcfn_type getvalueforname = tableRPC["getvalueforname"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
req.params.push_back(UniValue(sName1));
|
||||
req.params.push_back(blockHash.GetHex());
|
||||
|
||||
UniValue claimsResults = getclaimsforname(req);
|
||||
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[T_VALUE].get_str(), HexStr(sValue2));
|
||||
BOOST_CHECK_EQUAL(valueResults[T_AMOUNT].get_int(), 2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_rpcs_rollback3_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
std::string sName1("testN");
|
||||
std::string sValue1("test1");
|
||||
std::string sValue2("test2");
|
||||
|
||||
int height = chainActive.Height();
|
||||
|
||||
CMutableTransaction tx1 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue1, 3);
|
||||
fixture.IncrementBlocks(1);
|
||||
CMutableTransaction tx2 = fixture.MakeClaim(fixture.GetCoinbase(), sName1, sValue2, 2);
|
||||
fixture.IncrementBlocks(2);
|
||||
|
||||
uint256 blockHash = chainActive.Tip()->GetBlockHash();
|
||||
|
||||
CMutableTransaction tx3 = fixture.Spend(tx1); // abandon the claim
|
||||
fixture.IncrementBlocks(1);
|
||||
|
||||
rpcfn_type getclaimsforname = tableRPC["getclaimsforname"]->actor;
|
||||
rpcfn_type getvalueforname = tableRPC["getvalueforname"]->actor;
|
||||
rpcfn_type getblocktemplate = tableRPC["getblocktemplate"]->actor;
|
||||
|
||||
JSONRPCRequest req;
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
UniValue templateResults = getblocktemplate(req);
|
||||
BOOST_CHECK_EQUAL(templateResults["claimtrie"].get_str(), chainActive.Tip()->hashClaimTrie.GetHex());
|
||||
|
||||
req.params.push_back(UniValue(sName1));
|
||||
req.params.push_back(blockHash.GetHex());
|
||||
|
||||
UniValue claimsResults = getclaimsforname(req);
|
||||
BOOST_CHECK_EQUAL(claimsResults[T_LASTTAKEOVERHEIGHT].get_int(), height + 1);
|
||||
|
||||
UniValue valueResults = getvalueforname(req);
|
||||
BOOST_CHECK_EQUAL(valueResults[T_VALUE].get_str(), HexStr(sValue1));
|
||||
BOOST_CHECK_EQUAL(valueResults[T_AMOUNT].get_int(), 3);
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -28,7 +28,7 @@
|
||||
"76a91453c0307d6851aa0ce7825ba883c6bd9ad242b48688ac",
|
||||
{
|
||||
"isPrivkey": false,
|
||||
"chain": "regtest"
|
||||
"chain": "lbrycrdreg"
|
||||
}
|
||||
],
|
||||
[
|
||||
@@ -72,7 +72,7 @@
|
||||
{
|
||||
"isCompressed": false,
|
||||
"isPrivkey": true,
|
||||
"chain": "regtest"
|
||||
"chain": "lbrycrdreg"
|
||||
}
|
||||
],
|
||||
[
|
||||
@@ -90,7 +90,7 @@
|
||||
{
|
||||
"isCompressed": true,
|
||||
"isPrivkey": true,
|
||||
"chain": "regtest"
|
||||
"chain": "lbrycrdreg"
|
||||
}
|
||||
],
|
||||
[
|
||||
@@ -294,7 +294,7 @@
|
||||
{
|
||||
"isCompressed": false,
|
||||
"isPrivkey": true,
|
||||
"chain": "regtest"
|
||||
"chain": "lbrycrdreg"
|
||||
}
|
||||
],
|
||||
[
|
||||
@@ -481,7 +481,7 @@
|
||||
"001428e40f9a66993a8d50b2604af71b17e1606842d8",
|
||||
{
|
||||
"isPrivkey": false,
|
||||
"chain": "regtest",
|
||||
"chain": "lbrycrdreg",
|
||||
"tryCaseFlip": true
|
||||
}
|
||||
]
|
||||
|
||||
@@ -458,9 +458,6 @@
|
||||
["NOP", "CHECKSEQUENCEVERIFY 1", "P2SH,STRICTENC", "OK"],
|
||||
["NOP", "NOP4 1", "P2SH,STRICTENC", "OK"],
|
||||
["NOP", "NOP5 1", "P2SH,STRICTENC", "OK"],
|
||||
["NOP", "NOP6 1", "P2SH,STRICTENC", "OK"],
|
||||
["NOP", "NOP7 1", "P2SH,STRICTENC", "OK"],
|
||||
["NOP", "NOP8 1", "P2SH,STRICTENC", "OK"],
|
||||
["NOP", "NOP9 1", "P2SH,STRICTENC", "OK"],
|
||||
["NOP", "NOP10 1", "P2SH,STRICTENC", "OK"],
|
||||
|
||||
@@ -869,8 +866,8 @@
|
||||
["2 2 LSHIFT", "8 EQUAL", "P2SH,STRICTENC", "DISABLED_OPCODE", "disabled"],
|
||||
["2 1 RSHIFT", "1 EQUAL", "P2SH,STRICTENC", "DISABLED_OPCODE", "disabled"],
|
||||
|
||||
["1", "NOP1 CHECKLOCKTIMEVERIFY CHECKSEQUENCEVERIFY NOP4 NOP5 NOP6 NOP7 NOP8 NOP9 NOP10 2 EQUAL", "P2SH,STRICTENC", "EVAL_FALSE"],
|
||||
["'NOP_1_to_10' NOP1 CHECKLOCKTIMEVERIFY CHECKSEQUENCEVERIFY NOP4 NOP5 NOP6 NOP7 NOP8 NOP9 NOP10","'NOP_1_to_11' EQUAL", "P2SH,STRICTENC", "EVAL_FALSE"],
|
||||
["1", "NOP1 CHECKLOCKTIMEVERIFY CHECKSEQUENCEVERIFY NOP4 NOP5 NOP9 NOP10 2 EQUAL", "P2SH,STRICTENC", "EVAL_FALSE"],
|
||||
["'NOP_1_to_10' NOP1 CHECKLOCKTIMEVERIFY CHECKSEQUENCEVERIFY NOP4 NOP5 NOP9 NOP10","'NOP_1_to_11' EQUAL", "P2SH,STRICTENC", "EVAL_FALSE"],
|
||||
|
||||
["Ensure 100% coverage of discouraged NOPS"],
|
||||
["1", "NOP1", "P2SH,DISCOURAGE_UPGRADABLE_NOPS", "DISCOURAGE_UPGRADABLE_NOPS"],
|
||||
@@ -1793,7 +1790,7 @@
|
||||
"2-of-2 with two identical keys and sigs pushed using OP_DUP"
|
||||
],
|
||||
[
|
||||
"0x47 0x3044022018a2a81a93add5cb5f5da76305718e4ea66045ec4888b28d84cb22fae7f4645b02201e6daa5ed5d2e4b2b2027cf7ffd43d8d9844dd49f74ef86899ec8e669dfd39aa01 NOP8 0x23 0x2103363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640ac",
|
||||
"0x47 0x3044022018a2a81a93add5cb5f5da76305718e4ea66045ec4888b28d84cb22fae7f4645b02201e6daa5ed5d2e4b2b2027cf7ffd43d8d9844dd49f74ef86899ec8e669dfd39aa01 NOP9 0x23 0x2103363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640ac",
|
||||
"HASH160 0x14 0x215640c2f72f0d16b4eced26762035a42ffed39a EQUAL",
|
||||
"",
|
||||
"OK",
|
||||
@@ -1807,14 +1804,14 @@
|
||||
"P2PK with non-push scriptSig but with P2SH validation"
|
||||
],
|
||||
[
|
||||
"0x47 0x3044022018a2a81a93add5cb5f5da76305718e4ea66045ec4888b28d84cb22fae7f4645b02201e6daa5ed5d2e4b2b2027cf7ffd43d8d9844dd49f74ef86899ec8e669dfd39aa01 NOP8 0x23 0x2103363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640ac",
|
||||
"0x47 0x3044022018a2a81a93add5cb5f5da76305718e4ea66045ec4888b28d84cb22fae7f4645b02201e6daa5ed5d2e4b2b2027cf7ffd43d8d9844dd49f74ef86899ec8e669dfd39aa01 NOP9 0x23 0x2103363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640ac",
|
||||
"HASH160 0x14 0x215640c2f72f0d16b4eced26762035a42ffed39a EQUAL",
|
||||
"P2SH",
|
||||
"SIG_PUSHONLY",
|
||||
"P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY"
|
||||
],
|
||||
[
|
||||
"0x47 0x3044022018a2a81a93add5cb5f5da76305718e4ea66045ec4888b28d84cb22fae7f4645b02201e6daa5ed5d2e4b2b2027cf7ffd43d8d9844dd49f74ef86899ec8e669dfd39aa01 NOP8 0x23 0x2103363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640ac",
|
||||
"0x47 0x3044022018a2a81a93add5cb5f5da76305718e4ea66045ec4888b28d84cb22fae7f4645b02201e6daa5ed5d2e4b2b2027cf7ffd43d8d9844dd49f74ef86899ec8e669dfd39aa01 NOP9 0x23 0x2103363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640ac",
|
||||
"HASH160 0x14 0x215640c2f72f0d16b4eced26762035a42ffed39a EQUAL",
|
||||
"SIGPUSHONLY",
|
||||
"SIG_PUSHONLY",
|
||||
|
||||
@@ -8,7 +8,6 @@ BOOST_FIXTURE_TEST_SUITE(nameclaim_tests, BasicTestingSetup)
|
||||
|
||||
BOOST_AUTO_TEST_CASE(calc_min_claimtrie_fee)
|
||||
{
|
||||
|
||||
CMutableTransaction tx;
|
||||
tx.vout.resize(1);
|
||||
tx.vout[0].scriptPubKey = ClaimNameScript("A","test");
|
||||
@@ -31,7 +30,18 @@ BOOST_AUTO_TEST_CASE(calc_min_claimtrie_fee)
|
||||
CMutableTransaction tx4;
|
||||
tx4.vout.resize(1);
|
||||
BOOST_CHECK_EQUAL(CalcMinClaimTrieFee(tx4,MIN_FEE_PER_NAMECLAIM_CHAR), 0);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(support_handles_value)
|
||||
{
|
||||
auto script = SupportClaimScript("s1", uint160(), "me value");
|
||||
int op = 0;
|
||||
std::vector<std::vector<unsigned char>> params;
|
||||
BOOST_CHECK(!DecodeClaimScript(script, op, params, false));
|
||||
params.clear();
|
||||
BOOST_CHECK(DecodeClaimScript(script, op, params));
|
||||
BOOST_CHECK(params[0][0] == 's');
|
||||
BOOST_CHECK(std::string(params[2].begin(), params[2].end()) == "me value");
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(scriptToAsmStr_output)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <random.h>
|
||||
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <test/claimtriefixture.h>
|
||||
#include <test/test_bitcoin.h>
|
||||
|
||||
#include <chrono>
|
||||
@@ -37,7 +38,79 @@ std::vector<std::string> random_strings(std::size_t count)
|
||||
|
||||
using namespace std;
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(prefixtrie_tests, BasicTestingSetup)
|
||||
BOOST_FIXTURE_TEST_SUITE(prefixtrie_tests, RegTestingSetup)
|
||||
|
||||
#ifndef MAC_OSX // can't find a random number generator that produces the same sequence on OSX
|
||||
BOOST_AUTO_TEST_CASE(triehash_fuzzer_test)
|
||||
{
|
||||
ClaimTrieChainFixture fixture;
|
||||
|
||||
auto envClaims = std::getenv("TRIEHASH_FUZZER_CLAIMS");
|
||||
auto envBlocks = std::getenv("TRIEHASH_FUZZER_BLOCKS");
|
||||
|
||||
const int claimsPerBlock = envClaims ? std::atoi(envClaims) : 100;
|
||||
const int blocks = envBlocks ? std::atoi(envBlocks) : 13;
|
||||
|
||||
auto names = random_strings(blocks * claimsPerBlock);
|
||||
|
||||
FastRandomContext frc(true);
|
||||
std::unordered_map<std::string, std::vector<CMutableTransaction>> existingClaims;
|
||||
std::vector<CMutableTransaction> existingSupports;
|
||||
std::string value(1024, 'c');
|
||||
|
||||
std::vector<CTransaction> cb {fixture.GetCoinbase()};
|
||||
for (int i = 0; i < blocks; ++i) {
|
||||
for (int j = 0; j < claimsPerBlock; ++j) {
|
||||
auto name = names[i * claimsPerBlock + j];
|
||||
auto supportFront = frc.randrange(4) == 0;
|
||||
auto supportBack = frc.randrange(4) == 0;
|
||||
auto removeClaim = frc.randrange(4) == 0;
|
||||
auto removeSupport = frc.randrange(4) == 0;
|
||||
auto hit = existingClaims.find(name);
|
||||
if (supportFront && hit != existingClaims.end() && hit->second.size()) {
|
||||
auto tx = fixture.MakeSupport(cb.back(), hit->second[frc.rand64() % hit->second.size()], name, 2);
|
||||
existingSupports.push_back(tx);
|
||||
cb.emplace_back(std::move(tx));
|
||||
}
|
||||
if (removeClaim && hit != existingClaims.end() && hit->second.size()) {
|
||||
auto idx = frc.rand64() % hit->second.size();
|
||||
fixture.Spend(hit->second[idx]);
|
||||
hit->second.erase(hit->second.begin() + idx);
|
||||
} else {
|
||||
auto tx = fixture.MakeClaim(cb.back(), name, value, 2);
|
||||
existingClaims[name].push_back(tx);
|
||||
hit = existingClaims.find(name);
|
||||
cb.emplace_back(std::move(tx));
|
||||
}
|
||||
if (supportBack && hit != existingClaims.end() && hit->second.size()) {
|
||||
auto tx = fixture.MakeSupport(cb.back(), hit->second[frc.rand64() % hit->second.size()], name, 2);
|
||||
existingSupports.push_back(tx);
|
||||
cb.emplace_back(std::move(tx));
|
||||
}
|
||||
if (removeSupport && (i & 7) == 7 && !existingSupports.empty()) {
|
||||
const auto tidx = frc.rand64() % existingSupports.size();
|
||||
const auto tx = existingSupports[tidx];
|
||||
fixture.Spend(tx);
|
||||
existingSupports.erase(existingSupports.begin() + tidx);
|
||||
}
|
||||
if (cb.back().GetValueOut() < 10 || cb.size() > 40000) {
|
||||
cb.clear();
|
||||
cb.push_back(fixture.GetCoinbase());
|
||||
}
|
||||
}
|
||||
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(), "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(insert_erase_test)
|
||||
{
|
||||
|
||||
@@ -719,16 +719,16 @@ BOOST_AUTO_TEST_CASE(script_build)
|
||||
).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
|
||||
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
|
||||
"P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true
|
||||
).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem());
|
||||
).PushSig(keys.key2).Add(CScript() << OP_NOP9).PushRedeem());
|
||||
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
|
||||
"P2PK with non-push scriptSig but with P2SH validation", 0
|
||||
).PushSig(keys.key2).Add(CScript() << OP_NOP9));
|
||||
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
|
||||
"P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true
|
||||
).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
|
||||
).PushSig(keys.key2).Add(CScript() << OP_NOP9).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
|
||||
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
|
||||
"P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true
|
||||
).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
|
||||
).PushSig(keys.key2).Add(CScript() << OP_NOP9).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
|
||||
tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
|
||||
"2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY
|
||||
).Num(0).PushSig(keys.key1).PushSig(keys.key1));
|
||||
|
||||
@@ -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)
|
||||
@@ -80,16 +81,24 @@ std::ostream& operator<<(std::ostream& os, const CClaimValue& claim)
|
||||
std::ostream& operator<<(std::ostream& os, const CSupportValue& support)
|
||||
{
|
||||
os << "support(" << support.outPoint.ToString()
|
||||
<< ", " << support.supportedClaimId.ToString()
|
||||
<< ", " << support.nAmount
|
||||
<< ", " << support.nHeight
|
||||
<< ", " << support.nValidAtHeight << ')';
|
||||
<< ", " << support.supportedClaimId.ToString()
|
||||
<< ", " << support.nAmount
|
||||
<< ", " << support.nHeight
|
||||
<< ", " << support.nValidAtHeight << ')';
|
||||
return os;
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -701,7 +701,7 @@ BOOST_AUTO_TEST_CASE(test_IsStandard)
|
||||
|
||||
// Check dust with default relay fee:
|
||||
CAmount nDustThreshold = 182 * dustRelayFee.GetFeePerK()/1000;
|
||||
BOOST_CHECK_EQUAL(nDustThreshold, 546);
|
||||
BOOST_CHECK_EQUAL(nDustThreshold, 182);
|
||||
// dust:
|
||||
t.vout[0].nValue = nDustThreshold - 1;
|
||||
BOOST_CHECK(!IsStandardTx(t, reason));
|
||||
|
||||
+11
-10
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <util.h>
|
||||
|
||||
#include <chainparamsbase.h>
|
||||
#include <clientversion.h>
|
||||
#include <primitives/transaction.h>
|
||||
#include <sync.h>
|
||||
@@ -558,27 +559,27 @@ BOOST_AUTO_TEST_CASE(util_GetChainName)
|
||||
std::string error;
|
||||
|
||||
test_args.ParseParameters(0, (char**)argv_testnet, error);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrd");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::MAIN);
|
||||
|
||||
test_args.ParseParameters(2, (char**)argv_testnet, error);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(2, (char**)argv_regtest, error);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "regtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::REGTEST);
|
||||
|
||||
test_args.ParseParameters(3, (char**)argv_test_no_reg, error);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(3, (char**)argv_both, error);
|
||||
BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
|
||||
|
||||
test_args.ParseParameters(0, (char**)argv_testnet, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(2, (char**)argv_testnet, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(2, (char**)argv_regtest, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
@@ -586,7 +587,7 @@ BOOST_AUTO_TEST_CASE(util_GetChainName)
|
||||
|
||||
test_args.ParseParameters(3, (char**)argv_test_no_reg, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(3, (char**)argv_both, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
@@ -598,11 +599,11 @@ BOOST_AUTO_TEST_CASE(util_GetChainName)
|
||||
|
||||
test_args.ParseParameters(0, (char**)argv_testnet, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(2, (char**)argv_testnet, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(2, (char**)argv_regtest, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
@@ -610,7 +611,7 @@ BOOST_AUTO_TEST_CASE(util_GetChainName)
|
||||
|
||||
test_args.ParseParameters(2, (char**)argv_test_no_reg, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), "lbrycrdtest");
|
||||
BOOST_CHECK_EQUAL(test_args.GetChainName(), CBaseChainParams::TESTNET);
|
||||
|
||||
test_args.ParseParameters(3, (char**)argv_both, error);
|
||||
test_args.ReadConfigString(testnetconf);
|
||||
|
||||
+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
|
||||
|
||||
+42
-51
@@ -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,12 @@ 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());
|
||||
}
|
||||
}
|
||||
if (!trieCache.empty())
|
||||
trieCache.dumpToLog(trieCache.find({}));
|
||||
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 +1925,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 +1932,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,8 +2040,8 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
|
||||
|
||||
if (trieCache.getMerkleHash() != block.hashClaimTrie)
|
||||
{
|
||||
if (!trieCache.empty() && trieCache.checkConsistency())
|
||||
trieCache.dumpToLog(trieCache.begin());
|
||||
if (!trieCache.empty()) // we could run checkConsistency here, but it would take a while
|
||||
trieCache.dumpToLog(trieCache.find({}));
|
||||
return state.DoS(100, error("ConnectBlock() : the merkle root of the claim trie does not match "
|
||||
"(actual=%s vs block=%s on height=%d)", trieCache.getMerkleHash().GetHex(),
|
||||
block.hashClaimTrie.GetHex(), pindex->nHeight), REJECT_INVALID, "bad-claim-merkle-hash");
|
||||
@@ -2192,7 +2184,7 @@ bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &
|
||||
// overwrite one. Still, use a conservative safety factor of 2.
|
||||
if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
|
||||
return state.Error("out of disk space");
|
||||
if (!pclaimTrie->SyncToDisk())
|
||||
if (mode == FlushStateMode::ALWAYS && !pclaimTrie->SyncToDisk())
|
||||
return state.Error("Failed to write to claim trie database");
|
||||
// Flush the chainstate (which may refer to block index entries).
|
||||
if (!pcoinsTip->Flush())
|
||||
@@ -2258,7 +2250,8 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar
|
||||
}
|
||||
|
||||
std::string warningMessages;
|
||||
if (!IsInitialBlockDownload())
|
||||
auto isInitialBlockDownload = IsInitialBlockDownload();
|
||||
if (!isInitialBlockDownload)
|
||||
{
|
||||
int nUpgraded = 0;
|
||||
const CBlockIndex* pindex = pindexNew;
|
||||
@@ -2293,21 +2286,19 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar
|
||||
}
|
||||
static int64_t lastBlockPrintTime = 0;
|
||||
auto currentTime = GetAdjustedTime();
|
||||
auto oldBlock = pindexNew->nTime + MAX_FUTURE_BLOCK_TIME < currentTime;
|
||||
if (!warningMessages.empty() || !oldBlock || lastBlockPrintTime < currentTime - 15 || LogAcceptCategory(BCLog::CLAIMS)) {
|
||||
if (!warningMessages.empty() || !isInitialBlockDownload || 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)" : "");
|
||||
isInitialBlockDownload ? " IBD" : "");
|
||||
if (!warningMessages.empty())
|
||||
LogPrintf(" warning='%s'", warningMessages); /* Continued */
|
||||
LogPrintf("\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/** Disconnect chainActive's tip.
|
||||
|
||||
@@ -203,6 +203,12 @@ 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) {
|
||||
return pindexPrev != nullptr && pindexPrev->nHeight + 1 >= params.nWitnessForkHeight ?
|
||||
ThresholdState::ACTIVE : ThresholdState::FAILED;
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
|
||||
+251
-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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -800,12 +808,11 @@ UniValue listnameclaims(const JSONRPCRequest& request)
|
||||
|
||||
if (request.fHelp || request.params.size() > 3)
|
||||
throw std::runtime_error(
|
||||
"listnameclaims includesuppports activeonly minconf\n"
|
||||
"listnameclaims ( includesuppports activeonly minconf )\n"
|
||||
"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,60 +880,101 @@ 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"
|
||||
"supportclaim \"name\" ( \"claimid\" amount \"value\" isTip ) \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\
|
||||
of the claim that will be supported, nout is the transaction output which contains the claim to be supported, and amount is the amount which will be added to the value of the claim. If the claim is currently the authoritative claim, this support will go into effect immediately \
|
||||
. 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())
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to find a claim named %s", sName));
|
||||
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 (!trieCache.allowSupportMetadata())
|
||||
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;
|
||||
@@ -1867,6 +1914,68 @@ static UniValue addmultisigaddress(const JSONRPCRequest& request)
|
||||
return result;
|
||||
}
|
||||
|
||||
static UniValue addtimelockedaddress(const JSONRPCRequest& request)
|
||||
{
|
||||
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
|
||||
CWallet* const pwallet = wallet.get();
|
||||
|
||||
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
|
||||
return NullUniValue;
|
||||
}
|
||||
|
||||
if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) {
|
||||
std::string msg = "addtimelockedaddress timelock address ( \"label\" \"address_type\" )\n"
|
||||
"\nAdd an address that can't be redeemed until timelock. Requires a new wallet backup.\n"
|
||||
"See `importaddress` for watchonly p2sh address support.\n"
|
||||
"If 'label' is specified, assign address to that label.\n"
|
||||
|
||||
"\nArguments:\n"
|
||||
"1. timelock (numeric, required) Block height if < 500 million or unix timestamp if greater.\n"
|
||||
"1. \"address\" (string, required) The destination wallet address.\n"
|
||||
"2. \"label\" (string, optional) A label to assign the addresses to.\n"
|
||||
"3. \"address_type\" (string, optional) The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -addresstype.\n"
|
||||
|
||||
"\nResult:\n"
|
||||
"{\n"
|
||||
" \"address\":\"address\", (string) The value of the new P2SH address.\n"
|
||||
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
|
||||
"}\n"
|
||||
;
|
||||
throw std::runtime_error(msg);
|
||||
}
|
||||
|
||||
auto timelock = request.params[0].get_int();
|
||||
std::string label;
|
||||
if (!request.params[2].isNull())
|
||||
label = LabelFromValue(request.params[2]);
|
||||
|
||||
LOCK2(cs_main, pwallet->cs_wallet);
|
||||
|
||||
auto address = request.params[1].get_str();
|
||||
CTxDestination destination = DecodeDestination(address);
|
||||
if (!IsValidDestination(destination)) {
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid LBRY address: ") + address);
|
||||
}
|
||||
auto destinationScript = GetScriptForDestination(destination);
|
||||
|
||||
OutputType output_type = pwallet->m_default_address_type;
|
||||
if (!request.params[3].isNull()) {
|
||||
if (!ParseOutputType(request.params[3].get_str(), output_type)) {
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[3].get_str()));
|
||||
}
|
||||
}
|
||||
|
||||
// Construct using pay-to-script-hash:
|
||||
CScript inner = (CScript() << CScriptNum(timelock) << OP_CHECKLOCKTIMEVERIFY << OP_DROP) + destinationScript;
|
||||
CTxDestination dest = AddAndGetDestinationForScript(*pwallet, inner, output_type);
|
||||
pwallet->SetAddressBook(dest, label, "timelock");
|
||||
|
||||
UniValue result(UniValue::VOBJ);
|
||||
result.pushKV("address", EncodeDestination(dest));
|
||||
result.pushKV("redeemScript", HexStr(inner.begin(), inner.end()));
|
||||
return result;
|
||||
}
|
||||
|
||||
class Witnessifier : public boost::static_visitor<bool>
|
||||
{
|
||||
public:
|
||||
@@ -3491,6 +3600,9 @@ static UniValue getwalletinfo(const JSONRPCRequest& request)
|
||||
" \"walletname\": xxxxx, (string) the wallet name\n"
|
||||
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
|
||||
" \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
|
||||
" \"available_balance\": xxxxxxx, (numeric) balance minus stakes in " + CURRENCY_UNIT + "\n"
|
||||
" \"staked_claim_balance\": xxxxxxx, (numeric) total in claim reservations in " + CURRENCY_UNIT + "\n"
|
||||
" \"staked_support_balance\": xxxxxxx, (numeric) total in support reservations in " + CURRENCY_UNIT + "\n"
|
||||
" \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
|
||||
" \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
|
||||
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
|
||||
@@ -3519,7 +3631,13 @@ static UniValue getwalletinfo(const JSONRPCRequest& request)
|
||||
size_t kpExternalSize = pwallet->KeypoolCountExternalKeys();
|
||||
obj.pushKV("walletname", pwallet->GetName());
|
||||
obj.pushKV("walletversion", pwallet->GetVersion());
|
||||
obj.pushKV("balance", ValueFromAmount(pwallet->GetBalance()));
|
||||
auto balance = pwallet->GetBalance();
|
||||
auto claims = pwallet->GetBalance(ISMINE_CLAIM);
|
||||
auto supports = pwallet->GetBalance(ISMINE_SUPPORT);
|
||||
obj.pushKV("balance", ValueFromAmount(balance));
|
||||
obj.pushKV("available_balance", ValueFromAmount(balance - claims - supports));
|
||||
obj.pushKV("staked_claim_balance", ValueFromAmount(claims));
|
||||
obj.pushKV("staked_support_balance", ValueFromAmount(supports));
|
||||
obj.pushKV("unconfirmed_balance", ValueFromAmount(pwallet->GetUnconfirmedBalance()));
|
||||
obj.pushKV("immature_balance", ValueFromAmount(pwallet->GetImmatureBalance()));
|
||||
obj.pushKV("txcount", (int)pwallet->mapWallet.size());
|
||||
@@ -4688,6 +4806,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)) {
|
||||
@@ -5247,6 +5367,7 @@ static const CRPCCommand commands[] =
|
||||
{ "wallet", "abandontransaction", &abandontransaction, {"txid"} },
|
||||
{ "wallet", "abortrescan", &abortrescan, {} },
|
||||
{ "wallet", "addmultisigaddress", &addmultisigaddress, {"nrequired","keys","label|account","address_type"} },
|
||||
{ "wallet", "addtimelockedaddress", &addtimelockedaddress, {"timelock", "address", "label|account","address_type"} },
|
||||
{ "hidden", "addwitnessaddress", &addwitnessaddress, {"address","p2sh"} },
|
||||
{ "wallet", "backupwallet", &backupwallet, {"destination"} },
|
||||
{ "wallet", "bumpfee", &bumpfee, {"txid", "options"} },
|
||||
|
||||
@@ -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);
|
||||
@@ -59,6 +63,10 @@ uint256 ClaimAName(const std::string& name, const std::string& data, const std::
|
||||
UniValue results = rpc_method(req);
|
||||
auto txid = results.get_str();
|
||||
uint256 ret;
|
||||
if (txid.find(' ') != std::string::npos) {
|
||||
fprintf(stderr, "Error creating claim: %s\n", txid.c_str());
|
||||
return ret;
|
||||
}
|
||||
ret.SetHex(txid);
|
||||
return ret;
|
||||
}
|
||||
@@ -67,13 +75,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 +91,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 +99,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 +118,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 +131,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 +139,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 +155,20 @@ uint256 AbandonAClaim(const uint256& txid, bool isSupport = false) {
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(claim_op_runthrough)
|
||||
{
|
||||
generateBlock(105);
|
||||
void ValidateBalance(double claims, double supports) {
|
||||
rpcfn_type rpc_method = tableRPC["getwalletinfo"]->actor;
|
||||
JSONRPCRequest req;
|
||||
req.URI = "/wallet/tester_wallet";
|
||||
req.params = UniValue(UniValue::VARR);
|
||||
UniValue results = rpc_method(req);
|
||||
BOOST_CHECK_EQUAL(claims, results["staked_claim_balance"].get_real());
|
||||
BOOST_CHECK_EQUAL(supports, results["staked_support_balance"].get_real());
|
||||
BOOST_CHECK_EQUAL(claims + supports, results["balance"].get_real() - results["available_balance"].get_real());
|
||||
}
|
||||
|
||||
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 +186,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();
|
||||
@@ -182,6 +205,8 @@ BOOST_AUTO_TEST_CASE(claim_op_runthrough)
|
||||
BOOST_CHECK_EQUAL(looked[1]["txid"].get_str(), spid.GetHex());
|
||||
BOOST_CHECK_EQUAL(looked[1]["supported_claimid"].get_str(), clid);
|
||||
|
||||
ValidateBalance(1.0, 0.5);
|
||||
|
||||
// abandon support
|
||||
auto aid1 = AbandonAClaim(spid, true);
|
||||
BOOST_CHECK(!aid1.IsNull());
|
||||
@@ -244,4 +269,227 @@ 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_CASE(can_claim_after_each_fork)
|
||||
{
|
||||
generateBlock(140);
|
||||
auto txid = ClaimAName("tester", "deadbeef", "1.0");
|
||||
BOOST_CHECK(!txid.IsNull());
|
||||
generateBlock(100);
|
||||
txid = ClaimAName("tester2", "deadbeef", "1.0");
|
||||
BOOST_CHECK(!txid.IsNull());
|
||||
generateBlock(100);
|
||||
txid = ClaimAName("tester3", "deadbeef", "10.0");
|
||||
BOOST_CHECK(!txid.IsNull());
|
||||
generateBlock(15);
|
||||
txid = ClaimAName("tester4", "deadbeef", "10.0");
|
||||
BOOST_CHECK(!txid.IsNull());
|
||||
generateBlock(1);
|
||||
auto looked = LookupAllNames().get_array();
|
||||
BOOST_CHECK_EQUAL(looked.size(), 4U);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
+17
-18
@@ -166,7 +166,7 @@ public:
|
||||
txnouttype type;
|
||||
std::vector<CTxDestination> vDest;
|
||||
int nRequired;
|
||||
if (ExtractDestinations(script, type, vDest, nRequired)) {
|
||||
if (ExtractDestinations(StripClaimScriptPrefix(script), type, vDest, nRequired)) {
|
||||
for (const CTxDestination &dest : vDest)
|
||||
boost::apply_visitor(*this, dest);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -2987,6 +2985,7 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CTransac
|
||||
if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
|
||||
unsigned int tx_size_with_change = nBytes + coin_selection_params.change_output_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
|
||||
CAmount fee_needed_with_change = GetMinimumFee(*this, tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
|
||||
fee_needed_with_change = std::max(minClaimTrieFee, fee_needed_with_change);
|
||||
CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
|
||||
if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
|
||||
pick_new_inputs = false;
|
||||
|
||||
@@ -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