From e8e6ef352b80c3a98572e48147384fe76f813b52 Mon Sep 17 00:00:00 2001 From: Sale Djenic Date: Wed, 2 Oct 2024 15:49:45 +0200 Subject: [PATCH] fix_: suggested path calculation updated when adding previously deleted key pair When adding an account via seed phrase, for a key pair that was previously deleted, suggested path should start from index 0. It was not like that before, this commit fixes that. --- multiaccounts/accounts/database.go | 17 ++++++++++++++++- multiaccounts/accounts/database_test.go | 12 ++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/multiaccounts/accounts/database.go b/multiaccounts/accounts/database.go index 9ef5e3955..1d98fcf15 100644 --- a/multiaccounts/accounts/database.go +++ b/multiaccounts/accounts/database.go @@ -1162,6 +1162,12 @@ func (db *Database) SaveOrUpdateKeypair(keypair *Keypair) error { return ErrKeypairDifferentAccountsKeyUID } } + } else if dbKeypair.Removed { + // If the key pair beind added was removed in the past, then all its accounts must be removed before adding it again. + err = db.deleteAccountsForKeyUID(tx, keypair.KeyUID) + if err != nil { + return err + } } _, err = tx.Exec(` @@ -1599,6 +1605,15 @@ func (db *Database) MoveWalletAccount(fromPosition int64, toPosition int64, cloc return db.setClockOfLastAccountsPositionChange(tx, clock) } +func (db *Database) deleteAccountsForKeyUID(tx *sql.Tx, keyUID string) error { + if tx == nil { + return errDbTransactionIsNil + } + + _, err := tx.Exec("DELETE FROM keypairs_accounts WHERE key_uid = ?", keyUID) + return err +} + func (db *Database) CheckAndDeleteExpiredKeypairsAndAccounts(time uint64) error { tx, err := db.db.Begin() if err != nil { @@ -1728,7 +1743,7 @@ func (db *Database) ResolveSuggestedPathForKeypair(keyUID string) (suggestedPath }() var kp *Keypair - kp, err = db.getKeypairByKeyUID(tx, keyUID, true) + kp, err = db.getKeypairByKeyUID(tx, keyUID, false) if err != nil { if err == ErrDbKeypairNotFound { return fmt.Sprintf("%s0", statusWalletRootPath), nil diff --git a/multiaccounts/accounts/database_test.go b/multiaccounts/accounts/database_test.go index 92c588318..0c7f93587 100644 --- a/multiaccounts/accounts/database_test.go +++ b/multiaccounts/accounts/database_test.go @@ -662,4 +662,16 @@ func TestResolvingSuggestedDerivationPath(t *testing.T) { suggestedPath, err = db.ResolveSuggestedPathForKeypair(kp.KeyUID) require.NoError(t, err) require.Equal(t, fmt.Sprintf("%s%d", statusWalletRootPath, expectedLastUsedDerivationIndex+1), suggestedPath) + + // remove kaypair + err = db.RemoveKeypair(kp.KeyUID, 0) + require.NoError(t, err) + _, err = db.GetKeypairByKeyUID(kp.KeyUID) + require.Error(t, err) + require.True(t, err == ErrDbKeypairNotFound) + + // check suggested path after removing keypair when adding the same keypair again + suggestedPath, err = db.ResolveSuggestedPathForKeypair(kp.KeyUID) + require.NoError(t, err) + require.Equal(t, fmt.Sprintf("%s%d", statusWalletRootPath, 0), suggestedPath) }