@@ -3184,6 +3184,24 @@ bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interf
3184
3184
3185
3185
if (tip_height && *tip_height != rescan_height)
3186
3186
{
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
+
3187
3205
// Technically we could execute the code below in any case, but performing the
3188
3206
// `while` loop below can make startup very slow, so only check blocks on disk
3189
3207
// if necessary.
@@ -3218,17 +3236,6 @@ bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interf
3218
3236
chain.initMessage (_ (" Rescanning…" ).translated );
3219
3237
walletInstance->WalletLogPrintf (" Rescanning last %i blocks (from block %i)...\n " , *tip_height - rescan_height, rescan_height);
3220
3238
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
-
3232
3239
{
3233
3240
WalletRescanReserver reserver (*walletInstance);
3234
3241
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