diff --git a/wallet/wallet.c b/wallet/wallet.c index 26c7caf81..a7e9cb655 100644 --- a/wallet/wallet.c +++ b/wallet/wallet.c @@ -2,6 +2,7 @@ #include #include +#include struct wallet *wallet_new(const tal_t *ctx, struct log *log) { @@ -221,3 +222,13 @@ bool wallet_can_spend(struct wallet *w, const u8 *script, return false; } +s64 wallet_get_newindex(struct lightningd *ld) +{ + u64 newidx = db_get_intvar(ld->wallet->db, "bip32_max_index", 0) + 1; + + if (newidx == BIP32_INITIAL_HARDENED_CHILD) + return -1; + + db_set_intvar(ld->wallet->db, "bip32_max_index", newidx); + return newidx; +} diff --git a/wallet/wallet.h b/wallet/wallet.h index f3f3064f0..e49fbc8cf 100644 --- a/wallet/wallet.h +++ b/wallet/wallet.h @@ -7,6 +7,8 @@ #include #include +struct lightningd; + struct wallet { struct db *db; struct log *log; @@ -104,4 +106,12 @@ void wallet_confirm_utxos(struct wallet *w, const struct utxo **utxos); bool wallet_can_spend(struct wallet *w, const u8 *script, u32 *index, bool *output_is_p2sh); +/** + * wallet_get_newindex - get a new index from the wallet. + * @ld: (in) lightning daemon + * + * Returns -1 on error (key exhaustion). + */ +s64 wallet_get_newindex(struct lightningd *ld); + #endif /* WALLET_WALLET_H */ diff --git a/wallet/walletrpc.c b/wallet/walletrpc.c index 5134d57a0..8f2c67c23 100644 --- a/wallet/walletrpc.c +++ b/wallet/walletrpc.c @@ -161,10 +161,7 @@ static void json_withdraw(struct command *cmd, if (withdraw->changesatoshi <= 546) withdraw->changesatoshi = 0; - withdraw->change_key_index = - db_get_intvar(ld->wallet->db, "bip32_max_index", 0) + 1; - db_set_intvar(ld->wallet->db, "bip32_max_index", - withdraw->change_key_index); + withdraw->change_key_index = wallet_get_newindex(ld); utxos = from_utxoptr_arr(withdraw, withdraw->utxos); u8 *msg = towire_hsmctl_sign_withdrawal(cmd, @@ -238,14 +235,15 @@ static void json_newaddr(struct command *cmd, struct ripemd160 p2sh; struct pubkey pubkey; u8 *redeemscript; - u64 bip32_max_index = db_get_intvar(ld->wallet->db, "bip32_max_index", 0); + s64 keyidx; - if (bip32_max_index == BIP32_INITIAL_HARDENED_CHILD) { + keyidx = wallet_get_newindex(ld); + if (keyidx < 0) { command_fail(cmd, "Keys exhausted "); return; } - if (bip32_key_from_parent(ld->bip32_base, bip32_max_index, + if (bip32_key_from_parent(ld->bip32_base, keyidx, BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) { command_fail(cmd, "Keys generation failure"); return; @@ -261,8 +259,6 @@ static void json_newaddr(struct command *cmd, sha256(&h, redeemscript, tal_count(redeemscript)); ripemd160(&p2sh, h.u.u8, sizeof(h)); - db_set_intvar(ld->wallet->db, "bip32_max_index", bip32_max_index + 1); - json_object_start(response, NULL); json_add_string(response, "address", p2sh_to_base58(cmd, cmd->dstate->testnet, &p2sh));