@@ -3184,6 +3184,24 @@ bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interf
31843184
31853185 if (tip_height && *tip_height != rescan_height)
31863186 {
3187+ // No need to read and scan block if block was created before
3188+ // our wallet birthday (as adjusted for block time variability)
3189+ std::optional<int64_t > time_first_key;
3190+ for (auto spk_man : walletInstance->GetAllScriptPubKeyMans ()) {
3191+ int64_t time = spk_man->GetTimeFirstKey ();
3192+ if (!time_first_key || time < *time_first_key) time_first_key = time;
3193+ }
3194+ if (time_first_key) {
3195+ FoundBlock found = FoundBlock ().height (rescan_height);
3196+ chain.findFirstBlockWithTimeAndHeight (*time_first_key - TIMESTAMP_WINDOW, rescan_height, found);
3197+ if (!found.found ) {
3198+ // We were unable to find a block that had a time more recent than our earliest timestamp
3199+ // or a height higher than the wallet was synced to, indicating that the wallet is newer than the
3200+ // current chain tip. Skip rescanning in this case.
3201+ rescan_height = *tip_height;
3202+ }
3203+ }
3204+
31873205 // Technically we could execute the code below in any case, but performing the
31883206 // `while` loop below can make startup very slow, so only check blocks on disk
31893207 // if necessary.
@@ -3218,17 +3236,6 @@ bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interf
32183236 chain.initMessage (_ (" Rescanning…" ).translated );
32193237 walletInstance->WalletLogPrintf (" Rescanning last %i blocks (from block %i)...\n " , *tip_height - rescan_height, rescan_height);
32203238
3221- // No need to read and scan block if block was created before
3222- // our wallet birthday (as adjusted for block time variability)
3223- std::optional<int64_t > time_first_key;
3224- for (auto spk_man : walletInstance->GetAllScriptPubKeyMans ()) {
3225- int64_t time = spk_man->GetTimeFirstKey ();
3226- if (!time_first_key || time < *time_first_key) time_first_key = time;
3227- }
3228- if (time_first_key) {
3229- chain.findFirstBlockWithTimeAndHeight (*time_first_key - TIMESTAMP_WINDOW, rescan_height, FoundBlock ().height (rescan_height));
3230- }
3231-
32323239 {
32333240 WalletRescanReserver reserver (*walletInstance);
32343241 if (!reserver.reserve () || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions (chain.getBlockHash (rescan_height), rescan_height, /* max_height=*/ {}, reserver, /* fUpdate=*/ true , /* save_progress=*/ true ).status )) {
0 commit comments