diff --git a/api/backend.go b/api/backend.go index b3d88dfb32f..020b0dd4962 100644 --- a/api/backend.go +++ b/api/backend.go @@ -3,6 +3,7 @@ package api import ( signercore "github.com/ethereum/go-ethereum/signer/core/apitypes" + "github.com/status-im/status-go/account" "github.com/status-im/status-go/eth-node/types" "github.com/status-im/status-go/multiaccounts" "github.com/status-im/status-go/multiaccounts/accounts" @@ -15,22 +16,20 @@ import ( // StatusBackend defines the contract for the Status.im service type StatusBackend interface { - // IsNodeRunning() bool // NOTE: Only used in tests StartNode(config *params.NodeConfig) error // NOTE: Only used in canary StartNodeWithKey(acc multiaccounts.Account, password string, keyHex string, conf *params.NodeConfig) error StartNodeWithAccount(acc multiaccounts.Account, password string, conf *params.NodeConfig) error StartNodeWithAccountAndInitialConfig(account multiaccounts.Account, password string, settings settings.Settings, conf *params.NodeConfig, subaccs []*accounts.Account) error StopNode() error - // RestartNode() error // NOTE: Only used in tests GetNodeConfig() (*params.NodeConfig, error) UpdateRootDataDir(datadir string) - // SelectAccount(loginParams account.LoginParams) error + SelectAccount(loginParams account.LoginParams) error OpenAccounts() error GetAccounts() ([]multiaccounts.Account, error) LocalPairingStarted() error - // SaveAccount(account multiaccounts.Account) error + SaveAccount(account multiaccounts.Account) error SaveAccountAndStartNodeWithKey(acc multiaccounts.Account, password string, settings settings.Settings, conf *params.NodeConfig, subaccs []*accounts.Account, keyHex string) error Recover(rpcParams personal.RecoverParams) (types.Address, error) Logout() error diff --git a/api/backend_test.go b/api/backend_test.go index adb0f758451..b3315eb2deb 100644 --- a/api/backend_test.go +++ b/api/backend_test.go @@ -7,7 +7,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" "math/rand" "os" "path" @@ -72,7 +71,7 @@ func setupTestWalletDB() (*sql.DB, func() error, error) { } func setupTestMultiDB() (*multiaccounts.Database, func() error, error) { - tmpfile, err := ioutil.TempFile("", "tests") + tmpfile, err := os.CreateTemp("", "tests") if err != nil { return nil, nil, err } @@ -112,6 +111,12 @@ func setupGethStatusBackend() (*GethStatusBackend, func() error, func() error, f return backend, stop1, stop2, stop3, err } +func handleError(t *testing.T, err error) { + if err != nil { + t.Logf("deferred function error: '%s'", err) + } +} + func TestBackendStartNodeConcurrently(t *testing.T) { utils.Init() @@ -617,7 +622,7 @@ func TestBackendGetVerifiedAccount(t *testing.T) { Name: "private key keypair", Type: accounts.KeypairTypeKey, Accounts: []*accounts.Account{ - &accounts.Account{ + { Address: address, KeyUID: keyUID, }, @@ -647,7 +652,7 @@ func TestBackendGetVerifiedAccount(t *testing.T) { Name: "profile keypair", Type: accounts.KeypairTypeProfile, Accounts: []*accounts.Account{ - &accounts.Account{ + { Address: types.HexToAddress(derivedInfo.Address), KeyUID: walletInfo.KeyUID, Type: accounts.AccountTypeGenerated, @@ -675,7 +680,7 @@ func TestBackendGetVerifiedAccount(t *testing.T) { db, err := accounts.NewDB(backend.appDB) require.NoError(t, err) - defer db.Close() + defer handleError(t, db.Close()) _, err = backend.AccountManager().ImportAccount(pkey, password) require.NoError(t, err) require.NoError(t, db.SaveOrUpdateKeypair(&accounts.Keypair{ @@ -683,7 +688,7 @@ func TestBackendGetVerifiedAccount(t *testing.T) { Name: "private key keypair", Type: accounts.KeypairTypeKey, Accounts: []*accounts.Account{ - &accounts.Account{ + { Address: address, KeyUID: keyUID, }, @@ -711,7 +716,7 @@ func TestRuntimeLogLevelIsNotWrittenToDatabase(t *testing.T) { tmpdir := t.TempDir() - json := `{ + config := `{ "NetworkId": 3, "DataDir": "` + tmpdir + `", "KeyStoreDir": "` + tmpdir + `", @@ -727,7 +732,7 @@ func TestRuntimeLogLevelIsNotWrittenToDatabase(t *testing.T) { "LogLevel": "DEBUG" }` - conf, err := params.NewConfigFromJSON(json) + conf, err := params.NewConfigFromJSON(config) require.NoError(t, err) require.Equal(t, "INFO", conf.RuntimeLogLevel) keyhex := hex.EncodeToString(gethcrypto.FromECDSA(chatKey)) @@ -739,12 +744,12 @@ func TestRuntimeLogLevelIsNotWrittenToDatabase(t *testing.T) { address := crypto.PubkeyToAddress(walletKey.PublicKey) - settings := testSettings - settings.KeyUID = keyUID - settings.Address = crypto.PubkeyToAddress(walletKey.PublicKey) + s := testSettings + s.KeyUID = keyUID + s.Address = crypto.PubkeyToAddress(walletKey.PublicKey) chatPubKey := crypto.FromECDSAPub(&chatKey.PublicKey) - require.NoError(t, b.SaveAccountAndStartNodeWithKey(main, "test-pass", settings, conf, + require.NoError(t, b.SaveAccountAndStartNodeWithKey(main, "test-pass", s, conf, []*accounts.Account{ {Address: address, KeyUID: keyUID, Wallet: true}, {Address: crypto.PubkeyToAddress(chatKey.PublicKey), KeyUID: keyUID, Chat: true, PublicKey: chatPubKey}}, keyhex)) @@ -788,12 +793,12 @@ func TestLoginWithKey(t *testing.T) { address := crypto.PubkeyToAddress(walletKey.PublicKey) - settings := testSettings - settings.KeyUID = keyUID - settings.Address = crypto.PubkeyToAddress(walletKey.PublicKey) + s := testSettings + s.KeyUID = keyUID + s.Address = crypto.PubkeyToAddress(walletKey.PublicKey) chatPubKey := crypto.FromECDSAPub(&chatKey.PublicKey) - require.NoError(t, b.SaveAccountAndStartNodeWithKey(main, "test-pass", settings, conf, + require.NoError(t, b.SaveAccountAndStartNodeWithKey(main, "test-pass", s, conf, []*accounts.Account{ {Address: address, KeyUID: keyUID, Wallet: true}, {Address: crypto.PubkeyToAddress(chatKey.PublicKey), KeyUID: keyUID, Chat: true, PublicKey: chatPubKey}}, keyhex)) @@ -858,12 +863,12 @@ func TestLoginAccount(t *testing.T) { require.NoError(t, b.Logout()) require.NoError(t, b.StopNode()) - accounts, err := b.GetAccounts() + accs, err := b.GetAccounts() require.NoError(t, err) - require.Len(t, accounts, 1) + require.Len(t, accs, 1) loginAccountRequest := &requests.Login{ - KeyUID: accounts[0].KeyUID, + KeyUID: accs[0].KeyUID, Password: password, WakuV2Nameserver: nameserver, } @@ -898,13 +903,13 @@ func TestVerifyDatabasePassword(t *testing.T) { address := crypto.PubkeyToAddress(walletKey.PublicKey) - settings := testSettings - settings.KeyUID = keyUID - settings.Address = crypto.PubkeyToAddress(walletKey.PublicKey) + s := testSettings + s.KeyUID = keyUID + s.Address = crypto.PubkeyToAddress(walletKey.PublicKey) chatPubKey := crypto.FromECDSAPub(&chatKey.PublicKey) - require.NoError(t, b.SaveAccountAndStartNodeWithKey(main, "test-pass", settings, conf, []*accounts.Account{ + require.NoError(t, b.SaveAccountAndStartNodeWithKey(main, "test-pass", s, conf, []*accounts.Account{ {Address: address, KeyUID: keyUID, Wallet: true}, {Address: crypto.PubkeyToAddress(chatKey.PublicKey), KeyUID: keyUID, Chat: true, PublicKey: chatPubKey}}, keyhex)) require.NoError(t, b.Logout()) @@ -977,14 +982,14 @@ func TestDeleteMultiaccount(t *testing.T) { err = backend.SaveAccount(account) require.NoError(t, err) - files, err := ioutil.ReadDir(rootDataDir) + files, err := os.ReadDir(rootDataDir) require.NoError(t, err) require.NotEqual(t, 3, len(files)) err = backend.DeleteMultiaccount(account.KeyUID, keyStoreDir) require.NoError(t, err) - files, err = ioutil.ReadDir(rootDataDir) + files, err = os.ReadDir(rootDataDir) require.NoError(t, err) require.Equal(t, 3, len(files)) } @@ -1136,13 +1141,13 @@ func TestConvertAccount(t *testing.T) { err = backend.StartNodeWithAccountAndInitialConfig(account, password, *defaultSettings, nodeConfig, profileKeypair.Accounts) require.NoError(t, err) - multiaccounts, err := backend.GetAccounts() + multiaccs, err := backend.GetAccounts() require.NoError(t, err) - require.NotEmpty(t, multiaccounts[0].ColorHash) + require.NotEmpty(t, multiaccs[0].ColorHash) serverMessenger := backend.Messenger() require.NotNil(t, serverMessenger) - files, err := ioutil.ReadDir(rootDataDir) + files, err := os.ReadDir(rootDataDir) require.NoError(t, err) require.NotEqual(t, 3, len(files)) @@ -1239,19 +1244,19 @@ func TestConvertAccount(t *testing.T) { } func copyFile(srcFolder string, dstFolder string, fileName string, t *testing.T) { - data, err := ioutil.ReadFile(path.Join(srcFolder, fileName)) + data, err := os.ReadFile(path.Join(srcFolder, fileName)) if err != nil { t.Fail() } - err = ioutil.WriteFile(path.Join(dstFolder, fileName), data, 0600) + err = os.WriteFile(path.Join(dstFolder, fileName), data, 0600) if err != nil { t.Fail() } } func copyDir(srcFolder string, dstFolder string, t *testing.T) { - files, err := ioutil.ReadDir(srcFolder) + files, err := os.ReadDir(srcFolder) require.NoError(t, err) for _, file := range files { if !file.IsDir() { @@ -1282,18 +1287,18 @@ func login(t *testing.T, conf *params.NodeConfig) { require.NoError(t, b.OpenAccounts()) - accounts, err := b.GetAccounts() + accs, err := b.GetAccounts() require.NoError(t, err) - require.Len(t, accounts, 1) - require.Equal(t, username, accounts[0].Name) - require.Equal(t, keyUID, accounts[0].KeyUID) + require.Len(t, accs, 1) + require.Equal(t, username, accs[0].Name) + require.Equal(t, keyUID, accs[0].KeyUID) wg := sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() - err := b.StartNodeWithAccount(accounts[0], passwd, conf) + err := b.StartNodeWithAccount(accs[0], passwd, conf) require.NoError(t, err) }() @@ -1360,13 +1365,13 @@ func TestChangeDatabasePassword(t *testing.T) { require.NoError(t, err) appDb, err := sqlite.OpenDB(appDbPath, newPassword, account.KDFIterations) require.NoError(t, err) - appDb.Close() + defer handleError(t, appDb.Close()) walletDbPath, err := backend.getWalletDBPath(account.KeyUID) require.NoError(t, err) walletDb, err := sqlite.OpenDB(walletDbPath, newPassword, account.KDFIterations) require.NoError(t, err) - walletDb.Close() + defer handleError(t, walletDb.Close()) // Test that keystore can be decrypted with the new password acc, key, err := backend.accountManager.AddressToDecryptedAccount(accountInfo.WalletAddress, newPassword) diff --git a/api/geth_backend.go b/api/geth_backend.go index 9945159868a..19d411365f8 100644 --- a/api/geth_backend.go +++ b/api/geth_backend.go @@ -54,10 +54,6 @@ import ( ) var ( - // ErrWhisperClearIdentitiesFailure clearing whisper identities has failed. - ErrWhisperClearIdentitiesFailure = errors.New("failed to clear whisper identities") - // ErrWhisperIdentityInjectionFailure injecting whisper identities has failed. - ErrWhisperIdentityInjectionFailure = errors.New("failed to inject identity into Whisper") // ErrWakuIdentityInjectionFailure injecting whisper identities has failed. ErrWakuIdentityInjectionFailure = errors.New("failed to inject identity into waku") // ErrUnsupportedRPCMethod is for methods not supported by the RPC interface @@ -67,8 +63,6 @@ var ( ErrRPCClientUnavailable = errors.New("JSON-RPC client is unavailable") // ErrDBNotAvailable is returned if a method is called before the DB is available for usage ErrDBNotAvailable = errors.New("DB is unavailable") - // ErrConfigNotAvailable is returned if a method is called before the nodeconfig is set - ErrConfigNotAvailable = errors.New("NodeConfig is not available") ) var _ StatusBackend = (*GethStatusBackend)(nil) @@ -806,12 +800,12 @@ func (b *GethStatusBackend) GetSettings() (*settings.Settings, error) { return nil, err } - settings, err := accountsDB.GetSettings() + s, err := accountsDB.GetSettings() if err != nil { return nil, err } - return &settings, nil + return &s, nil } func (b *GethStatusBackend) GetEnsUsernames() ([]*ens.UsernameDetail, error) { @@ -830,17 +824,17 @@ func (b *GethStatusBackend) MigrateKeyStoreDir(acc multiaccounts.Account, passwo if err != nil { return err } - accounts, err := accountDB.GetActiveAccounts() + accs, err := accountDB.GetActiveAccounts() if err != nil { return err } - settings, err := accountDB.GetSettings() + s, err := accountDB.GetSettings() if err != nil { return err } - addresses := []string{settings.EIP1581Address.Hex(), settings.WalletRootAddress.Hex()} - for _, account := range accounts { - addresses = append(addresses, account.Address.Hex()) + addresses := []string{s.EIP1581Address.Hex(), s.WalletRootAddress.Hex()} + for _, acc := range accs { + addresses = append(addresses, acc.Address.Hex()) } err = b.accountManager.MigrateKeyStoreDir(oldDir, newDir, addresses) if err != nil { @@ -872,11 +866,11 @@ func (b *GethStatusBackend) LoggedIn(keyUID string, err error) error { signal.SendLoggedIn(nil, nil, nil, err) return err } - settings, err := b.GetSettings() + s, err := b.GetSettings() if err != nil { return err } - account, err := b.getAccountByKeyUID(keyUID) + acc, err := b.getAccountByKeyUID(keyUID) if err != nil { return err } @@ -892,7 +886,7 @@ func (b *GethStatusBackend) LoggedIn(keyUID string, err error) error { return err } } - signal.SendLoggedIn(account, settings, ensUsernamesJSON, nil) + signal.SendLoggedIn(acc, s, ensUsernamesJSON, nil) return nil } @@ -958,7 +952,7 @@ func (b *GethStatusBackend) reEncryptKeyStoreDir(currentPassword string, newPass } func (b *GethStatusBackend) ChangeDatabasePassword(keyUID string, password string, newPassword string) error { - account, err := b.multiaccountsDB.GetAccount(keyUID) + acc, err := b.multiaccountsDB.GetAccount(keyUID) if err != nil { return err } @@ -983,9 +977,9 @@ func (b *GethStatusBackend) ChangeDatabasePassword(keyUID string, password strin // because UI calls Logout and Quit afterwards. It should not be UI-dependent // and should be handled gracefully here if it makes sense to run dummy node after // logout - _ = b.startNodeWithAccount(*account, password, nil) + _ = b.startNodeWithAccount(*acc, password, nil) } else { - _ = b.startNodeWithAccount(*account, newPassword, nil) + _ = b.startNodeWithAccount(*acc, newPassword, nil) } } } @@ -1001,16 +995,16 @@ func (b *GethStatusBackend) ChangeDatabasePassword(keyUID string, password strin // First change app DB password, because it also reencrypts the keystore, // otherwise if we call changeWalletDbPassword first and logout, we will fail // to reencrypt the keystore - err = b.changeAppDBPassword(account, logout, password, newPassword) + err = b.changeAppDBPassword(acc, logout, password, newPassword) if err != nil { return err } // Already logged out but pass a param to decouple the logic for testing - err = b.changeWalletDBPassword(account, noLogout, password, newPassword) + err = b.changeWalletDBPassword(acc, noLogout, password, newPassword) if err != nil { // Revert the password to original - err2 := b.changeAppDBPassword(account, noLogout, newPassword, password) + err2 := b.changeAppDBPassword(acc, noLogout, newPassword, password) if err2 != nil { log.Error("failed to revert app db password", "err", err2) } @@ -1197,7 +1191,7 @@ func (b *GethStatusBackend) ConvertToKeycardAccount(account multiaccounts.Accoun return err } - // This check is added due to mobile app cause it doesn't support a Keycard features as desktop app. + // This check is added due to mobile app because it doesn't support a Keycard features as desktop app. // We should remove the following line once mobile and desktop app align. if len(keycardUID) > 0 { displayName, err := accountDB.DisplayName() @@ -1348,7 +1342,7 @@ func (b *GethStatusBackend) generateOrImportAccount(mnemonic string, customizati return nil, err } - account := multiaccounts.Account{ + acc := multiaccounts.Account{ KeyUID: info.KeyUID, Name: request.DisplayName, CustomizationColor: multiacccommon.CustomizationColor(request.CustomizationColor), @@ -1360,29 +1354,29 @@ func (b *GethStatusBackend) generateOrImportAccount(mnemonic string, customizati if err != nil { return nil, err } - account.Images = iis + acc.Images = iis } - settings, err := defaultSettings(info, derivedAddresses, nil) + s, err := defaultSettings(info, derivedAddresses, nil) if err != nil { return nil, err } - settings.DeviceName = request.DeviceName - settings.DisplayName = request.DisplayName - settings.PreviewPrivacy = request.PreviewPrivacy - settings.CurrentNetwork = request.CurrentNetwork + s.DeviceName = request.DeviceName + s.DisplayName = request.DisplayName + s.PreviewPrivacy = request.PreviewPrivacy + s.CurrentNetwork = request.CurrentNetwork // If restoring an account, we don't set the mnemonic if mnemonic == "" { - settings.Mnemonic = &info.Mnemonic - settings.OmitTransfersHistoryScan = true + s.Mnemonic = &info.Mnemonic + s.OmitTransfersHistoryScan = true // TODO(rasom): uncomment it as soon as address will be properly // marked as shown on mobile client - //settings.MnemonicWasNotShown = true + //s.MnemonicWasNotShown = true } - nodeConfig, err := defaultNodeConfig(settings.InstallationID, request, opts...) + nodeConfig, err := defaultNodeConfig(s.InstallationID, request, opts...) if err != nil { return nil, err } @@ -1421,13 +1415,13 @@ func (b *GethStatusBackend) generateOrImportAccount(mnemonic string, customizati } subAccounts := []*accounts.Account{walletAccount, chatAccount} - err = b.StartNodeWithAccountAndInitialConfig(account, request.Password, *settings, nodeConfig, subAccounts) + err = b.StartNodeWithAccountAndInitialConfig(acc, request.Password, *s, nodeConfig, subAccounts) if err != nil { b.log.Error("start node", err) return nil, err } - return &account, nil + return &acc, nil } func (b *GethStatusBackend) CreateAccountAndLogin(request *requests.CreateAccount, opts ...params.Option) (*multiaccounts.Account, error) { @@ -1536,7 +1530,7 @@ func (b *GethStatusBackend) VerifyDatabasePassword(keyUID string, password strin } if !b.appDBExists(keyUID) || !b.walletDBExists(keyUID) { - return errors.New("One or more databases not created") + return errors.New("one or more databases not created") } err = b.ensureDBsOpened(multiaccounts.Account{KeyUID: keyUID, KDFIterations: kdfIterations}, password) @@ -1678,7 +1672,7 @@ func (b *GethStatusBackend) saveAccountsAndSettings(settings settings.Settings, LastUsedDerivationIndex: 0, } - // When creating a new account, the chat account should have position -1, cause it doesn't participate + // When creating a new account, the chat account should have position -1, because it doesn't participate // in the wallet view and default wallet account should be at position 0. for _, acc := range subaccs { if acc.Chat { @@ -1719,7 +1713,7 @@ func (b *GethStatusBackend) loadNodeConfig(inputNodeCfg *params.NodeConfig) erro conf.WakuConfig.Enabled = !conf.WakuV2Config.Enabled // NodeConfig.Version should be taken from params.Version // which is set at the compile time. - // What's cached is usually outdated so we overwrite it here. + // What's cached is usually outdated, so we overwrite it here. conf.Version = params.Version conf.RootDataDir = b.rootDataDir conf.DataDir = filepath.Join(b.rootDataDir, conf.DataDir) @@ -1948,26 +1942,26 @@ func (b *GethStatusBackend) Recover(rpcParams personal.RecoverParams) (types.Add // SignTypedData accepts data and password. Gets verified account and signs typed data. func (b *GethStatusBackend) SignTypedData(typed typeddata.TypedData, address string, password string) (types.HexBytes, error) { - account, err := b.getVerifiedWalletAccount(address, password) + acc, err := b.getVerifiedWalletAccount(address, password) if err != nil { return types.HexBytes{}, err } chain := new(big.Int).SetUint64(b.StatusNode().Config().NetworkID) - sig, err := typeddata.Sign(typed, account.AccountKey.PrivateKey, chain) + sig, err := typeddata.Sign(typed, acc.AccountKey.PrivateKey, chain) if err != nil { return types.HexBytes{}, err } - return types.HexBytes(sig), err + return sig, err } // SignTypedDataV4 accepts data and password. Gets verified account and signs typed data. func (b *GethStatusBackend) SignTypedDataV4(typed signercore.TypedData, address string, password string) (types.HexBytes, error) { - account, err := b.getVerifiedWalletAccount(address, password) + acc, err := b.getVerifiedWalletAccount(address, password) if err != nil { return types.HexBytes{}, err } chain := new(big.Int).SetUint64(b.StatusNode().Config().NetworkID) - sig, err := typeddata.SignTypedDataV4(typed, account.AccountKey.PrivateKey, chain) + sig, err := typeddata.SignTypedDataV4(typed, acc.AccountKey.PrivateKey, chain) if err != nil { return types.HexBytes{}, err } @@ -2092,7 +2086,7 @@ func (b *GethStatusBackend) registerHandlers() error { return nil } -func unsupportedMethodHandler(ctx context.Context, chainID uint64, rpcParams ...interface{}) (interface{}, error) { +func unsupportedMethodHandler(_ context.Context, _ uint64, _ ...interface{}) (interface{}, error) { return nil, ErrUnsupportedRPCMethod } @@ -2213,7 +2207,7 @@ func (b *GethStatusBackend) Logout() error { return nil } -// cleanupServices stops parts of services that doesn't managed by a node and removes injected data from services. +// cleanupServices stops parts of services that aren't managed by a node and removes injected data from services. func (b *GethStatusBackend) cleanupServices() error { b.selectedAccountKeyID = "" if b.statusNode == nil { @@ -2381,9 +2375,9 @@ func (b *GethStatusBackend) SignGroupMembership(content string) (string, error) } func (b *GethStatusBackend) Messenger() *protocol.Messenger { - node := b.StatusNode() - if node != nil { - accountService := node.AccountService() + statusNode := b.StatusNode() + if statusNode != nil { + accountService := statusNode.AccountService() if accountService != nil { return accountService.GetMessenger() }