From 411a98b267d51527c37deeeee604923220789e87 Mon Sep 17 00:00:00 2001 From: oisupov Date: Fri, 20 Jan 2023 03:53:40 +0400 Subject: [PATCH] Review fix --- .../crypto_wallet/util/AsyncUtils.java | 2 +- browser/brave_wallet/BUILD.gn | 2 +- .../brave_wallet_auto_pin_service_factory.cc | 5 +- .../brave_wallet_auto_pin_service_factory.h | 2 +- .../brave_wallet_pin_service_factory.cc | 9 +- .../brave_wallet_pin_service_factory.h | 2 +- .../ipfs/ipfs_local_pin_service_factory.cc | 5 +- browser/ipfs/ipfs_local_pin_service_factory.h | 2 +- components/brave_wallet/browser/BUILD.gn | 2 +- .../browser/brave_wallet_auto_pin_service.cc | 50 +++-- .../browser/brave_wallet_auto_pin_service.h | 37 ++-- .../brave_wallet_auto_pin_service_unittest.cc | 51 +++-- .../brave_wallet/browser/brave_wallet_p3a.cc | 2 +- .../browser/brave_wallet_pin_service.cc | 196 +++++++++++------- .../browser/brave_wallet_pin_service.h | 52 ++--- .../brave_wallet_pin_service_unittest.cc | 111 +++++----- .../browser/brave_wallet_prefs.cc | 4 +- .../browser/brave_wallet_service.cc | 2 +- .../browser/brave_wallet_utils.cc | 8 +- .../brave_wallet/browser/brave_wallet_utils.h | 2 +- components/brave_wallet/browser/pref_names.cc | 2 +- components/brave_wallet/browser/pref_names.h | 2 +- .../brave_wallet/common/brave_wallet.mojom | 24 ++- components/ipfs/BUILD.gn | 2 +- components/ipfs/ipfs_json_parser.cc | 7 +- components/ipfs/ipfs_json_parser_unittest.cc | 14 ++ components/ipfs/pin/ipfs_base_pin_service.cc | 11 +- components/ipfs/pin/ipfs_base_pin_service.h | 8 +- .../pin/ipfs_base_pin_service_unittest.cc | 6 +- components/ipfs/pin/ipfs_local_pin_service.cc | 51 ++--- components/ipfs/pin/ipfs_local_pin_service.h | 44 +++- .../pin/ipfs_local_pin_service_unittest.cc | 2 +- components/ipfs/pin/ipfs_pin_rpc_types.cc | 2 +- components/ipfs/pin/ipfs_pin_rpc_types.h | 2 +- 34 files changed, 420 insertions(+), 303 deletions(-) diff --git a/android/java/org/chromium/chrome/browser/crypto_wallet/util/AsyncUtils.java b/android/java/org/chromium/chrome/browser/crypto_wallet/util/AsyncUtils.java index 90f4d198cfa3..1e50cd7c4059 100644 --- a/android/java/org/chromium/chrome/browser/crypto_wallet/util/AsyncUtils.java +++ b/android/java/org/chromium/chrome/browser/crypto_wallet/util/AsyncUtils.java @@ -423,7 +423,7 @@ public GetNftErc721MetadataContext(Runnable responseCompleteCallback) { } @Override - public void call(String erc721Metadata, Integer errorCode, String errorMessage) { + public void call(String tokenUrl, String erc721Metadata, Integer errorCode, String errorMessage) { this.tokenMetadata = erc721Metadata; this.errorCode = errorCode; this.errorMessage = errorMessage; diff --git a/browser/brave_wallet/BUILD.gn b/browser/brave_wallet/BUILD.gn index 55b6c6a23415..b3315b061960 100644 --- a/browser/brave_wallet/BUILD.gn +++ b/browser/brave_wallet/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 The Brave Authors. All rights reserved. +# Copyright (c) 2019 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 https://mozilla.org/MPL/2.0/. diff --git a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc b/browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc index b59db19648d5..e9954c3aba51 100644 --- a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc +++ b/browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -9,10 +9,9 @@ #include #include "brave/browser/brave_wallet/brave_wallet_context_utils.h" - #include "brave/browser/brave_wallet/brave_wallet_pin_service_factory.h" #include "brave/browser/brave_wallet/brave_wallet_service_factory.h" -// TODO(cypt4) : Refactor brave/browser into separate component (#27486) +// TODO(cypt4) : Refactor brave/browser/ipfs into separate component (#27486) #include "brave/browser/ipfs/ipfs_service_factory.h" // nogncheck #include "brave/components/brave_wallet/browser/brave_wallet_pin_service.h" diff --git a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h b/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h index f35a8d3c4aea..c2778d2771c8 100644 --- a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h +++ b/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. diff --git a/browser/brave_wallet/brave_wallet_pin_service_factory.cc b/browser/brave_wallet/brave_wallet_pin_service_factory.cc index 6e6343d96bb5..f49edf983367 100644 --- a/browser/brave_wallet/brave_wallet_pin_service_factory.cc +++ b/browser/brave_wallet/brave_wallet_pin_service_factory.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -34,7 +34,12 @@ BraveWalletPinServiceFactory::GetForContext(content::BrowserContext* context) { return mojo::PendingRemote(); } - return GetServiceForContext(context)->MakeRemote(); + auto* service = GetServiceForContext(context); + if (!service) { + return mojo::PendingRemote(); + } + + return service->MakeRemote(); } // static diff --git a/browser/brave_wallet/brave_wallet_pin_service_factory.h b/browser/brave_wallet/brave_wallet_pin_service_factory.h index 2b1b0c4cd565..35759571f282 100644 --- a/browser/brave_wallet/brave_wallet_pin_service_factory.h +++ b/browser/brave_wallet/brave_wallet_pin_service_factory.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. diff --git a/browser/ipfs/ipfs_local_pin_service_factory.cc b/browser/ipfs/ipfs_local_pin_service_factory.cc index 92af1458cf6c..aea731930338 100644 --- a/browser/ipfs/ipfs_local_pin_service_factory.cc +++ b/browser/ipfs/ipfs_local_pin_service_factory.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -25,6 +25,9 @@ IpfsLocalPinServiceFactory* IpfsLocalPinServiceFactory::GetInstance() { // static IpfsLocalPinService* IpfsLocalPinServiceFactory::GetServiceForContext( content::BrowserContext* context) { + if (!ipfs::IpfsServiceFactory::IsIpfsEnabled(context)) { + return nullptr; + } return static_cast( GetInstance()->GetServiceForBrowserContext(context, true)); } diff --git a/browser/ipfs/ipfs_local_pin_service_factory.h b/browser/ipfs/ipfs_local_pin_service_factory.h index 30ec5b3cb414..1ddcad2840c9 100644 --- a/browser/ipfs/ipfs_local_pin_service_factory.h +++ b/browser/ipfs/ipfs_local_pin_service_factory.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. diff --git a/components/brave_wallet/browser/BUILD.gn b/components/brave_wallet/browser/BUILD.gn index 86c7e5788fb2..75dee59a939a 100644 --- a/components/brave_wallet/browser/BUILD.gn +++ b/components/brave_wallet/browser/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 The Brave Authors. All rights reserved. +# Copyright (c) 2019 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 https://mozilla.org/MPL/2.0/. diff --git a/components/brave_wallet/browser/brave_wallet_auto_pin_service.cc b/components/brave_wallet/browser/brave_wallet_auto_pin_service.cc index dd7b0d8670d9..1217a041d13c 100644 --- a/components/brave_wallet/browser/brave_wallet_auto_pin_service.cc +++ b/components/brave_wallet/browser/brave_wallet_auto_pin_service.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -9,12 +9,13 @@ namespace brave_wallet { -IntentData::IntentData(const BlockchainTokenPtr& token, - Operation operation, - absl::optional service) +BraveWalletAutoPinService::IntentData::IntentData( + const BlockchainTokenPtr& token, + Operation operation, + absl::optional service) : token(token.Clone()), operation(operation), service(std::move(service)) {} -IntentData::~IntentData() {} +BraveWalletAutoPinService::IntentData::~IntentData() = default; BraveWalletAutoPinService::BraveWalletAutoPinService( PrefService* prefs, @@ -23,6 +24,7 @@ BraveWalletAutoPinService::BraveWalletAutoPinService( : pref_service_(prefs), brave_wallet_service_(brave_wallet_service), brave_wallet_pin_service_(brave_wallet_pin_service) { + DCHECK(brave_wallet_service); Restore(); brave_wallet_service->AddTokenObserver( token_observer_.BindNewPipeAndPassRemote()); @@ -43,41 +45,44 @@ BraveWalletAutoPinService::MakeRemote() { } void BraveWalletAutoPinService::OnTokenAdded(BlockchainTokenPtr token) { - if (!token->is_nft) { + if (!BraveWalletPinService::IsTokenSupportedForPinning(token)) { return; } if (!IsAutoPinEnabled()) { return; } - PostPinToken(std::move(token), base::OnceCallback()); + PostPinToken(std::move(token)); } void BraveWalletAutoPinService::OnTokenRemoved(BlockchainTokenPtr token) { - if (!token->is_nft) { + if (!BraveWalletPinService::IsTokenSupportedForPinning(token)) { return; } base::EraseIf(queue_, [&token](const std::unique_ptr& intent) { return intent->token == token; }); - PostUnpinToken(std::move(token), base::OnceCallback()); + PostUnpinToken(std::move(token)); } void BraveWalletAutoPinService::Restore() { - brave_wallet_service_->GetAllUserAssets(base::BindOnce( - &BraveWalletAutoPinService::OnTokenListResolved, base::Unretained(this))); + brave_wallet_service_->GetAllUserAssets( + base::BindOnce(&BraveWalletAutoPinService::OnTokenListResolved, + weak_ptr_factory_.GetWeakPtr())); } void BraveWalletAutoPinService::OnTokenListResolved( std::vector token_list) { bool autopin_enabled = IsAutoPinEnabled(); + // Resolves list of user tokens. + // Check whether they are pinned or not and posts corresponding tasks. std::set known_tokens = brave_wallet_pin_service_->GetTokens(absl::nullopt); for (const auto& token : token_list) { - if (!token->is_nft) { + if (!BraveWalletPinService::IsTokenSupportedForPinning(token)) { continue; } auto current_token_path = - BraveWalletPinService::GetPath(absl::nullopt, token); + BraveWalletPinService::GetTokenPrefPath(absl::nullopt, token); if (!current_token_path) { continue; } @@ -113,6 +118,8 @@ void BraveWalletAutoPinService::OnTokenListResolved( AddOrExecute(std::make_unique(token, Operation::kDelete, absl::nullopt)); } else if (status->code == mojom::TokenPinStatusCode::STATUS_PINNED) { + // Pinned tokens should be verified for entirety time to time. + // We should check that related CIDs are still pinned. auto t1 = status->validate_time; if ((base::Time::Now() - t1) > base::Days(1) || t1 > base::Time::Now()) { AddOrExecute(std::make_unique(token, Operation::kValidate, @@ -121,8 +128,11 @@ void BraveWalletAutoPinService::OnTokenListResolved( } } + // Tokens that were previously pinned but not listed in the wallet should be + // unpinned. for (const auto& t : known_tokens) { - mojom::BlockchainTokenPtr token = BraveWalletPinService::TokenFromPath(t); + mojom::BlockchainTokenPtr token = + BraveWalletPinService::TokenFromPrefPath(t); if (token) { AddOrExecute(std::make_unique(token, Operation::kDelete, absl::nullopt)); @@ -132,15 +142,13 @@ void BraveWalletAutoPinService::OnTokenListResolved( CheckQueue(); } -void BraveWalletAutoPinService::PostPinToken(BlockchainTokenPtr token, - PostPinTokenCallback callback) { +void BraveWalletAutoPinService::PostPinToken(BlockchainTokenPtr token) { queue_.push_back( std::make_unique(token, Operation::kAdd, absl::nullopt)); CheckQueue(); } -void BraveWalletAutoPinService::PostUnpinToken(BlockchainTokenPtr token, - PostPinTokenCallback callback) { +void BraveWalletAutoPinService::PostUnpinToken(BlockchainTokenPtr token) { queue_.push_back( std::make_unique(token, Operation::kDelete, absl::nullopt)); CheckQueue(); @@ -151,7 +159,7 @@ void BraveWalletAutoPinService::ValidateToken( brave_wallet_pin_service_->Validate( data->token->Clone(), data->service, base::BindOnce(&BraveWalletAutoPinService::OnValidateTaskFinished, - base::Unretained(this))); + weak_ptr_factory_.GetWeakPtr())); } void BraveWalletAutoPinService::PinToken( @@ -159,7 +167,7 @@ void BraveWalletAutoPinService::PinToken( brave_wallet_pin_service_->AddPin( data->token->Clone(), data->service, base::BindOnce(&BraveWalletAutoPinService::OnTaskFinished, - base::Unretained(this))); + weak_ptr_factory_.GetWeakPtr())); } void BraveWalletAutoPinService::UnpinToken( @@ -167,7 +175,7 @@ void BraveWalletAutoPinService::UnpinToken( brave_wallet_pin_service_->RemovePin( data->token->Clone(), data->service, base::BindOnce(&BraveWalletAutoPinService::OnTaskFinished, - base::Unretained(this))); + weak_ptr_factory_.GetWeakPtr())); } void BraveWalletAutoPinService::AddOrExecute(std::unique_ptr data) { diff --git a/components/brave_wallet/browser/brave_wallet_auto_pin_service.h b/components/brave_wallet/browser/brave_wallet_auto_pin_service.h index 9397d93930a2..e34ab3b94dbf 100644 --- a/components/brave_wallet/browser/brave_wallet_auto_pin_service.h +++ b/components/brave_wallet/browser/brave_wallet_auto_pin_service.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -30,19 +30,6 @@ using brave_wallet::mojom::BlockchainTokenPtr; namespace brave_wallet { -enum Operation { kAdd = 0, kDelete = 1, kValidate = 2 }; - -struct IntentData { - BlockchainTokenPtr token; - Operation operation; - absl::optional service; - size_t attempt = 0; - IntentData(const BlockchainTokenPtr& token, - Operation operation, - absl::optional service); - ~IntentData(); -}; - class BraveWalletAutoPinService : public KeyedService, public brave_wallet::mojom::WalletAutoPinService, @@ -59,16 +46,28 @@ class BraveWalletAutoPinService void SetAutoPinEnabled(bool enabled) override; void IsAutoPinEnabled(IsAutoPinEnabledCallback callback) override; - void PostPinToken(BlockchainTokenPtr token, - PostPinTokenCallback callback) override; - void PostUnpinToken(BlockchainTokenPtr token, - PostUnpinTokenCallback callback) override; - // BraveWalletServiceTokenObserver void OnTokenAdded(mojom::BlockchainTokenPtr token) override; void OnTokenRemoved(mojom::BlockchainTokenPtr token) override; private: + enum Operation { kAdd = 0, kDelete = 1, kValidate = 2 }; + + struct IntentData { + BlockchainTokenPtr token; + Operation operation; + absl::optional service; + size_t attempt = 0; + IntentData(const BlockchainTokenPtr& token, + Operation operation, + absl::optional service); + ~IntentData(); + }; + + void PostPinToken(BlockchainTokenPtr token); + void PostUnpinToken(BlockchainTokenPtr token); + + // Iterates through user tokens and manages their pin statuses. void Restore(); void OnTokenListResolved(std::vector); diff --git a/components/brave_wallet/browser/brave_wallet_auto_pin_service_unittest.cc b/components/brave_wallet/browser/brave_wallet_auto_pin_service_unittest.cc index b8262a88f61d..77e49b90039a 100644 --- a/components/brave_wallet/browser/brave_wallet_auto_pin_service_unittest.cc +++ b/components/brave_wallet/browser/brave_wallet_auto_pin_service_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -31,6 +31,13 @@ namespace brave_wallet { namespace { +mojom::BlockchainTokenPtr GetErc721Token(const std::string& pref_path) { + mojom::BlockchainTokenPtr token = + BraveWalletPinService::TokenFromPrefPath(pref_path); + token->is_erc721 = true; + return token; +} + class MockBraveWalletPinService : public BraveWalletPinService { public: MockBraveWalletPinService() : BraveWalletPinService() {} @@ -69,7 +76,10 @@ class MockBraveWalletService : public BraveWalletService { }; MATCHER_P(TokenPathMatches, path, "") { - return arg == BraveWalletPinService::TokenFromPath(path); + auto token = GetErc721Token(path); + return token->coin == arg->coin && token->chain_id == arg->chain_id && + token->contract_address == arg->contract_address && + token->token_id == arg->token_id; } } // namespace @@ -125,20 +135,23 @@ TEST_F(BraveWalletAutoPinServiceTest, Autopin_WhenTokenAdded) { EXPECT_CALL(*GetBraveWalletPinService(), AddPin(_, _, _)).Times(3); { - mojom::BlockchainTokenPtr token = BraveWalletPinService::TokenFromPath( + mojom::BlockchainTokenPtr token = GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1"); + token->is_erc721 = true; service()->OnTokenAdded(std::move(token)); } { - mojom::BlockchainTokenPtr token = BraveWalletPinService::TokenFromPath( + mojom::BlockchainTokenPtr token = GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2"); + token->is_erc721 = true; service()->OnTokenAdded(std::move(token)); } { - mojom::BlockchainTokenPtr token = BraveWalletPinService::TokenFromPath( + mojom::BlockchainTokenPtr token = GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x3"); + token->is_erc721 = true; service()->OnTokenAdded(std::move(token)); } } @@ -180,9 +193,9 @@ TEST_F(BraveWalletAutoPinServiceTest, UnpinUnknownTokens_WhenRestore) { .WillByDefault(::testing::Invoke([](BraveWalletService:: GetUserAssetsCallback callback) { std::vector result; - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2")); std::move(callback).Run(std::move(result)); })); @@ -236,13 +249,13 @@ TEST_F(BraveWalletAutoPinServiceTest, ValidateOldTokens_WhenRestore) { .WillByDefault(::testing::Invoke([](BraveWalletService:: GetUserAssetsCallback callback) { std::vector result; - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x3")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x4")); std::move(callback).Run(std::move(result)); })); @@ -317,11 +330,11 @@ TEST_F(BraveWalletAutoPinServiceTest, PinContinue_WhenRestore) { .WillByDefault(::testing::Invoke([](BraveWalletService:: GetUserAssetsCallback callback) { std::vector result; - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x3")); std::move(callback).Run(std::move(result)); })); @@ -391,9 +404,9 @@ TEST_F(BraveWalletAutoPinServiceTest, UnpinContinue_WhenRestore) { .WillByDefault(::testing::Invoke([](BraveWalletService:: GetUserAssetsCallback callback) { std::vector result; - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2")); std::move(callback).Run(std::move(result)); })); @@ -442,7 +455,7 @@ TEST_F(BraveWalletAutoPinServiceTest, DoNotAutoPin_WhenAutoPinDisabled) { EXPECT_CALL(*GetBraveWalletPinService(), AddPin(_, _, _)).Times(0); { - mojom::BlockchainTokenPtr token = BraveWalletPinService::TokenFromPath( + mojom::BlockchainTokenPtr token = GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1"); service()->OnTokenAdded(std::move(token)); } @@ -476,9 +489,9 @@ TEST_F(BraveWalletAutoPinServiceTest, PinOldTokens_WhenAutoPinEnabled) { .WillByDefault(::testing::Invoke([](BraveWalletService:: GetUserAssetsCallback callback) { std::vector result; - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1")); - result.push_back(BraveWalletPinService::TokenFromPath( + result.push_back(GetErc721Token( "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2")); std::move(callback).Run(std::move(result)); })); diff --git a/components/brave_wallet/browser/brave_wallet_p3a.cc b/components/brave_wallet/browser/brave_wallet_p3a.cc index f1679c4dbe9c..b87690364ced 100644 --- a/components/brave_wallet/browser/brave_wallet_p3a.cc +++ b/components/brave_wallet/browser/brave_wallet_p3a.cc @@ -108,7 +108,7 @@ BraveWalletP3A::BraveWalletP3A(BraveWalletService* wallet_service, base::Unretained(this), true)); } -BraveWalletP3A::BraveWalletP3A() {} +BraveWalletP3A::BraveWalletP3A() = default; BraveWalletP3A::~BraveWalletP3A() = default; diff --git a/components/brave_wallet/browser/brave_wallet_pin_service.cc b/components/brave_wallet/browser/brave_wallet_pin_service.cc index 8f19e89d1f59..a767587ccca1 100644 --- a/components/brave_wallet/browser/brave_wallet_pin_service.cc +++ b/components/brave_wallet/browser/brave_wallet_pin_service.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -21,9 +21,6 @@ #include "brave/components/ipfs/ipfs_utils.h" #include "components/prefs/scoped_user_pref_update.h" -using brave_wallet::mojom::BlockchainToken; -using brave_wallet::mojom::BlockchainTokenPtr; - namespace brave_wallet { const char kAssetStatus[] = "status"; @@ -104,7 +101,9 @@ absl::optional ExtractCID(const std::string& ipfs_url) { } // namespace -std::string StatusToString(const mojom::TokenPinStatusCode& status) { +// static +std::string BraveWalletPinService::StatusToString( + const mojom::TokenPinStatusCode& status) { switch (status) { case mojom::TokenPinStatusCode::STATUS_NOT_PINNED: return "not_pinned"; @@ -127,7 +126,8 @@ std::string StatusToString(const mojom::TokenPinStatusCode& status) { return ""; } -std::string ErrorCodeToString( +// static +std::string BraveWalletPinService::ErrorCodeToString( const mojom::WalletPinServiceErrorCode& error_code) { switch (error_code) { case mojom::WalletPinServiceErrorCode::ERR_WRONG_TOKEN: @@ -149,6 +149,52 @@ std::string ErrorCodeToString( return ""; } +// static +bool BraveWalletPinService::IsTokenSupportedForPinning( + const mojom::BlockchainTokenPtr& token) { + return token->is_erc721; +} + +/** + * Structure of kPinnedNFTAssets prefs: + * // Type of pinned content + * "nft" : { + * // List of services + * "local" : { + * // Coin type + * "60": { + * // Chain id + * "0x1": { + * // Contract + * "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d" : { + * // Token id + * "3139" : { + * "status": , + * "validate_timestamp": , + * "error": { + * "error_code": , + * "error_message": , + * }, + * cids: [ + * // List of related CIDs + * "bafy..", + * ... + * ] + * } + * ... + * } + * ... + * } + * ... + * } + * ... + * }, + * // Remote service + * nftstorage : { + * ... + * } + * } + */ BraveWalletPinService::BraveWalletPinService( PrefService* prefs, JsonRpcService* service, @@ -188,9 +234,9 @@ void BraveWalletPinService::AddObserver( } // static -absl::optional BraveWalletPinService::GetPath( +absl::optional BraveWalletPinService::GetTokenPrefPath( const absl::optional& service, - const BlockchainTokenPtr& token) { + const mojom::BlockchainTokenPtr& token) { if (service && base::ContainsOnlyChars(service.value(), ".")) { return absl::nullopt; } @@ -208,7 +254,7 @@ absl::optional BraveWalletPinService::GetPath( } // static -BlockchainTokenPtr BraveWalletPinService::TokenFromPath( +mojom::BlockchainTokenPtr BraveWalletPinService::TokenFromPrefPath( const std::string& path) { std::vector parts = base::SplitString(path, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); @@ -224,13 +270,12 @@ BlockchainTokenPtr BraveWalletPinService::TokenFromPath( token->chain_id = parts.at(3); token->contract_address = parts.at(4); token->token_id = parts.at(5); - token->is_erc721 = true; token->is_nft = true; return token; } // static -absl::optional BraveWalletPinService::ServiceFromPath( +absl::optional BraveWalletPinService::ServiceFromPrefPath( const std::string& path) { std::vector parts = base::SplitString(path, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); @@ -244,7 +289,7 @@ absl::optional BraveWalletPinService::ServiceFromPath( } } -void BraveWalletPinService::Validate(BlockchainTokenPtr token, +void BraveWalletPinService::Validate(mojom::BlockchainTokenPtr token, const absl::optional& service, ValidateCallback callback) { mojom::TokenPinStatusPtr status = GetTokenStatus(service, token); @@ -268,7 +313,7 @@ void BraveWalletPinService::Validate(BlockchainTokenPtr token, return; } - auto path = GetPath(absl::nullopt, token); + auto path = GetTokenPrefPath(absl::nullopt, token); if (!path) { std::move(callback).Run( false, @@ -281,8 +326,8 @@ void BraveWalletPinService::Validate(BlockchainTokenPtr token, local_pin_service_->ValidatePins( path.value(), cids.value(), base::BindOnce(&BraveWalletPinService::OnTokenValidated, - base::Unretained(this), service, std::move(callback), - std::move(token))); + weak_ptr_factory_.GetWeakPtr(), service, + std::move(callback), std::move(token))); } else { // Remote pinning not implemented yet std::move(callback).Run(false, nullptr); @@ -294,6 +339,12 @@ void BraveWalletPinService::IsLocalNodeRunning( std::move(callback).Run(ipfs_service_->IsDaemonLaunched()); } +void BraveWalletPinService::IsTokenSupported( + mojom::BlockchainTokenPtr token, + IsTokenSupportedCallback callback) { + std::move(callback).Run(IsTokenSupportedForPinning(token)); +} + void BraveWalletPinService::OnIpfsLaunched(bool result, int64_t pid) { for (const auto& observer : observers_) { observer->OnLocalNodeStatusChanged(result); @@ -320,16 +371,14 @@ void BraveWalletPinService::MarkAsPendingForUnpinning( mojom::TokenPinStatusCode::STATUS_UNPINNING_PENDING, nullptr); } -void BraveWalletPinService::AddPin(BlockchainTokenPtr token, +void BraveWalletPinService::AddPin(mojom::BlockchainTokenPtr token, const absl::optional& service, AddPinCallback callback) { - if (!token->is_nft) { - auto pin_error = mojom::PinError::New( - mojom::WalletPinServiceErrorCode::ERR_WRONG_TOKEN, "Token is not nft"); - - VLOG(1) << "Token is not nft"; - FinishAddingWithResult(service, token, false, std::move(pin_error), - std::move(callback)); + if (!IsTokenSupportedForPinning(token)) { + auto pin_error = + mojom::PinError::New(mojom::WalletPinServiceErrorCode::ERR_WRONG_TOKEN, + "Token pinning is not supported"); + std::move(callback).Run(false, std::move(pin_error)); return; } @@ -338,21 +387,19 @@ void BraveWalletPinService::AddPin(BlockchainTokenPtr token, token_status->code == mojom::TokenPinStatusCode::STATUS_PINNED) { auto pin_error = mojom::PinError::New( mojom::WalletPinServiceErrorCode::ERR_ALREADY_PINNED, "Already pinned"); - - FinishAddingWithResult(service, token, true, std::move(pin_error), - std::move(callback)); + std::move(callback).Run(true, std::move(pin_error)); return; } json_rpc_service_->GetERC721Metadata( token->contract_address, token->token_id, token->chain_id, base::BindOnce(&BraveWalletPinService::OnTokenMetaDataReceived, - base::Unretained(this), service, std::move(callback), - token.Clone())); + weak_ptr_factory_.GetWeakPtr(), service, + std::move(callback), token.Clone())); } void BraveWalletPinService::RemovePin( - BlockchainTokenPtr token, + mojom::BlockchainTokenPtr token, const absl::optional& service, RemovePinCallback callback) { auto token_status = GetTokenStatus(service, token); @@ -361,7 +408,7 @@ void BraveWalletPinService::RemovePin( return; } - auto path = GetPath(absl::nullopt, token); + auto path = GetTokenPrefPath(absl::nullopt, token); if (!path) { std::move(callback).Run( false, @@ -377,7 +424,7 @@ void BraveWalletPinService::RemovePin( if (!service) { local_pin_service_->RemovePins( path.value(), base::BindOnce(&BraveWalletPinService::OnPinsRemoved, - base::Unretained(this), service, + weak_ptr_factory_.GetWeakPtr(), service, std::move(callback), std::move(token))); } else { // Remote pinning not implemented yet @@ -385,7 +432,7 @@ void BraveWalletPinService::RemovePin( } } -void BraveWalletPinService::GetTokenStatus(BlockchainTokenPtr token, +void BraveWalletPinService::GetTokenStatus(mojom::BlockchainTokenPtr token, GetTokenStatusCallback callback) { mojom::TokenPinOverviewPtr result = mojom::TokenPinOverview::New(); result->local = GetTokenStatus(absl::nullopt, token); @@ -420,8 +467,7 @@ void BraveWalletPinService::OnTokenMetaDataReceived( "Failed to obtain token metadata"); SetTokenStatus(service, token, mojom::TokenPinStatusCode::STATUS_PINNING_FAILED, pin_error); - FinishAddingWithResult(service, token, false, std::move(pin_error), - std::move(callback)); + std::move(callback).Run(false, std::move(pin_error)); return; } @@ -432,8 +478,7 @@ void BraveWalletPinService::OnTokenMetaDataReceived( "Metadata has non-ipfs url"); SetTokenStatus(service, token, mojom::TokenPinStatusCode::STATUS_PINNING_FAILED, pin_error); - FinishAddingWithResult(service, token, false, std::move(pin_error), - std::move(callback)); + std::move(callback).Run(false, std::move(pin_error)); return; } @@ -446,8 +491,7 @@ void BraveWalletPinService::OnTokenMetaDataReceived( "Wrong metadata format"); SetTokenStatus(service, token, mojom::TokenPinStatusCode::STATUS_PINNING_FAILED, pin_error); - FinishAddingWithResult(service, token, false, std::move(pin_error), - std::move(callback)); + std::move(callback).Run(false, std::move(pin_error)); return; } @@ -462,7 +506,7 @@ void BraveWalletPinService::OnTokenMetaDataReceived( } } - auto path = GetPath(service, token); + auto path = GetTokenPrefPath(service, token); if (!path) { std::move(callback).Run( false, @@ -471,7 +515,7 @@ void BraveWalletPinService::OnTokenMetaDataReceived( return; } - CreateToken(service, token, cids); + AddToken(service, token, cids); SetTokenStatus(service, token, mojom::TokenPinStatusCode::STATUS_PINNING_IN_PROGRESS, nullptr); @@ -480,7 +524,7 @@ void BraveWalletPinService::OnTokenMetaDataReceived( local_pin_service_->AddPins( path.value(), cids, base::BindOnce(&BraveWalletPinService::OnTokenPinned, - base::Unretained(this), absl::nullopt, + weak_ptr_factory_.GetWeakPtr(), absl::nullopt, std::move(callback), std::move(token))); } else { // Remote pinning not implemented yet @@ -502,8 +546,7 @@ void BraveWalletPinService::OnTokenPinned(absl::optional service, : mojom::TokenPinStatusCode::STATUS_PINNING_FAILED, error); - FinishAddingWithResult(service, token, result, std::move(error), - std::move(callback)); + std::move(callback).Run(result, std::move(error)); } void BraveWalletPinService::OnTokenValidated( @@ -529,43 +572,45 @@ void BraveWalletPinService::OnTokenValidated( std::move(callback).Run(true, nullptr); } -bool BraveWalletPinService::CreateToken( - const absl::optional& service, - const mojom::BlockchainTokenPtr& token, - const std::vector& cids) { - auto path = GetPath(service, token); +bool BraveWalletPinService::AddToken(const absl::optional& service, + const mojom::BlockchainTokenPtr& token, + const std::vector& cids) { + auto path = GetTokenPrefPath(service, token); if (!path) { return false; } - DictionaryPrefUpdate update(prefs_, kPinnedErc721Assets); - base::Value::Dict& update_dict = update->GetDict(); + { + DictionaryPrefUpdate update(prefs_, kPinnedNFTAssets); + base::Value::Dict& update_dict = update->GetDict(); - base::Value::Dict token_data; - base::Value::List cids_list; + base::Value::Dict token_data; + base::Value::List cids_list; - for (const auto& cid : cids) { - cids_list.Append(cid); - } + for (const auto& cid : cids) { + cids_list.Append(cid); + } - token_data.Set(kAssetUrlListKey, std::move(cids_list)); - token_data.Set(kAssetStatus, - StatusToString(mojom::TokenPinStatusCode::STATUS_NOT_PINNED)); + token_data.Set(kAssetUrlListKey, std::move(cids_list)); + token_data.Set( + kAssetStatus, + StatusToString(mojom::TokenPinStatusCode::STATUS_NOT_PINNED)); - update_dict.SetByDottedPath(path.value(), std::move(token_data)); + update_dict.SetByDottedPath(path.value(), std::move(token_data)); + } return true; } bool BraveWalletPinService::RemoveToken( const absl::optional& service, const mojom::BlockchainTokenPtr& token) { - auto path = GetPath(service, token); + auto path = GetTokenPrefPath(service, token); if (!path) { return false; } { - DictionaryPrefUpdate update(prefs_, kPinnedErc721Assets); + DictionaryPrefUpdate update(prefs_, kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); update_dict.RemoveByDottedPath(path.value()); } @@ -581,13 +626,13 @@ bool BraveWalletPinService::SetTokenStatus( const mojom::BlockchainTokenPtr& token, mojom::TokenPinStatusCode status, const mojom::PinErrorPtr& error) { - auto path = GetPath(service, token); + auto path = GetTokenPrefPath(service, token); if (!path) { return false; } { - DictionaryPrefUpdate update(prefs_, kPinnedErc721Assets); + DictionaryPrefUpdate update(prefs_, kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); update_dict.SetByDottedPath(path.value() + "." + kAssetStatus, @@ -618,11 +663,11 @@ bool BraveWalletPinService::SetTokenStatus( absl::optional> BraveWalletPinService::ResolvePinItems( const absl::optional& service, - const BlockchainTokenPtr& token) { + const mojom::BlockchainTokenPtr& token) { const base::Value::Dict& pinned_assets_pref = - prefs_->GetDict(kPinnedErc721Assets); + prefs_->GetDict(kPinnedNFTAssets); - auto path = GetPath(service, token); + auto path = GetTokenPrefPath(service, token); if (!path) { return absl::nullopt; } @@ -650,9 +695,9 @@ mojom::TokenPinStatusPtr BraveWalletPinService::GetTokenStatus( const absl::optional& service, const mojom::BlockchainTokenPtr& token) { const base::Value::Dict& pinned_assets_pref = - prefs_->GetDict(kPinnedErc721Assets); + prefs_->GetDict(kPinnedNFTAssets); - auto path = GetPath(service, token); + auto path = GetTokenPrefPath(service, token); if (!path) { return nullptr; } @@ -704,9 +749,9 @@ absl::optional BraveWalletPinService::GetLastValidateTime( const absl::optional& service, const mojom::BlockchainTokenPtr& token) { const base::Value::Dict& pinned_assets_pref = - prefs_->GetDict(kPinnedErc721Assets); + prefs_->GetDict(kPinnedNFTAssets); - auto path = GetPath(service, token); + auto path = GetTokenPrefPath(service, token); if (!path) { return absl::nullopt; } @@ -721,21 +766,12 @@ absl::optional BraveWalletPinService::GetLastValidateTime( return base::ValueToTime(time); } -void BraveWalletPinService::FinishAddingWithResult( - const absl::optional& service, - const mojom::BlockchainTokenPtr& token, - bool result, - mojom::PinErrorPtr error, - AddPinCallback callback) { - std::move(callback).Run(result, std::move(error)); -} - std::set BraveWalletPinService::GetTokens( const absl::optional& service) { std::set result; const base::Value::Dict& pinned_assets_pref = - prefs_->GetDict(kPinnedErc721Assets); + prefs_->GetDict(kPinnedNFTAssets); const base::Value::Dict* service_dict = pinned_assets_pref.FindDictByDottedPath( diff --git a/components/brave_wallet/browser/brave_wallet_pin_service.h b/components/brave_wallet/browser/brave_wallet_pin_service.h index cc2b572b8105..461b695c5f6d 100644 --- a/components/brave_wallet/browser/brave_wallet_pin_service.h +++ b/components/brave_wallet/browser/brave_wallet_pin_service.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -12,6 +12,7 @@ #include "base/containers/cxx20_erase_deque.h" #include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" #include "base/task/sequenced_task_runner.h" #include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/json_rpc_service.h" @@ -24,14 +25,8 @@ #include "mojo/public/cpp/bindings/remote_set.h" #include "third_party/abseil-cpp/absl/types/optional.h" -using brave_wallet::mojom::BlockchainTokenPtr; - namespace brave_wallet { -std::string StatusToString(const mojom::TokenPinStatusCode& status); -std::string ErrorCodeToString( - const mojom::WalletPinServiceErrorCode& error_code); - class BraveWalletPinService : public KeyedService, public brave_wallet::mojom::WalletPinService, public ipfs::IpfsServiceObserver { @@ -45,27 +40,35 @@ class BraveWalletPinService : public KeyedService, mojo::PendingRemote MakeRemote(); void Bind(mojo::PendingReceiver receiver); - static absl::optional GetPath( + static absl::optional GetTokenPrefPath( const absl::optional& service, - const BlockchainTokenPtr& token); - static BlockchainTokenPtr TokenFromPath(const std::string& path); - static absl::optional ServiceFromPath(const std::string& path); + const mojom::BlockchainTokenPtr& token); + static mojom::BlockchainTokenPtr TokenFromPrefPath(const std::string& path); + static absl::optional ServiceFromPrefPath( + const std::string& path); + static std::string StatusToString(const mojom::TokenPinStatusCode& status); + static std::string ErrorCodeToString( + const mojom::WalletPinServiceErrorCode& error_code); + static bool IsTokenSupportedForPinning( + const mojom::BlockchainTokenPtr& token); // WalletPinService void AddObserver(::mojo::PendingRemote observer) override; - void AddPin(BlockchainTokenPtr token, + void AddPin(mojom::BlockchainTokenPtr token, const absl::optional& service, AddPinCallback callback) override; - void RemovePin(BlockchainTokenPtr token, + void RemovePin(mojom::BlockchainTokenPtr token, const absl::optional& service, RemovePinCallback callback) override; - void GetTokenStatus(BlockchainTokenPtr token, + void GetTokenStatus(mojom::BlockchainTokenPtr token, GetTokenStatusCallback callback) override; - void Validate(BlockchainTokenPtr token, + void Validate(mojom::BlockchainTokenPtr token, const absl::optional& service, ValidateCallback callback) override; void IsLocalNodeRunning(IsLocalNodeRunningCallback callback) override; + void IsTokenSupported(mojom::BlockchainTokenPtr token, + IsTokenSupportedCallback callback) override; virtual void MarkAsPendingForPinning( const mojom::BlockchainTokenPtr& token, @@ -80,6 +83,9 @@ class BraveWalletPinService : public KeyedService, virtual absl::optional GetLastValidateTime( const absl::optional& service, const mojom::BlockchainTokenPtr& token); + // Returns list of known tokens for the provided pinning service. + // Tokens are returned in the format of string path. + // See BraveWalletPinService::GetTokenPrefPath. virtual std::set GetTokens( const absl::optional& service); @@ -88,9 +94,9 @@ class BraveWalletPinService : public KeyedService, BraveWalletPinService(); private: - bool CreateToken(const absl::optional& service, - const mojom::BlockchainTokenPtr& token, - const std::vector& cids); + bool AddToken(const absl::optional& service, + const mojom::BlockchainTokenPtr& token, + const std::vector& cids); bool RemoveToken(const absl::optional& service, const mojom::BlockchainTokenPtr& token); bool SetTokenStatus(const absl::optional& service, @@ -98,15 +104,9 @@ class BraveWalletPinService : public KeyedService, mojom::TokenPinStatusCode, const mojom::PinErrorPtr& error); - void FinishAddingWithResult(const absl::optional& service, - const mojom::BlockchainTokenPtr& token, - bool result, - mojom::PinErrorPtr error, - AddPinCallback callback); - absl::optional> ResolvePinItems( const absl::optional& service, - const BlockchainTokenPtr& token); + const mojom::BlockchainTokenPtr& token); void OnPinsRemoved(absl::optional service, RemovePinCallback callback, @@ -143,6 +143,8 @@ class BraveWalletPinService : public KeyedService, raw_ptr json_rpc_service_ = nullptr; raw_ptr local_pin_service_ = nullptr; raw_ptr ipfs_service_ = nullptr; + + base::WeakPtrFactory weak_ptr_factory_{this}; }; } // namespace brave_wallet diff --git a/components/brave_wallet/browser/brave_wallet_pin_service_unittest.cc b/components/brave_wallet/browser/brave_wallet_pin_service_unittest.cc index f7904f898afc..93c8417230c7 100644 --- a/components/brave_wallet/browser/brave_wallet_pin_service_unittest.cc +++ b/components/brave_wallet/browser/brave_wallet_pin_service_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -111,7 +111,7 @@ class BraveWalletPinServiceTest : public testing::Test { protected: void SetUp() override { auto* registry = pref_service_.registry(); - registry->RegisterDictionaryPref(kPinnedErc721Assets); + registry->RegisterDictionaryPref(kPinnedNFTAssets); brave_wallet_pin_service_ = std::make_unique( GetPrefs(), GetJsonRpcService(), GetIpfsLocalPinService(), GetIpfsService()); @@ -169,8 +169,8 @@ TEST_F(BraveWalletPinServiceTest, AddPin) { auto scoped_override = OverrideWithTimeNow(base::Time::FromTimeT(123u)); mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token->is_erc721 = true; absl::optional call_status; service()->AddPin( std::move(token), absl::nullopt, @@ -183,14 +183,15 @@ TEST_F(BraveWalletPinServiceTest, AddPin) { const base::Value::Dict* token_record = GetPrefs() - ->GetDict(kPinnedErc721Assets) + ->GetDict(kPinnedNFTAssets) .FindDictByDottedPath(kMonkey1Path); base::Value::List expected_cids; expected_cids.Append("QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq"); expected_cids.Append("Qmcyc7tm9sZB9JnvLgejPTwdzjjNjDMiRWCUvaZAfp6cUg"); - EXPECT_EQ(StatusToString(mojom::TokenPinStatusCode::STATUS_PINNED), + EXPECT_EQ(BraveWalletPinService::StatusToString( + mojom::TokenPinStatusCode::STATUS_PINNED), *(token_record->FindString("status"))); EXPECT_EQ(nullptr, token_record->FindDict("error")); EXPECT_EQ(expected_cids, *(token_record->FindList("cids"))); @@ -213,8 +214,8 @@ TEST_F(BraveWalletPinServiceTest, AddPin) { })); mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey2Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey2Path); + token->is_erc721 = true; absl::optional call_status; service()->AddPin( std::move(token), absl::nullopt, @@ -228,12 +229,13 @@ TEST_F(BraveWalletPinServiceTest, AddPin) { const base::Value::Dict* token_record = GetPrefs() - ->GetDict(kPinnedErc721Assets) + ->GetDict(kPinnedNFTAssets) .FindDictByDottedPath(kMonkey2Path); - EXPECT_EQ(StatusToString(mojom::TokenPinStatusCode::STATUS_PINNING_FAILED), + EXPECT_EQ(BraveWalletPinService::StatusToString( + mojom::TokenPinStatusCode::STATUS_PINNING_FAILED), *(token_record->FindString("status"))); - EXPECT_EQ(ErrorCodeToString( + EXPECT_EQ(BraveWalletPinService::ErrorCodeToString( mojom::WalletPinServiceErrorCode::ERR_FETCH_METADATA_FAILED), token_record->FindByDottedPath("error.error_code")->GetString()); } @@ -241,7 +243,7 @@ TEST_F(BraveWalletPinServiceTest, AddPin) { TEST_F(BraveWalletPinServiceTest, RemovePin) { { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; @@ -263,8 +265,8 @@ TEST_F(BraveWalletPinServiceTest, RemovePin) { })); mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token->is_erc721 = true; absl::optional remove_status; service()->RemovePin( std::move(token), absl::nullopt, @@ -273,12 +275,12 @@ TEST_F(BraveWalletPinServiceTest, RemovePin) { remove_status = status; })); EXPECT_FALSE(remove_status.value()); - EXPECT_EQ( - StatusToString(mojom::TokenPinStatusCode::STATUS_UNPINNING_FAILED), - *(GetPrefs() - ->GetDict(kPinnedErc721Assets) - .FindByDottedPath(kMonkey1Path) - ->FindStringKey("status"))); + EXPECT_EQ(BraveWalletPinService::StatusToString( + mojom::TokenPinStatusCode::STATUS_UNPINNING_FAILED), + *(GetPrefs() + ->GetDict(kPinnedNFTAssets) + .FindByDottedPath(kMonkey1Path) + ->FindStringKey("status"))); } { @@ -290,8 +292,8 @@ TEST_F(BraveWalletPinServiceTest, RemovePin) { })); mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token->is_erc721 = true; absl::optional remove_status; service()->RemovePin( std::move(token), absl::nullopt, @@ -301,14 +303,14 @@ TEST_F(BraveWalletPinServiceTest, RemovePin) { })); EXPECT_TRUE(remove_status.value()); EXPECT_EQ(nullptr, GetPrefs() - ->GetDict(kPinnedErc721Assets) + ->GetDict(kPinnedNFTAssets) .FindDictByDottedPath(kMonkey1Path)); } } TEST_F(BraveWalletPinServiceTest, ValidatePin) { { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; @@ -326,8 +328,8 @@ TEST_F(BraveWalletPinServiceTest, ValidatePin) { auto scoped_override = OverrideWithTimeNow(base::Time::FromTimeT(345u)); mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token->is_erc721 = true; ON_CALL(*GetIpfsLocalPinService(), ValidatePins(_, _, _)) .WillByDefault(::testing::Invoke( [](const std::string& prefix, const std::vector& cids, @@ -351,7 +353,7 @@ TEST_F(BraveWalletPinServiceTest, ValidatePin) { const base::Value::Dict* token_record = GetPrefs() - ->GetDict(kPinnedErc721Assets) + ->GetDict(kPinnedNFTAssets) .FindDictByDottedPath(kMonkey1Path); EXPECT_EQ(base::Time::FromTimeT(345u), base::ValueToTime(token_record->Find("validate_timestamp"))); @@ -359,8 +361,8 @@ TEST_F(BraveWalletPinServiceTest, ValidatePin) { { mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token->is_erc721 = true; ON_CALL(*GetIpfsLocalPinService(), ValidatePins(_, _, _)) .WillByDefault(::testing::Invoke( [](const std::string& prefix, const std::vector& cids, @@ -380,7 +382,7 @@ TEST_F(BraveWalletPinServiceTest, ValidatePin) { const base::Value::Dict* token_record = GetPrefs() - ->GetDict(kPinnedErc721Assets) + ->GetDict(kPinnedNFTAssets) .FindDictByDottedPath(kMonkey1Path); EXPECT_EQ(base::Time::FromTimeT(345u), base::ValueToTime(token_record->Find("validate_timestamp"))); @@ -388,8 +390,8 @@ TEST_F(BraveWalletPinServiceTest, ValidatePin) { { mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token->is_erc721 = true; ON_CALL(*GetIpfsLocalPinService(), ValidatePins(_, _, _)) .WillByDefault(::testing::Invoke( [](const std::string& prefix, const std::vector& cids, @@ -409,7 +411,7 @@ TEST_F(BraveWalletPinServiceTest, ValidatePin) { const base::Value::Dict* token_record = GetPrefs() - ->GetDict(kPinnedErc721Assets) + ->GetDict(kPinnedNFTAssets) .FindDictByDottedPath(kMonkey1Path); EXPECT_EQ(nullptr, token_record->Find("validate_timestamp")); @@ -418,7 +420,7 @@ TEST_F(BraveWalletPinServiceTest, ValidatePin) { TEST_F(BraveWalletPinServiceTest, GetTokenStatus) { { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; @@ -434,15 +436,15 @@ TEST_F(BraveWalletPinServiceTest, GetTokenStatus) { } { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; - item.Set("status", - StatusToString(mojom::TokenPinStatusCode::STATUS_PINNING_FAILED)); + item.Set("status", BraveWalletPinService::StatusToString( + mojom::TokenPinStatusCode::STATUS_PINNING_FAILED)); base::Value::Dict error; error.Set("error_code", - ErrorCodeToString( + BraveWalletPinService::ErrorCodeToString( mojom::WalletPinServiceErrorCode::ERR_FETCH_METADATA_FAILED)); error.Set("error_message", "Fail to fetch metadata"); item.Set("error", std::move(error)); @@ -451,8 +453,8 @@ TEST_F(BraveWalletPinServiceTest, GetTokenStatus) { } mojom::BlockchainTokenPtr token1 = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token1->is_erc721 = true; { mojom::TokenPinStatusPtr status = service()->GetTokenStatus(absl::nullopt, token1); @@ -468,8 +470,8 @@ TEST_F(BraveWalletPinServiceTest, GetTokenStatus) { } mojom::BlockchainTokenPtr token2 = - BraveWalletPinService::TokenFromPath(kMonkey2Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey2Path); + token2->is_erc721 = true; { mojom::TokenPinStatusPtr status = service()->GetTokenStatus(absl::nullopt, token2); @@ -482,7 +484,7 @@ TEST_F(BraveWalletPinServiceTest, GetTokenStatus) { TEST_F(BraveWalletPinServiceTest, GetLastValidateTime) { { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; @@ -498,8 +500,8 @@ TEST_F(BraveWalletPinServiceTest, GetLastValidateTime) { } mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); + token->is_erc721 = true; { base::Time last_validate_time = service()->GetLastValidateTime(absl::nullopt, token).value(); @@ -512,10 +514,9 @@ TEST_F(BraveWalletPinServiceTest, GetLastValidateTime) { } } -TEST_F(BraveWalletPinServiceTest, TokenFromPath) { +TEST_F(BraveWalletPinServiceTest, TokenFromPrefPath) { mojom::BlockchainTokenPtr token = - BraveWalletPinService::TokenFromPath(kMonkey1Path); - EXPECT_TRUE(token->is_erc721); + BraveWalletPinService::TokenFromPrefPath(kMonkey1Path); EXPECT_EQ(mojom::CoinType::ETH, static_cast(token->coin)); EXPECT_EQ("0x1", token->chain_id); EXPECT_EQ("0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d", @@ -525,9 +526,9 @@ TEST_F(BraveWalletPinServiceTest, TokenFromPath) { TEST_F(BraveWalletPinServiceTest, ServiceFromPath) { EXPECT_FALSE( - BraveWalletPinService::ServiceFromPath(kMonkey1Path).has_value()); + BraveWalletPinService::ServiceFromPrefPath(kMonkey1Path).has_value()); - EXPECT_EQ("nftstorage", BraveWalletPinService::ServiceFromPath( + EXPECT_EQ("nftstorage", BraveWalletPinService::ServiceFromPrefPath( "nft.nftstorage.60.0x1." "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1") .value()); @@ -540,7 +541,7 @@ TEST_F(BraveWalletPinServiceTest, GetPath) { token->contract_address = "abc"; token->token_id = "0x2"; token->chain_id = "mainnet"; - auto path = BraveWalletPinService::GetPath(absl::nullopt, token); + auto path = BraveWalletPinService::GetTokenPrefPath(absl::nullopt, token); EXPECT_EQ("nft.local.60.mainnet.abc.0x2", path.value()); } @@ -550,14 +551,14 @@ TEST_F(BraveWalletPinServiceTest, GetPath) { token->contract_address = "abc"; token->token_id = "0x2"; token->chain_id = "mainnet"; - auto path = BraveWalletPinService::GetPath("nftstorage", token); + auto path = BraveWalletPinService::GetTokenPrefPath("nftstorage", token); EXPECT_EQ("nft.nftstorage.60.mainnet.abc.0x2", path.value()); } } TEST_F(BraveWalletPinServiceTest, GetTokens) { { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; @@ -567,7 +568,7 @@ TEST_F(BraveWalletPinServiceTest, GetTokens) { } { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; @@ -577,7 +578,7 @@ TEST_F(BraveWalletPinServiceTest, GetTokens) { } { - DictionaryPrefUpdate update(GetPrefs(), kPinnedErc721Assets); + DictionaryPrefUpdate update(GetPrefs(), kPinnedNFTAssets); base::Value::Dict& update_dict = update->GetDict(); base::Value::Dict item; diff --git a/components/brave_wallet/browser/brave_wallet_prefs.cc b/components/brave_wallet/browser/brave_wallet_prefs.cc index af1520cc2ebb..3f2f5cd7d019 100644 --- a/components/brave_wallet/browser/brave_wallet_prefs.cc +++ b/components/brave_wallet/browser/brave_wallet_prefs.cc @@ -127,7 +127,7 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { registry->RegisterTimePref(kBraveWalletP3AFirstReportTime, base::Time()); registry->RegisterListPref(kBraveWalletP3AWeeklyStorage); - registry->RegisterDictionaryPref(kPinnedErc721Assets); + registry->RegisterDictionaryPref(kPinnedNFTAssets); registry->RegisterBooleanPref(kAutoPinEnabled, false); } @@ -198,7 +198,7 @@ void ClearBraveWalletServicePrefs(PrefService* prefs) { prefs->ClearPref(kBraveWalletUserAssets); prefs->ClearPref(kDefaultBaseCurrency); prefs->ClearPref(kDefaultBaseCryptocurrency); - prefs->ClearPref(kPinnedErc721Assets); + prefs->ClearPref(kPinnedNFTAssets); } void MigrateObsoleteProfilePrefs(PrefService* prefs) { diff --git a/components/brave_wallet/browser/brave_wallet_service.cc b/components/brave_wallet/browser/brave_wallet_service.cc index f3dfca23f3c5..82ec48511315 100644 --- a/components/brave_wallet/browser/brave_wallet_service.cc +++ b/components/brave_wallet/browser/brave_wallet_service.cc @@ -283,7 +283,7 @@ std::vector BraveWalletService::GetUserAssets( std::vector result; const auto& user_assets_dict = profile_prefs->GetDict(kBraveWalletUserAssets); for (auto coin_it : user_assets_dict) { - auto coin = GetCoinFromPref(coin_it.first); + auto coin = GetCoinTypeFromPrefKey(coin_it.first); if (!coin) continue; diff --git a/components/brave_wallet/browser/brave_wallet_utils.cc b/components/brave_wallet/browser/brave_wallet_utils.cc index 090183c9f83e..f682a025b68a 100644 --- a/components/brave_wallet/browser/brave_wallet_utils.cc +++ b/components/brave_wallet/browser/brave_wallet_utils.cc @@ -1389,12 +1389,12 @@ std::string GetPrefKeyForCoinType(mojom::CoinType coin) { return ""; } -absl::optional GetCoinFromPref(const std::string& pref) { - if (pref == kEthereumPrefKey) { +absl::optional GetCoinTypeFromPrefKey(const std::string& key) { + if (key == kEthereumPrefKey) { return mojom::CoinType::ETH; - } else if (pref == kFilecoinPrefKey) { + } else if (key == kFilecoinPrefKey) { return mojom::CoinType::FIL; - } else if (pref == kSolanaPrefKey) { + } else if (key == kSolanaPrefKey) { return mojom::CoinType::SOL; } NOTREACHED(); diff --git a/components/brave_wallet/browser/brave_wallet_utils.h b/components/brave_wallet/browser/brave_wallet_utils.h index fbdeafa1eff6..0f45c440441a 100644 --- a/components/brave_wallet/browser/brave_wallet_utils.h +++ b/components/brave_wallet/browser/brave_wallet_utils.h @@ -152,7 +152,7 @@ std::string GetCurrentChainId(PrefService* prefs, mojom::CoinType coin); std::string GetPrefKeyForCoinType(mojom::CoinType coin); // Converts string representation of CoinType to enum. -absl::optional GetCoinFromPref(const std::string& pref); +absl::optional GetCoinTypeFromPrefKey(const std::string& key); // Resolves chain_id from network_id. absl::optional GetChainId(PrefService* prefs, diff --git a/components/brave_wallet/browser/pref_names.cc b/components/brave_wallet/browser/pref_names.cc index aa347c29089a..a7da02ebf79d 100644 --- a/components/brave_wallet/browser/pref_names.cc +++ b/components/brave_wallet/browser/pref_names.cc @@ -72,5 +72,5 @@ const char kBraveWalletCurrentChainId[] = const char kBraveWalletUserAssetsDeprecated[] = "brave.wallet.user_assets"; const char kBraveWalletUserAssetsAddPreloadingNetworksMigratedDeprecated[] = "brave.wallet.user.assets.add_preloading_networks_migrated"; -const char kPinnedErc721Assets[] = "brave.wallet.user_pin_data"; +const char kPinnedNFTAssets[] = "brave.wallet.user_pin_data"; const char kAutoPinEnabled[] = "brave.wallet.auto_pin_enabled"; diff --git a/components/brave_wallet/browser/pref_names.h b/components/brave_wallet/browser/pref_names.h index 51bf85873a32..555074102924 100644 --- a/components/brave_wallet/browser/pref_names.h +++ b/components/brave_wallet/browser/pref_names.h @@ -59,7 +59,7 @@ extern const char kBraveWalletCurrentChainId[]; extern const char kBraveWalletUserAssetsDeprecated[]; extern const char kBraveWalletUserAssetsAddPreloadingNetworksMigratedDeprecated[]; -extern const char kPinnedErc721Assets[]; +extern const char kPinnedNFTAssets[]; extern const char kAutoPinEnabled[]; #endif // BRAVE_COMPONENTS_BRAVE_WALLET_BROWSER_PREF_NAMES_H_ diff --git a/components/brave_wallet/common/brave_wallet.mojom b/components/brave_wallet/common/brave_wallet.mojom index cf577283ebac..9ab969ca61f6 100644 --- a/components/brave_wallet/common/brave_wallet.mojom +++ b/components/brave_wallet/common/brave_wallet.mojom @@ -212,9 +212,13 @@ interface SolanaProvider { mojo_base.mojom.DictionaryValue result); }; + enum WalletPinServiceErrorCode { + // Token not supported for pinning ERR_WRONG_TOKEN = 1, + // Token metadata has non-ipfs url ERR_NON_IPFS_TOKEN_URL = 2, + // Fetching metadata has failed ERR_FETCH_METADATA_FAILED = 3, ERR_WRONG_METADATA_FORMAT = 4, ERR_ALREADY_PINNED = 5, @@ -239,41 +243,57 @@ struct PinError { }; struct TokenPinStatus { + // Actual token status TokenPinStatusCode code; + // Token error related to the pin status. May be null. PinError? error; + // Last time token was validated(checked that data is pinned correctly) mojo_base.mojom.Time validate_time; }; struct TokenPinOverview { + // Token status for the local pin backend. TokenPinStatus? local; + // Token statuses for remote pin backends. map remotes; }; +// Observers state of the BraveWalletPinService interface BraveWalletPinServiceObserver { OnTokenStatusChanged(string? service, BlockchainToken token, TokenPinStatus status); OnLocalNodeStatusChanged(bool running); }; +// Low-level interface for token pinning. interface WalletPinService { AddObserver(pending_remote observer); + // Launches pinning for provided token. + // At the moment only local pinning is supported so use null "service" argument. AddPin(BlockchainToken token, string? service) =>(bool result, PinError? error); + // Unpins token. RemovePin(BlockchainToken token, string? service) => (bool result, PinError? response); + // Returns overview for provided token. GetTokenStatus(BlockchainToken token) => (TokenPinOverview? status, PinError? error); + // Checks whether token in pinned correctly. Validate(BlockchainToken token, string? service) => (bool result, PinError? error); + // Returns whether IPFS localnode is currently running. IsLocalNodeRunning() => (bool result); + + // Returns whether token is supported for pinning. + IsTokenSupported(BlockchainToken token) => (bool result); }; +// Listens for added user tokens and automatically pins them. interface WalletAutoPinService { + // Enables autopinning, so old and new user tokens may be pinned. SetAutoPinEnabled(bool enabled); IsAutoPinEnabled() => (bool enabled); - PostPinToken(BlockchainToken token) => (bool result); - PostUnpinToken(BlockchainToken token) => (bool result); }; // Used by the WebUI page to bootstrap bidirectional communication. diff --git a/components/ipfs/BUILD.gn b/components/ipfs/BUILD.gn index bba5c0c51458..8dee6455e938 100644 --- a/components/ipfs/BUILD.gn +++ b/components/ipfs/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 The Brave Authors. All rights reserved. +# Copyright (c) 2020 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 https://mozilla.org/MPL/2.0/. diff --git a/components/ipfs/ipfs_json_parser.cc b/components/ipfs/ipfs_json_parser.cc index 330671332b86..2ddd7d7ba3c8 100644 --- a/components/ipfs/ipfs_json_parser.cc +++ b/components/ipfs/ipfs_json_parser.cc @@ -71,7 +71,12 @@ absl::optional IPFSJSONParser::GetAddPinsResultFromJSON( } for (const base::Value& val : *pins_list) { - result.pins.push_back(val.GetString()); + auto* val_as_str = val.GetIfString(); + if (!val_as_str) { + VLOG(1) << "Invalid response, wrong format."; + return absl::nullopt; + } + result.pins.push_back(*val_as_str); } return result; } diff --git a/components/ipfs/ipfs_json_parser_unittest.cc b/components/ipfs/ipfs_json_parser_unittest.cc index 207755364d65..18ca0f3f561e 100644 --- a/components/ipfs/ipfs_json_parser_unittest.cc +++ b/components/ipfs/ipfs_json_parser_unittest.cc @@ -448,6 +448,13 @@ TEST_F(IPFSJSONParserTest, GetRemovePinsResultFromJSONTest) { EXPECT_TRUE(result.value().empty()); } + { + std::string json = R"({"Pins" : [{}, 123]})"; + auto result = IPFSJSONParser::GetRemovePinsResultFromJSON( + base::test::ParseJson(json)); + EXPECT_FALSE(result.has_value()); + } + { std::string json = R"({"Pins" : ["QmA", "QmB"]})"; auto result = IPFSJSONParser::GetRemovePinsResultFromJSON( @@ -492,6 +499,13 @@ TEST_F(IPFSJSONParserTest, GetAddPinsResultFromJSONTest) { EXPECT_EQ(result->progress, -1); } + { + std::string json = R"({"Pins" : [{}, 123]})"; + auto result = + IPFSJSONParser::GetAddPinsResultFromJSON(base::test::ParseJson(json)); + EXPECT_FALSE(result.has_value()); + } + { std::string json = R"({"Pins" : ["QmA", "QmB"], "Progress" : 10})"; auto result = diff --git a/components/ipfs/pin/ipfs_base_pin_service.cc b/components/ipfs/pin/ipfs_base_pin_service.cc index 7f4bed51553d..ea55664b0508 100644 --- a/components/ipfs/pin/ipfs_base_pin_service.cc +++ b/components/ipfs/pin/ipfs_base_pin_service.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -19,14 +19,9 @@ IpfsBasePinService::IpfsBasePinService(IpfsService* ipfs_service) ipfs_service_->AddObserver(this); } -IpfsBasePinService::IpfsBasePinService() {} +IpfsBasePinService::IpfsBasePinService() = default; -IpfsBasePinService::~IpfsBasePinService() {} - -// For unit tests -void IpfsBasePinService::RemovePrefListenersForTests() { - pref_change_registrar_.RemoveAll(); -} +IpfsBasePinService::~IpfsBasePinService() = default; void IpfsBasePinService::OnIpfsShutdown() { daemon_ready_ = false; diff --git a/components/ipfs/pin/ipfs_base_pin_service.h b/components/ipfs/pin/ipfs_base_pin_service.h index a4375fff49da..5037c6abe2b1 100644 --- a/components/ipfs/pin/ipfs_base_pin_service.h +++ b/components/ipfs/pin/ipfs_base_pin_service.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -13,7 +13,6 @@ #include #include "brave/components/ipfs/ipfs_service.h" -#include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" namespace ipfs { @@ -25,6 +24,8 @@ class IpfsBaseJob { virtual void Start() = 0; }; +// Manages a queue of IpfsService-related tasks. +// Launches IPFS daemon if needed. class IpfsBasePinService : public IpfsServiceObserver { public: explicit IpfsBasePinService(IpfsService* service); @@ -37,8 +38,6 @@ class IpfsBasePinService : public IpfsServiceObserver { void OnGetConnectedPeers(bool succes, const std::vector& peers) override; - void RemovePrefListenersForTests(); - protected: // For testing IpfsBasePinService(); @@ -51,7 +50,6 @@ class IpfsBasePinService : public IpfsServiceObserver { bool daemon_ready_ = false; raw_ptr ipfs_service_; - PrefChangeRegistrar pref_change_registrar_; std::unique_ptr current_job_; std::queue> jobs_; diff --git a/components/ipfs/pin/ipfs_base_pin_service_unittest.cc b/components/ipfs/pin/ipfs_base_pin_service_unittest.cc index f95cef81e9e2..8814bb08bb2c 100644 --- a/components/ipfs/pin/ipfs_base_pin_service_unittest.cc +++ b/components/ipfs/pin/ipfs_base_pin_service_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -45,10 +45,6 @@ class IpfsBasePinServiceTest : public testing::Test { std::make_unique(GetIpfsService()); } - void TearDown() override { - ipfs_base_pin_service_->RemovePrefListenersForTests(); - } - testing::NiceMock* GetIpfsService() { return &ipfs_service_; } diff --git a/components/ipfs/pin/ipfs_local_pin_service.cc b/components/ipfs/pin/ipfs_local_pin_service.cc index ff55124c1f47..b80cbc8b9ee2 100644 --- a/components/ipfs/pin/ipfs_local_pin_service.cc +++ b/components/ipfs/pin/ipfs_local_pin_service.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -21,16 +21,16 @@ const char kRecursiveMode[] = "recursive"; AddLocalPinJob::AddLocalPinJob(PrefService* prefs_service, IpfsService* ipfs_service, - const std::string& prefix, + const std::string& key, const std::vector& cids, AddPinCallback callback) : prefs_service_(prefs_service), ipfs_service_(ipfs_service), - prefix_(prefix), + key_(key), cids_(cids), callback_(std::move(callback)) {} -AddLocalPinJob::~AddLocalPinJob() {} +AddLocalPinJob::~AddLocalPinJob() = default; void AddLocalPinJob::Start() { ipfs_service_->AddPin(cids_, true, @@ -57,21 +57,21 @@ void AddLocalPinJob::OnAddPinResult(absl::optional result) { for (const auto& cid : cids_) { base::Value::List* list = update_dict.EnsureList(cid); - list->EraseValue(base::Value(prefix_)); - list->Append(base::Value(prefix_)); + list->EraseValue(base::Value(key_)); + list->Append(base::Value(key_)); } } std::move(callback_).Run(true); } RemoveLocalPinJob::RemoveLocalPinJob(PrefService* prefs_service, - const std::string& prefix, + const std::string& key, RemovePinCallback callback) : prefs_service_(prefs_service), - prefix_(prefix), + key_(key), callback_(std::move(callback)) {} -RemoveLocalPinJob::~RemoveLocalPinJob() {} +RemoveLocalPinJob::~RemoveLocalPinJob() = default; void RemoveLocalPinJob::Start() { { @@ -82,7 +82,7 @@ void RemoveLocalPinJob::Start() { for (auto pair : update_dict) { base::Value::List* list = pair.second.GetIfList(); if (list) { - list->EraseValue(base::Value(prefix_)); + list->EraseValue(base::Value(key_)); if (list->empty()) { remove_list.push_back(pair.first); } @@ -97,16 +97,16 @@ void RemoveLocalPinJob::Start() { VerifyLocalPinJob::VerifyLocalPinJob(PrefService* prefs_service, IpfsService* ipfs_service, - const std::string& prefix, + const std::string& key, const std::vector& cids, ValidatePinsCallback callback) : prefs_service_(prefs_service), ipfs_service_(ipfs_service), - prefix_(prefix), + key_(key), cids_(cids), callback_(std::move(callback)) {} -VerifyLocalPinJob::~VerifyLocalPinJob() {} +VerifyLocalPinJob::~VerifyLocalPinJob() = default; void VerifyLocalPinJob::Start() { ipfs_service_->GetPins(absl::nullopt, kRecursiveMode, true, @@ -129,11 +129,11 @@ void VerifyLocalPinJob::OnGetPinsResult(absl::optional result) { verification_passed = false; } else { if (result->find(cid) != result->end()) { - list->EraseValue(base::Value(prefix_)); - list->Append(base::Value(prefix_)); + list->EraseValue(base::Value(key_)); + list->Append(base::Value(key_)); } else { verification_passed = false; - list->EraseValue(base::Value(prefix_)); + list->EraseValue(base::Value(key_)); } if (list->empty()) { update_dict.Remove(cid); @@ -149,7 +149,8 @@ GcJob::GcJob(PrefService* prefs_service, : prefs_service_(prefs_service), ipfs_service_(ipfs_service), callback_(std::move(callback)) {} -GcJob::~GcJob() {} + +GcJob::~GcJob() = default; void GcJob::Start() { ipfs_service_->GetPins( @@ -195,37 +196,37 @@ IpfsLocalPinService::IpfsLocalPinService(PrefService* prefs_service, base::Minutes(1)); } -IpfsLocalPinService::IpfsLocalPinService() {} +IpfsLocalPinService::IpfsLocalPinService() = default; void IpfsLocalPinService::SetIpfsBasePinServiceForTesting( std::unique_ptr service) { ipfs_base_pin_service_ = std::move(service); } -IpfsLocalPinService::~IpfsLocalPinService() {} +IpfsLocalPinService::~IpfsLocalPinService() = default; -void IpfsLocalPinService::AddPins(const std::string& prefix, +void IpfsLocalPinService::AddPins(const std::string& key, const std::vector& cids, AddPinCallback callback) { ipfs_base_pin_service_->AddJob(std::make_unique( - prefs_service_, ipfs_service_, prefix, cids, + prefs_service_, ipfs_service_, key, cids, base::BindOnce(&IpfsLocalPinService::OnAddJobFinished, weak_ptr_factory_.GetWeakPtr(), std::move(callback)))); } -void IpfsLocalPinService::RemovePins(const std::string& prefix, +void IpfsLocalPinService::RemovePins(const std::string& key, RemovePinCallback callback) { ipfs_base_pin_service_->AddJob(std::make_unique( - prefs_service_, prefix, + prefs_service_, key, base::BindOnce(&IpfsLocalPinService::OnRemovePinsFinished, weak_ptr_factory_.GetWeakPtr(), std::move(callback)))); } -void IpfsLocalPinService::ValidatePins(const std::string& prefix, +void IpfsLocalPinService::ValidatePins(const std::string& key, const std::vector& cids, ValidatePinsCallback callback) { ipfs_base_pin_service_->AddJob(std::make_unique( - prefs_service_, ipfs_service_, prefix, cids, + prefs_service_, ipfs_service_, key, cids, base::BindOnce(&IpfsLocalPinService::OnValidateJobFinished, weak_ptr_factory_.GetWeakPtr(), std::move(callback)))); } diff --git a/components/ipfs/pin/ipfs_local_pin_service.h b/components/ipfs/pin/ipfs_local_pin_service.h index afcd8196f111..9f80a94a5def 100644 --- a/components/ipfs/pin/ipfs_local_pin_service.h +++ b/components/ipfs/pin/ipfs_local_pin_service.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. @@ -23,11 +23,28 @@ using RemovePinCallback = base::OnceCallback; using ValidatePinsCallback = base::OnceCallback)>; using GcCallback = base::OnceCallback; +/** + * Pins provided cids and writes record to kIPFSPinnedCids: + * { + * // List of all pinned CIDs + * "Qme1": [ + * // List of tokens that contain this CID + * "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1" + * "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2" + * ], + * "Qme2": [ + * "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x1" + * ], + * "Qme3": [ + * "nft.local.60.0x1.0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d.0x2" + * ] + * } + */ class AddLocalPinJob : public IpfsBaseJob { public: AddLocalPinJob(PrefService* prefs_service, IpfsService* ipfs_service, - const std::string& prefix, + const std::string& key, const std::vector& cids, AddPinCallback callback); ~AddLocalPinJob() override; @@ -39,16 +56,17 @@ class AddLocalPinJob : public IpfsBaseJob { raw_ptr prefs_service_; raw_ptr ipfs_service_; - std::string prefix_; + std::string key_; std::vector cids_; AddPinCallback callback_; base::WeakPtrFactory weak_ptr_factory_{this}; }; +// Removes records related to the key and launches GC task. class RemoveLocalPinJob : public IpfsBaseJob { public: RemoveLocalPinJob(PrefService* prefs_service, - const std::string& prefix, + const std::string& key, RemovePinCallback callback); ~RemoveLocalPinJob() override; @@ -56,16 +74,17 @@ class RemoveLocalPinJob : public IpfsBaseJob { private: raw_ptr prefs_service_; - std::string prefix_; + std::string key_; RemovePinCallback callback_; base::WeakPtrFactory weak_ptr_factory_{this}; }; +// Verifies that cids are actually pinned class VerifyLocalPinJob : public IpfsBaseJob { public: VerifyLocalPinJob(PrefService* prefs_service, IpfsService* ipfs_service, - const std::string& prefix, + const std::string& key, const std::vector& cids, ValidatePinsCallback callback); ~VerifyLocalPinJob() override; @@ -77,12 +96,13 @@ class VerifyLocalPinJob : public IpfsBaseJob { raw_ptr prefs_service_; raw_ptr ipfs_service_; - std::string prefix_; + std::string key_; std::vector cids_; ValidatePinsCallback callback_; base::WeakPtrFactory weak_ptr_factory_{this}; }; +// Unpins cids that don't have kIPFSPinnedCids record class GcJob : public IpfsBaseJob { public: GcJob(PrefService* prefs_service, @@ -109,12 +129,14 @@ class IpfsLocalPinService : public KeyedService { IpfsLocalPinService(); ~IpfsLocalPinService() override; - virtual void AddPins(const std::string& prefix, + // Pins provided cids and stores related record in the prefs. + virtual void AddPins(const std::string& key, const std::vector& cids, AddPinCallback callback); - virtual void RemovePins(const std::string& prefix, - RemovePinCallback callback); - virtual void ValidatePins(const std::string& prefix, + // Unpins all cids related to the key. + virtual void RemovePins(const std::string& key, RemovePinCallback callback); + // Checks that all cids related to the key are pinned. + virtual void ValidatePins(const std::string& key, const std::vector& cids, ValidatePinsCallback callback); diff --git a/components/ipfs/pin/ipfs_local_pin_service_unittest.cc b/components/ipfs/pin/ipfs_local_pin_service_unittest.cc index ecda844f28e5..76c0c9d11f8b 100644 --- a/components/ipfs/pin/ipfs_local_pin_service_unittest.cc +++ b/components/ipfs/pin/ipfs_local_pin_service_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. diff --git a/components/ipfs/pin/ipfs_pin_rpc_types.cc b/components/ipfs/pin/ipfs_pin_rpc_types.cc index c09cea3c9db3..0a4deca1c27d 100644 --- a/components/ipfs/pin/ipfs_pin_rpc_types.cc +++ b/components/ipfs/pin/ipfs_pin_rpc_types.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. diff --git a/components/ipfs/pin/ipfs_pin_rpc_types.h b/components/ipfs/pin/ipfs_pin_rpc_types.h index 263dd7214ce4..ba0b9c732886 100644 --- a/components/ipfs/pin/ipfs_pin_rpc_types.h +++ b/components/ipfs/pin/ipfs_pin_rpc_types.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/.