diff --git a/lightningd/opening_control.c b/lightningd/opening_control.c index 0406f57da61a..1d3a4b3851f3 100644 --- a/lightningd/opening_control.c +++ b/lightningd/opening_control.c @@ -1480,13 +1480,10 @@ static struct channel *stub_chan(struct command *cmd, 144); /* If the channel is already stored, return NULL. */ - peer = peer_by_id(cmd->ld, &nodeid); - if (peer) { - if (find_channel_by_id(peer, &cid)) { - log_debug(cmd->ld->log, "channel %s already exists!", - fmt_channel_id(tmpctx, &cid)); - return NULL; - } + if (channel_exists_by_id(cmd->ld->wallet, id)) { + log_debug(cmd->ld->log, "channel %s already exists!", + fmt_channel_id(tmpctx, &cid)); + return NULL; } else { struct wireaddr_internal wint; diff --git a/wallet/wallet.c b/wallet/wallet.c index 4e98b8ef8eef..2b1e0fb7e009 100644 --- a/wallet/wallet.c +++ b/wallet/wallet.c @@ -2586,6 +2586,26 @@ static void wallet_peer_save(struct wallet *w, struct peer *peer) } } +bool channel_exists_by_id(struct wallet *w, u64 dbid) { + struct db_stmt *stmt; + stmt = db_prepare_v2(w->db, SQL("SELECT *" + " FROM channels" + " WHERE id = ?")); + + db_bind_u64(stmt, dbid); + db_query_prepared(stmt); + + /* If we found a result it means channel exists at that place. */ + if (db_step(stmt)) { + db_col_ignore(stmt, "*"); + tal_free(stmt); + return true; + } + + tal_free(stmt); + return false; +} + void wallet_channel_insert(struct wallet *w, struct channel *chan) { struct db_stmt *stmt; diff --git a/wallet/wallet.h b/wallet/wallet.h index 45f59d283449..cbb221196b29 100644 --- a/wallet/wallet.h +++ b/wallet/wallet.h @@ -607,6 +607,16 @@ void wallet_htlcsigs_confirm_inflight(struct wallet *w, struct channel *chan, */ void wallet_channel_save(struct wallet *w, struct channel *chan); +/** + * wallet_channels_by_dbid -- Check if an ID is preoccupied inside the `channels` table + * + * @wallet: the wallet + * @dbid: the ID at which we want to check the value. + * + * Returns `true` if it is occupied, false otherwise. +*/ +bool channel_exists_by_id(struct wallet *w, u64 dbid); + /** * wallet_channel_insert -- Insert the initial channel into the database *