Skip to content

Commit 8c2de82

Browse files
committed
Merge #7061: [Wallet] Add RPC call "rescanblockchain <startheight> <stopheight>"
7a91ceb [QA] Add RPC based rescan test (Jonas Schnelli) c77170f [Wallet] add rescanblockchain <start_height> <stop_height> RPC command (Jonas Schnelli) Pull request description: A RPC rescan command is much more flexible for the following reasons: * You can define the start and end-height * It can be called during runtime * It can work in multiwallet environment Tree-SHA512: df67177bad6ad1d08e5a621f095564524fa3eb87204c2048ef7265e77013e4b1b29f991708f807002329a507a254f35e79a4ed28a2d18d4b3da7a75d57ce0ea5
2 parents 424be03 + 7a91ceb commit 8c2de82

File tree

7 files changed

+117
-11
lines changed

7 files changed

+117
-11
lines changed

src/qt/test/wallettests.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ void TestGUI()
164164
wallet.SetAddressBook(test.coinbaseKey.GetPubKey().GetID(), "", "receive");
165165
wallet.AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey());
166166
}
167-
wallet.ScanForWalletTransactions(chainActive.Genesis(), true);
167+
wallet.ScanForWalletTransactions(chainActive.Genesis(), nullptr, true);
168168
wallet.SetBroadcastTransactions(true);
169169

170170
// Create widgets for sending coins and listing transactions.

src/rpc/client.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ static const CRPCConvertParam vRPCConvertParams[] =
141141
{ "echojson", 7, "arg7" },
142142
{ "echojson", 8, "arg8" },
143143
{ "echojson", 9, "arg9" },
144+
{ "rescanblockchain", 0, "start_height"},
145+
{ "rescanblockchain", 1, "stop_height"},
144146
};
145147

146148
class CRPCConvertTable

src/wallet/rpcwallet.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3212,6 +3212,81 @@ UniValue generate(const JSONRPCRequest& request)
32123212
return generateBlocks(coinbase_script, num_generate, max_tries, true);
32133213
}
32143214

3215+
UniValue rescanblockchain(const JSONRPCRequest& request)
3216+
{
3217+
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
3218+
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3219+
return NullUniValue;
3220+
}
3221+
3222+
if (request.fHelp || request.params.size() > 2) {
3223+
throw std::runtime_error(
3224+
"rescanblockchain (\"start_height\") (\"stop_height\")\n"
3225+
"\nRescan the local blockchain for wallet related transactions.\n"
3226+
"\nArguments:\n"
3227+
"1. \"start_height\" (numeric, optional) block height where the rescan should start\n"
3228+
"2. \"stop_height\" (numeric, optional) the last block height that should be scanned\n"
3229+
"\nResult:\n"
3230+
"{\n"
3231+
" \"start_height\" (numeric) The block height where the rescan has started. If omitted, rescan started from the genesis block.\n"
3232+
" \"stop_height\" (numeric) The height of the last rescanned block. If omitted, rescan stopped at the chain tip.\n"
3233+
"}\n"
3234+
"\nExamples:\n"
3235+
+ HelpExampleCli("rescanblockchain", "100000 120000")
3236+
+ HelpExampleRpc("rescanblockchain", "100000 120000")
3237+
);
3238+
}
3239+
3240+
LOCK2(cs_main, pwallet->cs_wallet);
3241+
3242+
CBlockIndex *pindexStart = chainActive.Genesis();
3243+
CBlockIndex *pindexStop = nullptr;
3244+
if (!request.params[0].isNull()) {
3245+
pindexStart = chainActive[request.params[0].get_int()];
3246+
if (!pindexStart) {
3247+
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid start_height");
3248+
}
3249+
}
3250+
3251+
if (!request.params[1].isNull()) {
3252+
pindexStop = chainActive[request.params[1].get_int()];
3253+
if (!pindexStop) {
3254+
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height");
3255+
}
3256+
else if (pindexStop->nHeight < pindexStart->nHeight) {
3257+
throw JSONRPCError(RPC_INVALID_PARAMETER, "stop_height must be greater then start_height");
3258+
}
3259+
}
3260+
3261+
// We can't rescan beyond non-pruned blocks, stop and throw an error
3262+
if (fPruneMode) {
3263+
CBlockIndex *block = pindexStop ? pindexStop : chainActive.Tip();
3264+
while (block && block->nHeight >= pindexStart->nHeight) {
3265+
if (!(block->nStatus & BLOCK_HAVE_DATA)) {
3266+
throw JSONRPCError(RPC_MISC_ERROR, "Can't rescan beyond pruned data. Use RPC call getblockchaininfo to determine your pruned height.");
3267+
}
3268+
block = block->pprev;
3269+
}
3270+
}
3271+
3272+
CBlockIndex *stopBlock = pwallet->ScanForWalletTransactions(pindexStart, pindexStop, true);
3273+
if (!stopBlock) {
3274+
if (pwallet->IsAbortingRescan()) {
3275+
throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted.");
3276+
}
3277+
// if we got a nullptr returned, ScanForWalletTransactions did rescan up to the requested stopindex
3278+
stopBlock = pindexStop ? pindexStop : chainActive.Tip();
3279+
}
3280+
else {
3281+
throw JSONRPCError(RPC_MISC_ERROR, "Rescan failed. Potentially corrupted data files.");
3282+
}
3283+
3284+
UniValue response(UniValue::VOBJ);
3285+
response.pushKV("start_height", pindexStart->nHeight);
3286+
response.pushKV("stop_height", stopBlock->nHeight);
3287+
return response;
3288+
}
3289+
32153290
extern UniValue abortrescan(const JSONRPCRequest& request); // in rpcdump.cpp
32163291
extern UniValue dumpprivkey(const JSONRPCRequest& request); // in rpcdump.cpp
32173292
extern UniValue importprivkey(const JSONRPCRequest& request);
@@ -3222,6 +3297,7 @@ extern UniValue importwallet(const JSONRPCRequest& request);
32223297
extern UniValue importprunedfunds(const JSONRPCRequest& request);
32233298
extern UniValue removeprunedfunds(const JSONRPCRequest& request);
32243299
extern UniValue importmulti(const JSONRPCRequest& request);
3300+
extern UniValue rescanblockchain(const JSONRPCRequest& request);
32253301

32263302
static const CRPCCommand commands[] =
32273303
{ // category name actor (function) argNames
@@ -3276,6 +3352,7 @@ static const CRPCCommand commands[] =
32763352
{ "wallet", "walletpassphrasechange", &walletpassphrasechange, {"oldpassphrase","newpassphrase"} },
32773353
{ "wallet", "walletpassphrase", &walletpassphrase, {"passphrase","timeout"} },
32783354
{ "wallet", "removeprunedfunds", &removeprunedfunds, {"txid"} },
3355+
{ "wallet", "rescanblockchain", &rescanblockchain, {"start_height", "stop_height"} },
32793356

32803357
{ "generating", "generate", &generate, {"nblocks","maxtries"} },
32813358
};

src/wallet/test/wallet_tests.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
386386
{
387387
CWallet wallet;
388388
AddKey(wallet, coinbaseKey);
389-
BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip));
389+
BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip, nullptr));
390390
BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN);
391391
}
392392

@@ -399,7 +399,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
399399
{
400400
CWallet wallet;
401401
AddKey(wallet, coinbaseKey);
402-
BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip));
402+
BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip, nullptr));
403403
BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN);
404404
}
405405

@@ -604,7 +604,7 @@ class ListCoinsTestingSetup : public TestChain100Setup
604604
bool firstRun;
605605
wallet->LoadWallet(firstRun);
606606
AddKey(*wallet, coinbaseKey);
607-
wallet->ScanForWalletTransactions(chainActive.Genesis());
607+
wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr);
608608
}
609609

610610
~ListCoinsTestingSetup()

src/wallet/wallet.cpp

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1568,7 +1568,7 @@ int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
15681568
LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
15691569

15701570
if (startBlock) {
1571-
const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1571+
const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
15721572
if (failedBlock) {
15731573
return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
15741574
}
@@ -1584,12 +1584,19 @@ int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
15841584
* Returns null if scan was successful. Otherwise, if a complete rescan was not
15851585
* possible (due to pruning or corruption), returns pointer to the most recent
15861586
* block that could not be scanned.
1587+
*
1588+
* If pindexStop is not a nullptr, the scan will stop at the block-index
1589+
* defined by pindexStop
15871590
*/
1588-
CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1591+
CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
15891592
{
15901593
int64_t nNow = GetTime();
15911594
const CChainParams& chainParams = Params();
15921595

1596+
if (pindexStop) {
1597+
assert(pindexStop->nHeight >= pindexStart->nHeight);
1598+
}
1599+
15931600
CBlockIndex* pindex = pindexStart;
15941601
CBlockIndex* ret = nullptr;
15951602
{
@@ -1617,6 +1624,9 @@ CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool f
16171624
} else {
16181625
ret = pindex;
16191626
}
1627+
if (pindex == pindexStop) {
1628+
break;
1629+
}
16201630
pindex = chainActive.Next(pindex);
16211631
}
16221632
if (pindex && fAbortRescan) {
@@ -3930,7 +3940,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
39303940
}
39313941

39323942
nStart = GetTimeMillis();
3933-
walletInstance->ScanForWalletTransactions(pindexRescan, true);
3943+
walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
39343944
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
39353945
walletInstance->SetBestChain(chainActive.GetLocator());
39363946
walletInstance->dbw->IncrementUpdateCounter();

src/wallet/wallet.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -919,7 +919,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface
919919
void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
920920
bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
921921
int64_t RescanFromTime(int64_t startTime, bool update);
922-
CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
922+
CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate = false);
923923
void ReacceptWalletTransactions();
924924
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
925925
// ResendWalletTransactionsBefore may only be called if fBroadcastTransactions!

test/functional/wallet-hd.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
connect_nodes_bi,
1111
)
1212
import shutil
13+
import os
1314

1415
class WalletHDTest(BitcoinTestFramework):
1516
def set_test_params(self):
@@ -70,9 +71,9 @@ def run_test (self):
7071
self.stop_node(1)
7172
# we need to delete the complete regtest directory
7273
# otherwise node1 would auto-recover all funds in flag the keypool keys as used
73-
shutil.rmtree(tmpdir + "/node1/regtest/blocks")
74-
shutil.rmtree(tmpdir + "/node1/regtest/chainstate")
75-
shutil.copyfile(tmpdir + "/hd.bak", tmpdir + "/node1/regtest/wallet.dat")
74+
shutil.rmtree(os.path.join(tmpdir, "node1/regtest/blocks"))
75+
shutil.rmtree(os.path.join(tmpdir, "node1/regtest/chainstate"))
76+
shutil.copyfile(os.path.join(tmpdir, "hd.bak"), os.path.join(tmpdir, "node1/regtest/wallet.dat"))
7677
self.start_node(1)
7778

7879
# Assert that derivation is deterministic
@@ -91,6 +92,22 @@ def run_test (self):
9192
self.start_node(1, extra_args=self.extra_args[1] + ['-rescan'])
9293
assert_equal(self.nodes[1].getbalance(), num_hd_adds + 1)
9394

95+
# Try a RPC based rescan
96+
self.stop_node(1)
97+
shutil.rmtree(os.path.join(tmpdir, "node1/regtest/blocks"))
98+
shutil.rmtree(os.path.join(tmpdir, "node1/regtest/chainstate"))
99+
shutil.copyfile(os.path.join(tmpdir, "hd.bak"), os.path.join(tmpdir, "node1/regtest/wallet.dat"))
100+
self.start_node(1, extra_args=self.extra_args[1])
101+
connect_nodes_bi(self.nodes, 0, 1)
102+
self.sync_all()
103+
out = self.nodes[1].rescanblockchain(0, 1)
104+
assert_equal(out['start_height'], 0)
105+
assert_equal(out['stop_height'], 1)
106+
out = self.nodes[1].rescanblockchain()
107+
assert_equal(out['start_height'], 0)
108+
assert_equal(out['stop_height'], self.nodes[1].getblockcount())
109+
assert_equal(self.nodes[1].getbalance(), num_hd_adds + 1)
110+
94111
# send a tx and make sure its using the internal chain for the changeoutput
95112
txid = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1)
96113
outs = self.nodes[1].decoderawtransaction(self.nodes[1].gettransaction(txid)['hex'])['vout']

0 commit comments

Comments
 (0)