diff --git a/lightningd/chaintopology.c b/lightningd/chaintopology.c index f977dc45823c..2f9b45976a25 100644 --- a/lightningd/chaintopology.c +++ b/lightningd/chaintopology.c @@ -1420,7 +1420,7 @@ void setup_topology(struct chain_topology *topo) fixup = db_get_intvar(topo->ld->wallet->db, "fixup_block_scan", -1); if (fixup == -1) { /* Never done fixup: this is set to non-zero if we have blocks. */ - topo->old_block_scan = wallet_blocks_minheight(topo->ld->wallet); + topo->old_block_scan = wallet_blocks_contig_minheight(topo->ld->wallet); db_set_intvar(topo->ld->wallet->db, "fixup_block_scan", topo->old_block_scan); } else { diff --git a/wallet/wallet.c b/wallet/wallet.c index f67be5ec88e8..a8f4da06b61c 100644 --- a/wallet/wallet.c +++ b/wallet/wallet.c @@ -2554,16 +2554,22 @@ u32 wallet_blocks_maxheight(struct wallet *w) return max; } -u32 wallet_blocks_minheight(struct wallet *w) +u32 wallet_blocks_contig_minheight(struct wallet *w) { u32 min = 0; - struct db_stmt *stmt = db_prepare_v2(w->db, SQL("SELECT MIN(height) FROM blocks;")); + struct db_stmt *stmt = db_prepare_v2(w->db, SQL("SELECT MAX(b.height)" + " FROM blocks b" + " WHERE NOT EXISTS (" + " SELECT 1" + " FROM blocks b2" + " WHERE b2.height = b.height - 1)")); db_query_prepared(stmt); - /* If we ever processed a block we'll get the latest block in the chain */ + /* If we ever processed a block we'll get the first block in + * the last run of blocks */ if (db_step(stmt)) { - if (!db_col_is_null(stmt, "MIN(height)")) { - min = db_col_int(stmt, "MIN(height)"); + if (!db_col_is_null(stmt, "MAX(b.height)")) { + min = db_col_int(stmt, "MAX(b.height)"); } } tal_free(stmt); diff --git a/wallet/wallet.h b/wallet/wallet.h index e367037db007..dcfc38782033 100644 --- a/wallet/wallet.h +++ b/wallet/wallet.h @@ -790,13 +790,14 @@ void wallet_channel_stats_incr_out_fulfilled(struct wallet *w, u64 cdbid, struct u32 wallet_blocks_maxheight(struct wallet *w); /** - * Retrieve the blockheight of the first block processed by lightningd. + * Retrieve the blockheight of the first block processed by lightningd (ignoring + * backfilled blocks for gossip). * * Will return the 0 if the wallet was never used before. * * @w: wallet to load from. */ -u32 wallet_blocks_minheight(struct wallet *w); +u32 wallet_blocks_contig_minheight(struct wallet *w); /** * wallet_extract_owned_outputs - given a tx, extract all of our outputs