From 3820bc872660f6dfbf0fd287a625457e5e0b2360 Mon Sep 17 00:00:00 2001 From: "Brian R. Bondy" Date: Tue, 21 Dec 2021 15:42:01 -0500 Subject: [PATCH] Various reset wallet fixes --- app/brave_generated_resources.grd | 3 + browser/brave_wallet/BUILD.gn | 2 + browser/brave_wallet/brave_wallet_reset.cc | 36 +++++++++++ browser/brave_wallet/brave_wallet_reset.h | 21 +++++++ .../brave_wallet_service_unittest.cc | 36 +++++++++++ .../keyring_controller_unittest.cc | 15 +++-- .../brave_wallet_page/brave_wallet_page.js | 1 + .../brave_default_extensions_handler.cc | 7 +-- .../settings_localized_strings_provider.cc | 1 + .../browser/brave_wallet_prefs.cc | 20 ++++-- .../brave_wallet/browser/brave_wallet_prefs.h | 5 +- .../browser/brave_wallet_provider_impl.h | 1 + .../browser/brave_wallet_service.cc | 22 ++++++- .../browser/brave_wallet_service.h | 7 +++ .../browser/eth_json_rpc_controller.cc | 16 +++++ .../browser/eth_json_rpc_controller.h | 5 ++ .../eth_json_rpc_controller_unittest.cc | 61 ++++++++++++------- .../browser/eth_pending_tx_tracker.cc | 6 ++ .../browser/eth_pending_tx_tracker.h | 1 + .../brave_wallet/browser/eth_tx_controller.cc | 13 ++++ .../brave_wallet/browser/eth_tx_controller.h | 6 ++ .../browser/eth_tx_controller_unittest.cc | 26 ++++++++ .../browser/keyring_controller.cc | 6 +- .../brave_wallet/common/brave_wallet.mojom | 14 ++++- .../common/actions/wallet_actions.ts | 1 + .../brave_wallet_ui/common/async/handlers.ts | 4 ++ .../common/wallet_api_proxy.ts | 3 + 27 files changed, 301 insertions(+), 38 deletions(-) create mode 100644 browser/brave_wallet/brave_wallet_reset.cc create mode 100644 browser/brave_wallet/brave_wallet_reset.h diff --git a/app/brave_generated_resources.grd b/app/brave_generated_resources.grd index 63c212f64346..2f16a091945b 100644 --- a/app/brave_generated_resources.grd +++ b/app/brave_generated_resources.grd @@ -1000,6 +1000,9 @@ Are you sure you want to do this? Are you sure you want to reset your wallet? If your wallet is not backed up, resetting will cause you to lose all account data (including any associated funds). Type "$1Yes" to confirm. + + Your wallet was reset. + Yes diff --git a/browser/brave_wallet/BUILD.gn b/browser/brave_wallet/BUILD.gn index 810f96b98481..762484cd0694 100644 --- a/browser/brave_wallet/BUILD.gn +++ b/browser/brave_wallet/BUILD.gn @@ -8,6 +8,8 @@ source_set("brave_wallet") { "asset_ratio_controller_factory.h", "brave_wallet_context_utils.cc", "brave_wallet_context_utils.h", + "brave_wallet_reset.cc", + "brave_wallet_reset.h", "brave_wallet_service_factory.cc", "brave_wallet_service_factory.h", "erc_token_images_source.cc", diff --git a/browser/brave_wallet/brave_wallet_reset.cc b/browser/brave_wallet/brave_wallet_reset.cc new file mode 100644 index 000000000000..a97f0817f8d0 --- /dev/null +++ b/browser/brave_wallet/brave_wallet_reset.cc @@ -0,0 +1,36 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/brave_wallet/brave_wallet_reset.h" +#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" +#include "brave/browser/brave_wallet/eth_tx_controller_factory.h" +#include "brave/browser/brave_wallet/keyring_controller_factory.h" +#include "brave/browser/brave_wallet/rpc_controller_factory.h" +#include "brave/components/brave_wallet/browser/brave_wallet_service.h" +#include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" +#include "brave/components/brave_wallet/browser/eth_tx_controller.h" +#include "brave/components/brave_wallet/browser/keyring_controller.h" + +namespace brave_wallet { + +void ResetWallet(content::BrowserContext* context) { + auto* eth_tx_controller = + brave_wallet::EthTxControllerFactory::GetControllerForContext(context); + eth_tx_controller->Reset(); + + auto* rpc_controller = + brave_wallet::RpcControllerFactory::GetControllerForContext(context); + rpc_controller->Reset(); + + auto* brave_wallet_service = + brave_wallet::BraveWalletServiceFactory::GetServiceForContext(context); + brave_wallet_service->Reset(); + + auto* keyring_controller = + brave_wallet::KeyringControllerFactory::GetControllerForContext(context); + keyring_controller->Reset(); +} + +} // namespace brave_wallet diff --git a/browser/brave_wallet/brave_wallet_reset.h b/browser/brave_wallet/brave_wallet_reset.h new file mode 100644 index 000000000000..8634167aec33 --- /dev/null +++ b/browser/brave_wallet/brave_wallet_reset.h @@ -0,0 +1,21 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_RESET_H_ +#define BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_RESET_H_ + +#include "content/public/browser/browser_context.h" + +namespace content { +class BrowserContext; +} // namespace content + +namespace brave_wallet { + +void ResetWallet(content::BrowserContext* context); + +} // namespace brave_wallet + +#endif // BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_RESET_H_ diff --git a/browser/brave_wallet/brave_wallet_service_unittest.cc b/browser/brave_wallet/brave_wallet_service_unittest.cc index 15093b08638d..4cde0919b018 100644 --- a/browser/brave_wallet/brave_wallet_service_unittest.cc +++ b/browser/brave_wallet/brave_wallet_service_unittest.cc @@ -1525,4 +1525,40 @@ TEST_F(BraveWalletServiceUnitTest, GetUserAsset) { mojom::kRopstenChainId)); } +TEST_F(BraveWalletServiceUnitTest, Reset) { + SetDefaultBaseCurrency("CAD"); + SetDefaultBaseCryptocurrency("ETH"); + mojom::ERCTokenPtr token1 = GetToken1(); + bool callback_called; + bool success; + AddUserAsset(token1.Clone(), "0x1", &callback_called, &success); + EXPECT_TRUE(callback_called); + EXPECT_TRUE(success); + EXPECT_TRUE(GetPrefs()->HasPrefPath(kBraveWalletUserAssets)); + EXPECT_TRUE(GetPrefs()->HasPrefPath(kDefaultBaseCurrency)); + EXPECT_TRUE(GetPrefs()->HasPrefPath(kDefaultBaseCryptocurrency)); + std::string address = "0xbe862ad9abfe6f22bcb087716c7d89a26051f74c"; + std::string message = "0xAB"; + auto request1 = mojom::SignMessageRequest::New( + 1, address, std::string(message.begin(), message.end())); + service_->AddSignMessageRequest( + std::move(request1), + base::BindLambdaForTesting( + [](bool, const std::string&, const std::string&) {})); + mojom::ERCTokenPtr custom_token = + mojom::ERCToken::New("0x6b175474e89094C44Da98b954eEdeAC495271d1e", + "COLOR", "", true, false, "COLOR", 18, true, ""); + AddSuggestToken(custom_token.Clone(), custom_token.Clone(), true); + + service_->Reset(); + + EXPECT_FALSE(GetPrefs()->HasPrefPath(kBraveWalletUserAssets)); + EXPECT_FALSE(GetPrefs()->HasPrefPath(kDefaultBaseCurrency)); + EXPECT_FALSE(GetPrefs()->HasPrefPath(kDefaultBaseCryptocurrency)); + EXPECT_TRUE(service_->sign_message_requests_.empty()); + EXPECT_TRUE(service_->sign_message_callbacks_.empty()); + EXPECT_TRUE(service_->add_suggest_token_callbacks_.empty()); + EXPECT_TRUE(service_->add_suggest_token_requests_.empty()); +} + } // namespace brave_wallet diff --git a/browser/brave_wallet/keyring_controller_unittest.cc b/browser/brave_wallet/keyring_controller_unittest.cc index 9164561223e3..889231f4afd1 100644 --- a/browser/brave_wallet/keyring_controller_unittest.cc +++ b/browser/brave_wallet/keyring_controller_unittest.cc @@ -57,6 +57,7 @@ class TestKeyringControllerObserver // TODO(bbondy): We should be testing all of these observer events void KeyringCreated() override {} void KeyringRestored() override {} + void KeyringReset() override { keyringResetFired_ = true; } void Locked() override {} void Unlocked() override {} void BackedUp() override {} @@ -70,6 +71,7 @@ class TestKeyringControllerObserver bool AutoLockMinutesChangedFired() { return autoLockMinutesChangedFired_; } bool SelectedAccountChangedFired() { return selectedAccountChangedFired_; } bool AccountsChangedFired() { return accountsChangedFired_; } + bool KeyringResetFired() { return keyringResetFired_; } mojo::PendingRemote GetReceiver() { @@ -80,12 +82,14 @@ class TestKeyringControllerObserver autoLockMinutesChangedFired_ = false; selectedAccountChangedFired_ = false; accountsChangedFired_ = false; + keyringResetFired_ = false; } private: bool autoLockMinutesChangedFired_ = false; bool selectedAccountChangedFired_ = false; bool accountsChangedFired_ = false; + bool keyringResetFired_ = false; mojo::Receiver observer_receiver_{this}; }; @@ -814,6 +818,9 @@ TEST_F(KeyringControllerUnitTest, LockAndUnlock) { TEST_F(KeyringControllerUnitTest, Reset) { KeyringController controller(GetPrefs()); + TestKeyringControllerObserver observer; + controller.AddObserver(observer.GetReceiver()); + HDKeyring* keyring = controller.CreateDefaultKeyring("brave"); keyring->AddAccounts(); // Trigger account number saving @@ -826,17 +833,17 @@ TEST_F(KeyringControllerUnitTest, Reset) { GetPrefs()->Set(kBraveWalletCustomNetworks, base::ListValue()); GetPrefs()->SetString(kBraveWalletCurrentChainId, brave_wallet::mojom::kMainnetChainId); - EXPECT_TRUE(GetPrefs()->HasPrefPath(kBraveWalletCustomNetworks)); - EXPECT_TRUE(GetPrefs()->HasPrefPath(kBraveWalletCurrentChainId)); controller.Reset(); EXPECT_FALSE(HasPrefForKeyring(kPasswordEncryptorSalt, "default")); EXPECT_FALSE(HasPrefForKeyring(kPasswordEncryptorNonce, "default")); EXPECT_FALSE(HasPrefForKeyring(kEncryptedMnemonic, "default")); EXPECT_FALSE(GetPrefs()->HasPrefPath(kBraveWalletKeyrings)); - EXPECT_FALSE(GetPrefs()->HasPrefPath(kBraveWalletCustomNetworks)); - EXPECT_FALSE(GetPrefs()->HasPrefPath(kBraveWalletCurrentChainId)); EXPECT_EQ(controller.default_keyring_, nullptr); EXPECT_EQ(controller.encryptor_, nullptr); + EXPECT_FALSE(controller.IsDefaultKeyringCreated()); + // Keyring observer fire + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(observer.KeyringResetFired()); } TEST_F(KeyringControllerUnitTest, BackupComplete) { diff --git a/browser/resources/settings/brave_wallet_page/brave_wallet_page.js b/browser/resources/settings/brave_wallet_page/brave_wallet_page.js index 871bd4e32beb..c24775c6a474 100644 --- a/browser/resources/settings/brave_wallet_page/brave_wallet_page.js +++ b/browser/resources/settings/brave_wallet_page/brave_wallet_page.js @@ -154,6 +154,7 @@ class SettingsBraveWalletPage extends SettingsBraveWalletPageBase { if (window.prompt(message) !== this.i18n('walletResetConfirmationPhrase')) return this.browserProxy_.resetWallet() + window.alert(this.i18n('walletResetConfirmed')) } } diff --git a/browser/ui/webui/settings/brave_default_extensions_handler.cc b/browser/ui/webui/settings/brave_default_extensions_handler.cc index d4eddedee10b..43ab98294ae8 100644 --- a/browser/ui/webui/settings/brave_default_extensions_handler.cc +++ b/browser/ui/webui/settings/brave_default_extensions_handler.cc @@ -11,10 +11,9 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" -#include "brave/browser/brave_wallet/keyring_controller_factory.h" +#include "brave/browser/brave_wallet/brave_wallet_reset.h" #include "brave/browser/extensions/brave_component_loader.h" #include "brave/common/pref_names.h" -#include "brave/components/brave_wallet/browser/keyring_controller.h" #include "brave/components/brave_webtorrent/grit/brave_webtorrent_resources.h" #include "brave/components/decentralized_dns/buildflags/buildflags.h" #include "brave/components/ipfs/buildflags/buildflags.h" @@ -207,9 +206,7 @@ void BraveDefaultExtensionsHandler::GetRestartNeeded( void BraveDefaultExtensionsHandler::ResetWallet( base::Value::ConstListView args) { - auto* keyring_controller = - brave_wallet::KeyringControllerFactory::GetControllerForContext(profile_); - keyring_controller->Reset(); + brave_wallet::ResetWallet(profile_); } void BraveDefaultExtensionsHandler::SetWebTorrentEnabled( diff --git a/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 73031b70944d..a077632fd32c 100644 --- a/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc @@ -408,6 +408,7 @@ void BraveAddCommonStrings(content::WebUIDataSource* html_source, {"ipfsKeyExportError", IDS_SETTINGS_IPNS_KEYS_EXPORT_ERROR}, {"resetWallet", IDS_SETTINGS_WALLET_RESET}, {"walletResetConfirmation", IDS_SETTINGS_WALLET_RESET_CONFIRMATION}, + {"walletResetConfirmed", IDS_SETTINGS_WALLET_RESET_CONFIRMED}, {"walletNetworksLinkTitle", IDS_SETTINGS_WALLET_NETWORKS_ITEM}, {"walletAddNetworkDialogTitle", IDS_SETTINGS_WALLET_ADD_NETWORK_TITLE}, {"walletAddNetworkInvalidURLInput", diff --git a/components/brave_wallet/browser/brave_wallet_prefs.cc b/components/brave_wallet/browser/brave_wallet_prefs.cc index 6586382b265a..da888e2694b1 100644 --- a/components/brave_wallet/browser/brave_wallet_prefs.cc +++ b/components/brave_wallet/browser/brave_wallet_prefs.cc @@ -103,16 +103,28 @@ void RegisterProfilePrefsForMigration( static_cast(mojom::DefaultWallet::BraveWalletPreferExtension)); } -void ClearProfilePrefs(PrefService* prefs) { +void ClearEthJsonRpcControllerProfilePrefs(PrefService* prefs) { DCHECK(prefs); prefs->ClearPref(kBraveWalletCustomNetworks); prefs->ClearPref(kBraveWalletCurrentChainId); - prefs->ClearPref(kBraveWalletTransactions); - prefs->ClearPref(kBraveWalletUserAssets); + prefs->ClearPref(kSupportEip1559OnLocalhostChain); +} + +void ClearKeyringControllerProfilePrefs(PrefService* prefs) { + DCHECK(prefs); prefs->ClearPref(kBraveWalletKeyrings); prefs->ClearPref(kBraveWalletAutoLockMinutes); prefs->ClearPref(kBraveWalletSelectedAccount); - prefs->ClearPref(kSupportEip1559OnLocalhostChain); +} + +void ClearEthTxControllerProfilePrefs(PrefService* prefs) { + DCHECK(prefs); + prefs->ClearPref(kBraveWalletTransactions); +} + +void ClearBraveWalletServicePrefs(PrefService* prefs) { + DCHECK(prefs); + prefs->ClearPref(kBraveWalletUserAssets); prefs->ClearPref(kDefaultBaseCurrency); prefs->ClearPref(kDefaultBaseCryptocurrency); } diff --git a/components/brave_wallet/browser/brave_wallet_prefs.h b/components/brave_wallet/browser/brave_wallet_prefs.h index b01516b3c0f7..7a0797184d04 100644 --- a/components/brave_wallet/browser/brave_wallet_prefs.h +++ b/components/brave_wallet/browser/brave_wallet_prefs.h @@ -17,7 +17,10 @@ namespace brave_wallet { void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); void RegisterProfilePrefsForMigration( user_prefs::PrefRegistrySyncable* registry); -void ClearProfilePrefs(PrefService* prefs); +void ClearEthJsonRpcControllerProfilePrefs(PrefService* prefs); +void ClearKeyringControllerProfilePrefs(PrefService* prefs); +void ClearEthTxControllerProfilePrefs(PrefService* prefs); +void ClearBraveWalletServicePrefs(PrefService* prefs); void MigrateObsoleteProfilePrefs(PrefService* prefs); } // namespace brave_wallet diff --git a/components/brave_wallet/browser/brave_wallet_provider_impl.h b/components/brave_wallet/browser/brave_wallet_provider_impl.h index 683d9c81cad7..1d7f5818e657 100644 --- a/components/brave_wallet/browser/brave_wallet_provider_impl.h +++ b/components/brave_wallet/browser/brave_wallet_provider_impl.h @@ -202,6 +202,7 @@ class BraveWalletProviderImpl final // KeyringControllerObserver void KeyringCreated() override {} void KeyringRestored() override {} + void KeyringReset() override {} void Locked() override; void Unlocked() override; void BackedUp() override {} diff --git a/components/brave_wallet/browser/brave_wallet_service.cc b/components/brave_wallet/browser/brave_wallet_service.cc index aa6c4c5ab1f8..99bb67ef5a26 100644 --- a/components/brave_wallet/browser/brave_wallet_service.cc +++ b/components/brave_wallet/browser/brave_wallet_service.cc @@ -12,6 +12,7 @@ #include "base/strings/string_util.h" #include "base/values.h" #include "brave/components/brave_stats/browser/brave_stats_updater_util.h" +#include "brave/components/brave_wallet/browser/brave_wallet_prefs.h" #include "brave/components/brave_wallet/browser/brave_wallet_utils.h" #include "brave/components/brave_wallet/browser/erc_token_registry.h" #include "brave/components/brave_wallet/browser/keyring_controller.h" @@ -755,7 +756,7 @@ void BraveWalletService::NotifyAddSuggestTokenRequestsProcessed( } } -void BraveWalletService::OnNetworkChanged() { +void BraveWalletService::CancelAllSuggestedTokenCallbacks() { add_suggest_token_requests_.clear(); // Reject pending suggest token requests when network changed. for (auto& callback : add_suggest_token_callbacks_) @@ -765,4 +766,23 @@ void BraveWalletService::OnNetworkChanged() { add_suggest_token_callbacks_.clear(); } +void BraveWalletService::CancelAllSignMessageCallbacks() { + while (!sign_message_requests_.empty()) { + auto callback = std::move(sign_message_callbacks_.front()); + sign_message_requests_.pop_front(); + sign_message_callbacks_.pop_front(); + std::move(callback).Run(false, std::string(), std::string()); + } +} + +void BraveWalletService::OnNetworkChanged() { + CancelAllSuggestedTokenCallbacks(); +} + +void BraveWalletService::Reset() { + ClearBraveWalletServicePrefs(prefs_); + CancelAllSuggestedTokenCallbacks(); + CancelAllSignMessageCallbacks(); +} + } // namespace brave_wallet diff --git a/components/brave_wallet/browser/brave_wallet_service.h b/components/brave_wallet/browser/brave_wallet_service.h index 38385f606094..5a65376d9f2f 100644 --- a/components/brave_wallet/browser/brave_wallet_service.h +++ b/components/brave_wallet/browser/brave_wallet_service.h @@ -119,6 +119,10 @@ class BraveWalletService : public KeyedService, // BraveWalletServiceDelegate::Observer: void OnActiveOriginChanged(const std::string& origin) override; + // Resets things back to the original state of BraveWalletService. + // To be used when the Wallet is reset / erased + void Reset() override; + void RecordWalletUsage(base::Time wallet_last_used); void AddSignMessageRequest(mojom::SignMessageRequestPtr request, @@ -134,6 +138,7 @@ class BraveWalletService : public KeyedService, FRIEND_TEST_ALL_PREFIXES(BraveWalletServiceUnitTest, AddSuggestToken); FRIEND_TEST_ALL_PREFIXES(BraveWalletServiceUnitTest, GetUserAsset); FRIEND_TEST_ALL_PREFIXES(BraveWalletServiceUnitTest, ImportFromMetaMask); + FRIEND_TEST_ALL_PREFIXES(BraveWalletServiceUnitTest, Reset); void OnDefaultWalletChanged(); void OnDefaultBaseCurrencyChanged(); @@ -164,6 +169,8 @@ class BraveWalletService : public KeyedService, bool is_erc721, const std::string& chain_id); void OnNetworkChanged(); + void CancelAllSuggestedTokenCallbacks(); + void CancelAllSignMessageCallbacks(); base::circular_deque sign_message_requests_; base::circular_deque sign_message_callbacks_; diff --git a/components/brave_wallet/browser/eth_json_rpc_controller.cc b/components/brave_wallet/browser/eth_json_rpc_controller.cc index cd4c8af70900..11950f65d9bb 100644 --- a/components/brave_wallet/browser/eth_json_rpc_controller.cc +++ b/components/brave_wallet/browser/eth_json_rpc_controller.cc @@ -11,6 +11,7 @@ #include "base/environment.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" +#include "brave/components/brave_wallet/browser/brave_wallet_prefs.h" #include "brave/components/brave_wallet/browser/brave_wallet_utils.h" #include "brave/components/brave_wallet/browser/eth_data_builder.h" #include "brave/components/brave_wallet/browser/eth_requests.h" @@ -1066,4 +1067,19 @@ bool EthJsonRpcController::AddSwitchEthereumChainRequest( return true; } +void EthJsonRpcController::Reset() { + ClearEthJsonRpcControllerProfilePrefs(prefs_); + SetNetwork(prefs_->GetString(kBraveWalletCurrentChainId)); + + add_chain_pending_requests_.clear(); + switch_chain_requests_.clear(); + // Reject pending suggest token requests when network changed. + for (auto& callback : switch_chain_callbacks_) { + std::move(callback.second) + .Run(mojom::ProviderError::kUserRejectedRequest, + l10n_util::GetStringUTF8(IDS_WALLET_USER_REJECTED_REQUEST)); + } + switch_chain_callbacks_.clear(); +} + } // namespace brave_wallet diff --git a/components/brave_wallet/browser/eth_json_rpc_controller.h b/components/brave_wallet/browser/eth_json_rpc_controller.h index c8eef6980c9e..564cb7b03556 100644 --- a/components/brave_wallet/browser/eth_json_rpc_controller.h +++ b/components/brave_wallet/browser/eth_json_rpc_controller.h @@ -173,6 +173,10 @@ class EthJsonRpcController : public KeyedService, const std::string& account_address, GetERC721TokenBalanceCallback callback) override; + // Resets things back to the original state of BraveWalletService. + // To be used when the Wallet is reset / erased + void Reset() override; + using GetSupportsInterfaceCallback = base::OnceCallback; void GetSupportsInterface(const std::string& contract_address, @@ -303,6 +307,7 @@ class EthJsonRpcController : public KeyedService, RequestCallback callback); FRIEND_TEST_ALL_PREFIXES(EthJsonRpcControllerUnitTest, IsValidDomain); + FRIEND_TEST_ALL_PREFIXES(EthJsonRpcControllerUnitTest, Reset); bool IsValidDomain(const std::string& domain); void OnGetERC721OwnerOf( diff --git a/components/brave_wallet/browser/eth_json_rpc_controller_unittest.cc b/components/brave_wallet/browser/eth_json_rpc_controller_unittest.cc index 3c3b41af451d..62716a7d9fc6 100644 --- a/components/brave_wallet/browser/eth_json_rpc_controller_unittest.cc +++ b/components/brave_wallet/browser/eth_json_rpc_controller_unittest.cc @@ -509,27 +509,6 @@ TEST_F(EthJsonRpcControllerUnitTest, EnsGetEthAddr) { EXPECT_TRUE(callback_called); } -TEST_F(EthJsonRpcControllerUnitTest, ResetCustomChains) { - std::vector values; - brave_wallet::mojom::EthereumChain chain( - "0x1", "chain_name", {"https://url1.com"}, {"https://url1.com"}, - {"https://url1.com"}, "symbol_name", "symbol", 11, false); - auto chain_ptr = chain.Clone(); - values.push_back(brave_wallet::EthereumChainToValue(chain_ptr)); - UpdateCustomNetworks(prefs(), &values); - - std::vector custom_chains; - GetAllCustomChains(prefs(), &custom_chains); - ASSERT_FALSE(custom_chains.empty()); - custom_chains.clear(); - ASSERT_TRUE(custom_chains.empty()); - - KeyringController controller(prefs()); - controller.Reset(); - GetAllCustomChains(prefs(), &custom_chains); - ASSERT_TRUE(custom_chains.empty()); -} - TEST_F(EthJsonRpcControllerUnitTest, AddEthereumChainApproved) { brave_wallet::mojom::EthereumChain chain( "0x111", "chain_name", {"https://url1.com"}, {"https://url1.com"}, @@ -1233,4 +1212,44 @@ TEST_F(EthJsonRpcControllerUnitTest, GetSupportsInterface) { EXPECT_TRUE(callback_called); } +TEST_F(EthJsonRpcControllerUnitTest, Reset) { + std::vector values; + brave_wallet::mojom::EthereumChain chain( + "0x1", "chain_name", {"https://url1.com"}, {"https://url1.com"}, + {"https://url1.com"}, "symbol_name", "symbol", 11, false); + auto chain_ptr = chain.Clone(); + values.push_back(brave_wallet::EthereumChainToValue(chain_ptr)); + UpdateCustomNetworks(prefs(), &values); + + std::vector custom_chains; + GetAllCustomChains(prefs(), &custom_chains); + ASSERT_FALSE(custom_chains.empty()); + custom_chains.clear(); + ASSERT_TRUE(custom_chains.empty()); + SetNetwork(mojom::kLocalhostChainId); + prefs()->SetBoolean(kSupportEip1559OnLocalhostChain, true); + EXPECT_TRUE(prefs()->HasPrefPath(kBraveWalletCustomNetworks)); + EXPECT_EQ(prefs()->GetString(kBraveWalletCurrentChainId), + mojom::kLocalhostChainId); + // This isn't valid data for these maps but we are just checking to make sure + // it gets cleared + rpc_controller_->add_chain_pending_requests_["1"] = + EthJsonRpcController::EthereumChainRequest(); + rpc_controller_->switch_chain_requests_[GURL()] = ""; + rpc_controller_->switch_chain_callbacks_[GURL()] = base::BindLambdaForTesting( + [&](mojom::ProviderError error, const std::string& error_message) {}); + + rpc_controller_->Reset(); + + GetAllCustomChains(prefs(), &custom_chains); + ASSERT_TRUE(custom_chains.empty()); + EXPECT_FALSE(prefs()->HasPrefPath(kBraveWalletCustomNetworks)); + EXPECT_EQ(prefs()->GetString(kBraveWalletCurrentChainId), + mojom::kMainnetChainId); + EXPECT_FALSE(prefs()->HasPrefPath(kSupportEip1559OnLocalhostChain)); + EXPECT_TRUE(rpc_controller_->add_chain_pending_requests_.empty()); + EXPECT_TRUE(rpc_controller_->switch_chain_requests_.empty()); + EXPECT_TRUE(rpc_controller_->switch_chain_callbacks_.empty()); +} + } // namespace brave_wallet diff --git a/components/brave_wallet/browser/eth_pending_tx_tracker.cc b/components/brave_wallet/browser/eth_pending_tx_tracker.cc index 81fdb60d06ba..5965d275288f 100644 --- a/components/brave_wallet/browser/eth_pending_tx_tracker.cc +++ b/components/brave_wallet/browser/eth_pending_tx_tracker.cc @@ -65,6 +65,11 @@ void EthPendingTxTracker::ResubmitPendingTransactions() { } } +void EthPendingTxTracker::Reset() { + network_nonce_map_.clear(); + dropped_blocks_counter_.clear(); +} + void EthPendingTxTracker::OnGetTxReceipt(std::string id, bool status, TransactionReceipt receipt) { @@ -97,6 +102,7 @@ void EthPendingTxTracker::OnGetNetworkNonce(std::string address, uint256_t result) { if (!status) return; + network_nonce_map_[address] = result; } diff --git a/components/brave_wallet/browser/eth_pending_tx_tracker.h b/components/brave_wallet/browser/eth_pending_tx_tracker.h index f5f3ff69295f..5ee7871126e2 100644 --- a/components/brave_wallet/browser/eth_pending_tx_tracker.h +++ b/components/brave_wallet/browser/eth_pending_tx_tracker.h @@ -30,6 +30,7 @@ class EthPendingTxTracker { bool UpdatePendingTransactions(size_t* num_pending); void ResubmitPendingTransactions(); + void Reset(); private: FRIEND_TEST_ALL_PREFIXES(EthPendingTxTrackerUnitTest, IsNonceTaken); diff --git a/components/brave_wallet/browser/eth_tx_controller.cc b/components/brave_wallet/browser/eth_tx_controller.cc index a67a514e90db..6c663d6d165c 100644 --- a/components/brave_wallet/browser/eth_tx_controller.cc +++ b/components/brave_wallet/browser/eth_tx_controller.cc @@ -17,6 +17,7 @@ #include "base/strings/string_util.h" #include "brave/components/brave_wallet/browser/asset_ratio_controller.h" #include "brave/components/brave_wallet/browser/brave_wallet_constants.h" +#include "brave/components/brave_wallet/browser/brave_wallet_prefs.h" #include "brave/components/brave_wallet/browser/eip1559_transaction.h" #include "brave/components/brave_wallet/browser/eth_data_builder.h" #include "brave/components/brave_wallet/browser/eth_data_parser.h" @@ -115,6 +116,7 @@ EthTxController::EthTxController( : rpc_controller_(rpc_controller), keyring_controller_(keyring_controller), asset_ratio_controller_(asset_ratio_controller), + prefs_(prefs), tx_state_manager_(std::move(tx_state_manager)), nonce_tracker_(std::move(nonce_tracker)), pending_tx_tracker_(std::move(pending_tx_tracker)), @@ -855,6 +857,10 @@ void EthTxController::KeyringRestored() { UpdatePendingTransactions(); } +void EthTxController::KeyringReset() { + UpdatePendingTransactions(); +} + void EthTxController::SpeedupOrCancelTransaction( const std::string& tx_meta_id, bool cancel, @@ -1012,4 +1018,11 @@ void EthTxController::RetryTransaction(const std::string& tx_meta_id, Uint256ValueToHex(meta->tx->gas_limit())); } +void EthTxController::Reset() { + ClearEthTxControllerProfilePrefs(prefs_); + eth_block_tracker_->Stop(); + pending_tx_tracker_->Reset(); + known_no_pending_tx = false; +} + } // namespace brave_wallet diff --git a/components/brave_wallet/browser/eth_tx_controller.h b/components/brave_wallet/browser/eth_tx_controller.h index cdb2573da670..3846a573d0d5 100644 --- a/components/brave_wallet/browser/eth_tx_controller.h +++ b/components/brave_wallet/browser/eth_tx_controller.h @@ -118,6 +118,9 @@ class EthTxController : public KeyedService, GetTransactionMessageToSignCallback callback) override; void AddObserver( ::mojo::PendingRemote observer) override; + // Resets things back to the original state of EthTxController + // To be used when the Wallet is reset / erased + void Reset() override; static bool ValidateTxData(const mojom::TxDataPtr& tx_data, std::string* error); @@ -129,6 +132,7 @@ class EthTxController : public KeyedService, private: FRIEND_TEST_ALL_PREFIXES(EthTxControllerUnitTest, TestSubmittedToConfirmed); FRIEND_TEST_ALL_PREFIXES(EthTxControllerUnitTest, RetryTransaction); + FRIEND_TEST_ALL_PREFIXES(EthTxControllerUnitTest, Reset); friend class EthTxControllerUnitTest; void NotifyUnapprovedTxUpdated(EthTxStateManager::TxMeta* meta); @@ -201,6 +205,7 @@ class EthTxController : public KeyedService, // KeyringControllerObserver: void KeyringCreated() override; void KeyringRestored() override; + void KeyringReset() override; void Locked() override; void Unlocked() override; void BackedUp() override {} @@ -219,6 +224,7 @@ class EthTxController : public KeyedService, EthJsonRpcController* rpc_controller_; // NOT OWNED KeyringController* keyring_controller_; // NOT OWNED AssetRatioController* asset_ratio_controller_; // NOT OWNED + PrefService* prefs_; // NOT OWNED std::unique_ptr tx_state_manager_; std::unique_ptr nonce_tracker_; std::unique_ptr pending_tx_tracker_; diff --git a/components/brave_wallet/browser/eth_tx_controller_unittest.cc b/components/brave_wallet/browser/eth_tx_controller_unittest.cc index 60a561e66c4b..026390017da0 100644 --- a/components/brave_wallet/browser/eth_tx_controller_unittest.cc +++ b/components/brave_wallet/browser/eth_tx_controller_unittest.cc @@ -25,6 +25,7 @@ #include "brave/components/brave_wallet/browser/eth_tx_state_manager.h" #include "brave/components/brave_wallet/browser/hd_keyring.h" #include "brave/components/brave_wallet/browser/keyring_controller.h" +#include "brave/components/brave_wallet/browser/pref_names.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" #include "brave/components/brave_wallet/common/hex_utils.h" #include "components/prefs/testing_pref_service.h" @@ -257,6 +258,8 @@ class EthTxControllerUnitTest : public testing::Test { EthTxController* eth_tx_controller() { return eth_tx_controller_.get(); } + PrefService* GetPrefs() { return &prefs_; } + void SetInterceptor(const std::string& content) { url_loader_factory_.SetInterceptor(base::BindLambdaForTesting( [&, content](const network::ResourceRequest& request) { @@ -1793,4 +1796,27 @@ TEST_F(EthTxControllerUnitTest, MakeERC721TransferFromDataTxType) { run_loop->Run(); } +TEST_F(EthTxControllerUnitTest, Reset) { + eth_tx_controller()->known_no_pending_tx = true; + eth_tx_controller()->eth_block_tracker_->Start(base::Seconds(10)); + EXPECT_TRUE(eth_tx_controller()->eth_block_tracker_->IsRunning()); + EthTxStateManager::TxMeta meta; + meta.id = "001"; + meta.from = EthAddress::FromHex("0xbe862ad9abfe6f22bcb087716c7d89a26051f74a"); + meta.status = mojom::TransactionStatus::Unapproved; + auto tx_data = mojom::TxData::New( + "0x1", "0x1", "0x0974", "0xbe862ad9abfe6f22bcb087716c7d89a26051f74c", + "0x016345785d8a0000", std::vector()); + auto tx = EthTransaction::FromTxData(tx_data, false); + meta.tx = std::make_unique(*tx); + eth_tx_controller()->tx_state_manager_->AddOrUpdateTx(meta); + EXPECT_TRUE(GetPrefs()->HasPrefPath(kBraveWalletTransactions)); + + eth_tx_controller()->Reset(); + + EXPECT_FALSE(eth_tx_controller()->known_no_pending_tx); + EXPECT_FALSE(eth_tx_controller()->eth_block_tracker_->IsRunning()); + EXPECT_FALSE(GetPrefs()->HasPrefPath(kBraveWalletTransactions)); +} + } // namespace brave_wallet diff --git a/components/brave_wallet/browser/keyring_controller.cc b/components/brave_wallet/browser/keyring_controller.cc index 4343ebee829d..a46ac801ced2 100644 --- a/components/brave_wallet/browser/keyring_controller.cc +++ b/components/brave_wallet/browser/keyring_controller.cc @@ -1053,7 +1053,11 @@ void KeyringController::Reset() { encryptor_.reset(); default_keyring_.reset(); - ClearProfilePrefs(prefs_); + ClearKeyringControllerProfilePrefs(prefs_); + + for (const auto& observer : observers_) { + observer->KeyringReset(); + } } void KeyringController::StopAutoLockTimer() { diff --git a/components/brave_wallet/common/brave_wallet.mojom b/components/brave_wallet/common/brave_wallet.mojom index 2d781bc798bc..a4388a908bbf 100644 --- a/components/brave_wallet/common/brave_wallet.mojom +++ b/components/brave_wallet/common/brave_wallet.mojom @@ -277,6 +277,9 @@ interface KeyringControllerObserver { // Fired when a keyring is restored KeyringRestored(); + // Fired when a keyring is reset + KeyringReset(); + // Fired when a keyring is locked Locked(); @@ -369,7 +372,7 @@ interface KeyringController { // Obtains the keyring information GetDefaultKeyringInfo() => (KeyringInfo keyring); - // Resets the keyring and all preferences + // Resets the keyring and the related preferences Reset(); // Adds a KeyringControllerObserver @@ -577,6 +580,9 @@ interface EthJsonRpcController { // Balance is 0x1 if current selected account is the same as token owner's // address, otherwise balance is 0x0. GetERC721TokenBalance(string contract_address, string token_id, string account_address) => (bool success, string balance); + + // Resets the keyring and the related preferences + Reset(); }; enum TransactionStatus { @@ -663,6 +669,9 @@ interface EthTxController { GetNonceForHardwareTransaction(string tx_meta_id) => (string? nonce); GetTransactionMessageToSign(string tx_meta_id) => (string? message); ProcessHardwareSignature(string tx_meta_id, string v, string r, string s) => (bool status); + + // Resets the keyring and the related preferences + Reset(); }; interface BraveWalletServiceObserver { @@ -775,6 +784,9 @@ interface BraveWalletService { // Obtain the pending add suggest token requests for current chain, will be // cleared when user switch networks. GetPendingAddSuggestTokenRequests() => (array requests); + + // Resets the keyring and the related preferences + Reset(); }; enum DefaultWallet { diff --git a/components/brave_wallet_ui/common/actions/wallet_actions.ts b/components/brave_wallet_ui/common/actions/wallet_actions.ts index 1ffea3bd251f..74fb26501842 100644 --- a/components/brave_wallet_ui/common/actions/wallet_actions.ts +++ b/components/brave_wallet_ui/common/actions/wallet_actions.ts @@ -63,6 +63,7 @@ export const chainChangedEvent = createAction('cha export const isEip1559Changed = createAction('isEip1559Changed') export const keyringCreated = createAction('keyringCreated') export const keyringRestored = createAction('keyringRestored') +export const keyringReset = createAction('keyringReset') export const locked = createAction('locked') export const unlocked = createAction('unlocked') export const backedUp = createAction('backedUp') diff --git a/components/brave_wallet_ui/common/async/handlers.ts b/components/brave_wallet_ui/common/async/handlers.ts index 29fb115c7fa3..ba13e363a939 100644 --- a/components/brave_wallet_ui/common/async/handlers.ts +++ b/components/brave_wallet_ui/common/async/handlers.ts @@ -124,6 +124,10 @@ handler.on(WalletActions.keyringRestored.getType(), async (store) => { await refreshWalletInfo(store) }) +handler.on(WalletActions.keyringReset.getType(), async (store) => { + window.location.reload() +}) + handler.on(WalletActions.locked.getType(), async (store) => { interactionNotifier.stopWatchingForInteraction() await refreshWalletInfo(store) diff --git a/components/brave_wallet_ui/common/wallet_api_proxy.ts b/components/brave_wallet_ui/common/wallet_api_proxy.ts index 8fa9499ed1bc..69aba02dcb49 100644 --- a/components/brave_wallet_ui/common/wallet_api_proxy.ts +++ b/components/brave_wallet_ui/common/wallet_api_proxy.ts @@ -42,6 +42,9 @@ export default class WalletApiProxy { keyringRestored: function () { store.dispatch(WalletActions.keyringRestored()) }, + keyringReset: function () { + store.dispatch(WalletActions.keyringReset()) + }, locked: function () { store.dispatch(WalletActions.locked()) },