From 2a54da59218b6ae347871966a0c271816f56337d Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Tue, 14 Jul 2020 09:08:05 +0200 Subject: [PATCH 1/4] Unify file names --- vendor/bat-native-ledger/BUILD.gn | 12 +++---- .../internal/contribution/contribution.cc | 4 +-- .../src/bat/ledger/internal/wallet/wallet.cc | 12 +++---- .../src/bat/ledger/internal/wallet/wallet.h | 6 ++-- .../wallet/{balance.cc => wallet_balance.cc} | 32 +++++++++---------- .../wallet/{balance.h => wallet_balance.h} | 13 ++++---- .../wallet/{create.cc => wallet_create.cc} | 16 +++++----- .../wallet/{create.h => wallet_create.h} | 13 ++++---- .../wallet/{recover.cc => wallet_recover.cc} | 23 +++++++------ .../wallet/{recover.h => wallet_recover.h} | 13 ++++---- 10 files changed, 70 insertions(+), 74 deletions(-) rename vendor/bat-native-ledger/src/bat/ledger/internal/wallet/{balance.cc => wallet_balance.cc} (84%) rename vendor/bat-native-ledger/src/bat/ledger/internal/wallet/{balance.h => wallet_balance.h} (86%) rename vendor/bat-native-ledger/src/bat/ledger/internal/wallet/{create.cc => wallet_create.cc} (94%) rename vendor/bat-native-ledger/src/bat/ledger/internal/wallet/{create.h => wallet_create.h} (80%) rename vendor/bat-native-ledger/src/bat/ledger/internal/wallet/{recover.cc => wallet_recover.cc} (89%) rename vendor/bat-native-ledger/src/bat/ledger/internal/wallet/{recover.h => wallet_recover.h} (85%) diff --git a/vendor/bat-native-ledger/BUILD.gn b/vendor/bat-native-ledger/BUILD.gn index 7d541089ab08..2d952ff230cd 100644 --- a/vendor/bat-native-ledger/BUILD.gn +++ b/vendor/bat-native-ledger/BUILD.gn @@ -389,14 +389,14 @@ source_set("ledger") { "src/bat/ledger/internal/uphold/uphold_util.cc", "src/bat/ledger/internal/uphold/uphold_wallet.h", "src/bat/ledger/internal/uphold/uphold_wallet.cc", - "src/bat/ledger/internal/wallet/balance.h", - "src/bat/ledger/internal/wallet/balance.cc", - "src/bat/ledger/internal/wallet/create.h", - "src/bat/ledger/internal/wallet/create.cc", - "src/bat/ledger/internal/wallet/recover.h", - "src/bat/ledger/internal/wallet/recover.cc", "src/bat/ledger/internal/wallet/wallet.h", "src/bat/ledger/internal/wallet/wallet.cc", + "src/bat/ledger/internal/wallet/wallet_balance.h", + "src/bat/ledger/internal/wallet/wallet_balance.cc", + "src/bat/ledger/internal/wallet/wallet_create.h", + "src/bat/ledger/internal/wallet/wallet_create.cc", + "src/bat/ledger/internal/wallet/wallet_recover.h", + "src/bat/ledger/internal/wallet/wallet_recover.cc", "src/bat/ledger/internal/wallet/wallet_util.h", "src/bat/ledger/internal/wallet/wallet_util.cc", "src/bat/ledger/internal/media/github.h", diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc index 6e44200cddc3..232b61adea3b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc @@ -28,7 +28,7 @@ #include "bat/ledger/internal/contribution/unverified.h" #include "bat/ledger/internal/state/state_util.h" #include "bat/ledger/internal/uphold/uphold.h" -#include "bat/ledger/internal/wallet/balance.h" +#include "bat/ledger/internal/wallet/wallet_balance.h" #include "bat/ledger/internal/ledger_impl.h" #include "brave_base/random.h" @@ -360,7 +360,7 @@ void Contribution::CreateNewEntry( } const double wallet_balance = - braveledger_wallet::Balance::GetPerWalletBalance( + braveledger_wallet::WalletBalance::GetPerWalletBalance( wallet_type, balance->wallets); if (wallet_balance == 0) { diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc index 2b0cd264bcd0..b9b493e20b75 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc @@ -24,9 +24,9 @@ #include "bat/ledger/internal/state/state_util.h" #include "bat/ledger/internal/uphold/uphold.h" #include "bat/ledger/internal/uphold/uphold_util.h" -#include "bat/ledger/internal/wallet/balance.h" -#include "bat/ledger/internal/wallet/create.h" -#include "bat/ledger/internal/wallet/recover.h" +#include "bat/ledger/internal/wallet/wallet_balance.h" +#include "bat/ledger/internal/wallet/wallet_create.h" +#include "bat/ledger/internal/wallet/wallet_recover.h" #include "bat/ledger/internal/wallet/wallet_util.h" #include "wally_bip39.h" // NOLINT @@ -39,9 +39,9 @@ namespace braveledger_wallet { Wallet::Wallet(bat_ledger::LedgerImpl* ledger) : ledger_(ledger), - create_(std::make_unique(ledger)), - recover_(std::make_unique(ledger)), - balance_(std::make_unique(ledger)), + create_(std::make_unique(ledger)), + recover_(std::make_unique(ledger)), + balance_(std::make_unique(ledger)), uphold_(std::make_unique(ledger)) { } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h index 426ab0186cfb..001537bc208b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h @@ -95,9 +95,9 @@ class Wallet { ledger::ResultCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED - std::unique_ptr create_; - std::unique_ptr recover_; - std::unique_ptr balance_; + std::unique_ptr create_; + std::unique_ptr recover_; + std::unique_ptr balance_; std::unique_ptr uphold_; }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc similarity index 84% rename from vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc rename to vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc index 9538220a1f11..15332f7f0503 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc @@ -3,7 +3,7 @@ * 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 "bat/ledger/internal/wallet/balance.h" +#include "bat/ledger/internal/wallet/wallet_balance.h" #include #include @@ -26,19 +26,19 @@ using std::placeholders::_3; namespace braveledger_wallet { -Balance::Balance(bat_ledger::LedgerImpl* ledger) : +WalletBalance::WalletBalance(bat_ledger::LedgerImpl* ledger) : uphold_(std::make_unique(ledger)), ledger_(ledger) { } -Balance::~Balance() { +WalletBalance::~WalletBalance() { } -void Balance::Fetch(ledger::FetchBalanceCallback callback) { +void WalletBalance::Fetch(ledger::FetchBalanceCallback callback) { // if we don't have user funds in anon card anymore // we can skip balance server ping if (!braveledger_state::GetFetchOldBalanceEnabled(ledger_)) { - auto balance = ledger::Balance::New(); + auto balance = ledger::WalletBalance::New(); balance->user_funds = "0"; GetUnblindedTokens(std::move(balance), callback); return; @@ -53,14 +53,14 @@ void Balance::Fetch(ledger::FetchBalanceCallback callback) { path, PREFIX_V2, braveledger_request_util::ServerTypes::BALANCE); - auto load_callback = std::bind(&Balance::OnFetch, + auto load_callback = std::bind(&WalletBalance::OnFetch, this, _1, callback); ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, load_callback); } -void Balance::OnFetch( +void WalletBalance::OnFetch( const ledger::UrlResponse& response, ledger::FetchBalanceCallback callback) { BLOG(6, ledger::UrlResponseToString(__func__, response)); @@ -83,7 +83,7 @@ void Balance::OnFetch( GetUnblindedTokens(std::move(balance), callback); } -void Balance::GetUnblindedTokens( +void WalletBalance::GetUnblindedTokens( ledger::BalancePtr balance, ledger::FetchBalanceCallback callback) { if (!balance) { @@ -92,7 +92,7 @@ void Balance::GetUnblindedTokens( return; } - auto tokens_callback = std::bind(&Balance::OnGetUnblindedTokens, + auto tokens_callback = std::bind(&WalletBalance::OnGetUnblindedTokens, this, *balance, callback, @@ -102,11 +102,11 @@ void Balance::GetUnblindedTokens( tokens_callback); } -void Balance::OnGetUnblindedTokens( +void WalletBalance::OnGetUnblindedTokens( ledger::Balance info, ledger::FetchBalanceCallback callback, ledger::UnblindedTokenList list) { - auto info_ptr = ledger::Balance::New(info); + auto info_ptr = ledger::WalletBalance::New(info); double total = 0.0; for (auto & item : list) { total+=item->value; @@ -116,7 +116,7 @@ void Balance::OnGetUnblindedTokens( ExternalWallets(std::move(info_ptr), callback); } -void Balance::ExternalWallets( +void WalletBalance::ExternalWallets( ledger::BalancePtr balance, ledger::FetchBalanceCallback callback) { if (!balance) { @@ -132,7 +132,7 @@ void Balance::ExternalWallets( return; } - auto uphold_callback = std::bind(&Balance::OnUpholdFetchBalance, + auto uphold_callback = std::bind(&WalletBalance::OnUpholdFetchBalance, this, *balance, callback, @@ -142,11 +142,11 @@ void Balance::ExternalWallets( uphold_->FetchBalance(uphold_callback); } -void Balance::OnUpholdFetchBalance(ledger::Balance info, +void WalletBalance::OnUpholdFetchBalance(ledger::Balance info, ledger::FetchBalanceCallback callback, ledger::Result result, double balance) { - ledger::BalancePtr info_ptr = ledger::Balance::New(info); + ledger::BalancePtr info_ptr = ledger::WalletBalance::New(info); if (result == ledger::Result::LEDGER_ERROR) { BLOG(0, "Can't get uphold balance"); @@ -160,7 +160,7 @@ void Balance::OnUpholdFetchBalance(ledger::Balance info, } // static -double Balance::GetPerWalletBalance( +double WalletBalance::GetPerWalletBalance( const std::string& type, base::flat_map wallets) { if (type.empty() || wallets.size() == 0) { diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h similarity index 86% rename from vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.h rename to vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h index 725b6cb73b3a..ce6729792e35 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h @@ -3,8 +3,8 @@ * 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 BRAVELEDGER_WALLET_BALANCE_H_ -#define BRAVELEDGER_WALLET_BALANCE_H_ +#ifndef BRAVELEDGER_WALLET_WALLET_BALANCE_H_ +#define BRAVELEDGER_WALLET_WALLET_BALANCE_H_ #include @@ -24,11 +24,10 @@ class Uphold; namespace braveledger_wallet { -class Balance { +class WalletBalance { public: - explicit Balance(bat_ledger::LedgerImpl* ledger); - - ~Balance(); + explicit WalletBalance(bat_ledger::LedgerImpl* ledger); + ~WalletBalance(); void Fetch(ledger::FetchBalanceCallback callback); @@ -64,4 +63,4 @@ class Balance { }; } // namespace braveledger_wallet -#endif // BRAVELEDGER_WALLET_BALANCE_H_ +#endif // BRAVELEDGER_WALLET_WALLET_BALANCE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc similarity index 94% rename from vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc rename to vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc index 940225425610..5729fd37d931 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc @@ -3,7 +3,7 @@ * 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 "bat/ledger/internal/wallet/create.h" +#include "bat/ledger/internal/wallet/wallet_create.h" #include @@ -95,15 +95,15 @@ std::string StringifyRequestCredentials( namespace braveledger_wallet { -Create::Create(bat_ledger::LedgerImpl* ledger) : +WalletCreate::WalletCreate(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { initAnonize(); } -Create::~Create() = default; +WalletCreate::~Create() = default; -void Create::Start(ledger::ResultCallback callback) { - auto req_callback = std::bind(&Create::RequestCredentialsCallback, +void WalletCreate::Start(ledger::ResultCallback callback) { + auto req_callback = std::bind(&WalletCreate::RequestCredentialsCallback, this, _1, std::move(callback)); @@ -114,7 +114,7 @@ void Create::Start(ledger::ResultCallback callback) { ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, req_callback); } -void Create::RequestCredentialsCallback( +void WalletCreate::RequestCredentialsCallback( const ledger::UrlResponse& response, ledger::ResultCallback callback) { BLOG(6, ledger::UrlResponseToString(__func__, response)); @@ -196,7 +196,7 @@ void Create::RequestCredentialsCallback( // We should use simple callbacks on iOS const std::string url = braveledger_request_util::BuildUrl( (std::string)REGISTER_PERSONA + "/" + user_id, PREFIX_V2); - auto on_register = std::bind(&Create::RegisterPersonaCallback, + auto on_register = std::bind(&WalletCreate::RegisterPersonaCallback, this, _1, user_id, @@ -213,7 +213,7 @@ void Create::RequestCredentialsCallback( on_register); } -void Create::RegisterPersonaCallback( +void WalletCreate::RegisterPersonaCallback( const ledger::UrlResponse& response, const std::string& user_id, const std::string& pre_flight, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h similarity index 80% rename from vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.h rename to vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h index bbe6084e0e4b..afffa95f8381 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h @@ -3,8 +3,8 @@ * 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 BRAVELEDGER_WALLET_CREATE_H_ -#define BRAVELEDGER_WALLET_CREATE_H_ +#ifndef BRAVELEDGER_WALLET_WALLET_CREATE_H_ +#define BRAVELEDGER_WALLET_WALLET_CREATE_H_ #include @@ -21,11 +21,10 @@ class LedgerImpl; namespace braveledger_wallet { -class Create { +class WalletCreate { public: - explicit Create(bat_ledger::LedgerImpl* ledger); - - ~Create(); + explicit WalletCreate(bat_ledger::LedgerImpl* ledger); + ~WalletCreate(); void Start(ledger::ResultCallback callback); @@ -45,4 +44,4 @@ class Create { }; } // namespace braveledger_wallet -#endif // BRAVELEDGER_WALLET_CREATE_H_ +#endif // BRAVELEDGER_WALLET_WALLET_CREATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc similarity index 89% rename from vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc rename to vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc index 823984a30b93..c5d39f8e6b59 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc @@ -2,8 +2,7 @@ * 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 "bat/ledger/internal/wallet/recover.h" +#include "bat/ledger/internal/wallet/wallet_recover.h" #include @@ -25,14 +24,14 @@ using std::placeholders::_3; namespace braveledger_wallet { -Recover::Recover(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { +WalletRecover::WalletRecover(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { initAnonize(); } -Recover::~Recover() { +WalletRecover::~WalletRecover() { } -void Recover::Start( +void WalletRecover::Start( const std::string& pass_phrase, ledger::RecoverWalletCallback callback) { if (pass_phrase.empty()) { @@ -50,7 +49,7 @@ void Recover::Start( if (phrase_split.size() == 16) { // use niceware for legacy wallet passphrases - ledger_->LoadNicewareList(std::bind(&Recover::OnNicewareListLoaded, + ledger_->LoadNicewareList(std::bind(&WalletRecover::OnNicewareListLoaded, this, pass_phrase, _1, @@ -70,7 +69,7 @@ void Recover::Start( ContinueRecover(result, &written, newSeed, std::move(callback)); } -void Recover::OnNicewareListLoaded( +void WalletRecover::OnNicewareListLoaded( const std::string& pass_phrase, ledger::Result result, const std::string& data, @@ -106,7 +105,7 @@ void Recover::OnNicewareListLoaded( return; } -void Recover::ContinueRecover( +void WalletRecover::ContinueRecover( int result, size_t* written, const std::vector& newSeed, @@ -125,7 +124,7 @@ void Recover::ContinueRecover( &newSecretKey); std::string publicKeyHex = braveledger_bat_helper::uint8ToHex(publicKey); - auto on_load = std::bind(&Recover::RecoverWalletPublicKeyCallback, + auto on_load = std::bind(&WalletRecover::RecoverWalletPublicKeyCallback, this, _1, newSeed, @@ -136,7 +135,7 @@ void Recover::ContinueRecover( ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, std::move(on_load)); } -void Recover::RecoverWalletPublicKeyCallback( +void WalletRecover::RecoverWalletPublicKeyCallback( const ledger::UrlResponse& response, const std::vector& new_seed, ledger::RecoverWalletCallback callback) { @@ -150,7 +149,7 @@ void Recover::RecoverWalletPublicKeyCallback( return; } - auto recover_callback = std::bind(&Recover::RecoverWalletCallback, + auto recover_callback = std::bind(&WalletRecover::RecoverWalletCallback, this, _1, recovery_id, @@ -161,7 +160,7 @@ void Recover::RecoverWalletPublicKeyCallback( ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, recover_callback); } -void Recover::RecoverWalletCallback( +void WalletRecover::RecoverWalletCallback( const ledger::UrlResponse& response, const std::string& recovery_id, const std::vector& new_seed, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h similarity index 85% rename from vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.h rename to vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h index 5c2f78b63cc3..6ddef2370f32 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h @@ -3,8 +3,8 @@ * 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 BRAVELEDGER_WALLET_RECOVER_H_ -#define BRAVELEDGER_WALLET_RECOVER_H_ +#ifndef BRAVELEDGER_WALLET_WALLET_RECOVER_H_ +#define BRAVELEDGER_WALLET_WALLET_RECOVER_H_ #include @@ -21,11 +21,10 @@ class LedgerImpl; namespace braveledger_wallet { -class Recover { +class WalletRecover { public: - explicit Recover(bat_ledger::LedgerImpl* ledger); - - ~Recover(); + explicit WalletRecover(bat_ledger::LedgerImpl* ledger); + ~WalletRecover(); void Start( const std::string& pass_phrase, @@ -60,4 +59,4 @@ class Recover { }; } // namespace braveledger_wallet -#endif // BRAVELEDGER_WALLET_RECOVER_H_ +#endif // BRAVELEDGER_WALLET_WALLET_RECOVER_H_ From a4cbc1be6eb680c3c6b60f1b2da22a6082c7a1c9 Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Wed, 15 Jul 2020 13:58:53 +0200 Subject: [PATCH 2/4] Implements new persona api Resolves https://github.com/brave/brave-browser/issues/8428 --- .../android/brave_rewards_native_worker.cc | 3 +- .../android/brave_rewards_native_worker.h | 6 +- browser/ui/webui/brave_rewards_page_ui.cc | 25 +- browser/ui/webui/brave_webui_source.cc | 1 + .../browser/ads_service_browsertest.cc | 44 +- .../brave_rewards/browser/rewards_service.cc | 1 - .../browser/rewards_service_impl.cc | 40 +- .../browser/rewards_service_impl.h | 6 +- .../browser/rewards_service_impl_unittest.cc | 4 +- .../browser/rewards_service_observer.h | 3 +- .../rewards_browsertest_contribution.cc | 1 - .../common/rewards_browsertest_response.cc | 40 +- .../common/rewards_browsertest_response.h | 4 +- .../browser/test/rewards_state_browsertest.cc | 3 - components/brave_rewards/common/pref_names.cc | 1 - components/brave_rewards/common/pref_names.h | 1 - .../android_page/reducers/rewards_reducer.ts | 2 +- .../resources/android_page/storage.ts | 2 +- .../brave_rewards_static_resources.grd | 1 - .../resources/page/actions/rewards_actions.ts | 4 +- .../resources/page/brave_rewards_page.tsx | 4 +- .../resources/page/components/pageWallet.tsx | 34 +- .../page/reducers/rewards_reducer.ts | 4 +- .../resources/page/reducers/wallet_reducer.ts | 14 +- .../brave_rewards/resources/page/storage.ts | 2 +- .../resources/ui/components/alert/style.ts | 4 + components/brave_rewards/test/BUILD.gn | 2 - components/definitions/global.d.ts | 2 +- components/definitions/rewards.d.ts | 2 +- .../resources/brave_components_strings.grd | 3 +- .../bat_ledger_client_mojo_bridge.cc | 18 - .../bat_ledger_client_mojo_bridge.h | 2 - .../services/bat_ledger/bat_ledger_impl.cc | 8 +- .../services/bat_ledger/bat_ledger_impl.h | 3 +- .../public/cpp/ledger_client_mojo_bridge.cc | 21 - .../public/cpp/ledger_client_mojo_bridge.h | 7 - .../public/interfaces/bat_ledger.mojom | 4 +- .../page/reducers/rewards_reducer_test.ts | 4 +- .../page/reducers/wallet_reducer_test.ts | 18 +- .../rewards-data/register_persona_resp.json | 18 - .../rewards-data/uphold_addresses_resp.json | 11 + .../rewards-data/verify_persona_resp.json | 28 - test/data/rewards-data/wallet_resp.json | 9 + .../internal/confirmations_client_mock.h | 7 - vendor/bat-native-ledger/BUILD.gn | 7 +- .../include/bat/ledger/ledger.h | 6 +- .../include/bat/ledger/ledger_client.h | 4 - .../bat/ledger/public/interfaces/ledger.mojom | 1 - vendor/bat-native-ledger/niceware/wordlist | 1 - .../attestation/attestation_androidx.cc | 3 +- .../attestation/attestation_desktop.cc | 3 +- .../internal/attestation/attestation_iosx.cc | 3 +- .../src/bat/ledger/internal/bat_helper.cc | 94 --- .../src/bat/ledger/internal/bat_helper.h | 16 - .../ledger/internal/common/security_helper.cc | 125 +++- .../ledger/internal/common/security_helper.h | 17 + .../contribution/contribution_anon_card.cc | 2 +- .../credentials/credentials_promotion.cc | 8 +- .../bat/ledger/internal/ledger_client_mock.h | 3 - .../src/bat/ledger/internal/ledger_impl.cc | 53 +- .../src/bat/ledger/internal/ledger_impl.h | 17 +- .../bat/ledger/internal/ledger_impl_mock.h | 14 +- .../internal/legacy/unsigned_tx_properties.cc | 33 - .../internal/legacy/unsigned_tx_properties.h | 32 - .../internal/legacy/unsigned_tx_state.cc | 178 ------ .../internal/legacy/unsigned_tx_state.h | 49 -- .../legacy/unsigned_tx_state_unittest.cc | 84 --- .../ledger/internal/promotion/promotion.cc | 4 +- .../internal/promotion/promotion_transfer.cc | 31 +- .../internal/promotion/promotion_transfer.h | 6 - .../internal/promotion/promotion_unittest.cc | 3 +- .../recovery/recovery_empty_balance.cc | 2 +- .../internal/request/request_promotion.cc | 18 + .../internal/request/request_promotion.h | 6 + .../ledger/internal/request/request_util.cc | 15 +- .../ledger/internal/request/request_util.h | 4 +- .../internal/response/response_wallet.cc | 567 +++++------------- .../internal/response/response_wallet.h | 18 +- .../bat/ledger/internal/state/state_keys.h | 1 - .../internal/state/state_migration_v2.cc | 4 - .../bat/ledger/internal/state/state_util.cc | 12 - .../bat/ledger/internal/state/state_util.h | 6 - .../src/bat/ledger/internal/static_values.h | 38 -- .../test/niceware_partial_unittest.cc | 204 ------- .../src/bat/ledger/internal/uphold/uphold.cc | 28 +- .../src/bat/ledger/internal/uphold/uphold.h | 8 +- .../ledger/internal/uphold/uphold_wallet.cc | 26 +- .../ledger/internal/uphold/uphold_wallet.h | 6 +- .../src/bat/ledger/internal/wallet/wallet.cc | 298 ++------- .../src/bat/ledger/internal/wallet/wallet.h | 54 +- .../ledger/internal/wallet/wallet_balance.cc | 8 +- .../ledger/internal/wallet/wallet_balance.h | 9 +- .../ledger/internal/wallet/wallet_claim.cc | 210 +++++++ .../bat/ledger/internal/wallet/wallet_claim.h | 48 ++ .../ledger/internal/wallet/wallet_create.cc | 258 ++------ .../ledger/internal/wallet/wallet_create.h | 12 +- .../ledger/internal/wallet/wallet_recover.cc | 159 ++--- .../ledger/internal/wallet/wallet_recover.h | 27 +- .../internal/wallet/wallet_util_unittest.cc | 1 - vendor/brave-ios/BUILD.gn | 2 - vendor/brave-ios/Ledger/BATBraveLedger.mm | 15 +- .../Ledger/Generated/NativeLedgerClient.h | 1 - .../Ledger/Generated/NativeLedgerClient.mm | 3 - .../Generated/NativeLedgerClientBridge.h | 1 - .../BATExternalWallet+DictionaryValue.mm | 8 +- 105 files changed, 939 insertions(+), 2356 deletions(-) delete mode 100644 test/data/rewards-data/register_persona_resp.json create mode 100644 test/data/rewards-data/uphold_addresses_resp.json delete mode 100644 test/data/rewards-data/verify_persona_resp.json create mode 100644 test/data/rewards-data/wallet_resp.json delete mode 100644 vendor/bat-native-ledger/niceware/wordlist delete mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.cc delete mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.h delete mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.cc delete mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.h delete mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state_unittest.cc delete mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/test/niceware_partial_unittest.cc create mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc create mode 100644 vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h diff --git a/browser/brave_rewards/android/brave_rewards_native_worker.cc b/browser/brave_rewards/android/brave_rewards_native_worker.cc index 74fd096c4140..958f317e4c34 100644 --- a/browser/brave_rewards/android/brave_rewards_native_worker.cc +++ b/browser/brave_rewards/android/brave_rewards_native_worker.cc @@ -782,8 +782,7 @@ void BraveRewardsNativeWorker::RecoverWallet( void BraveRewardsNativeWorker::OnRecoverWallet( brave_rewards::RewardsService* rewards_service, - unsigned int result, - double balance) { + const int32_t result) { JNIEnv* env = base::android::AttachCurrentThread(); Java_BraveRewardsNativeWorker_OnRecoverWallet( env, weak_java_brave_rewards_native_worker_.get(env), result); diff --git a/browser/brave_rewards/android/brave_rewards_native_worker.h b/browser/brave_rewards/android/brave_rewards_native_worker.h index f9d456b0b16c..8f472dd8cde8 100644 --- a/browser/brave_rewards/android/brave_rewards_native_worker.h +++ b/browser/brave_rewards/android/brave_rewards_native_worker.h @@ -259,9 +259,9 @@ class BraveRewardsNativeWorker : public brave_rewards::RewardsServiceObserver, const std::string& wallet_type, const std::string& action, const std::map& args); - void OnRecoverWallet(brave_rewards::RewardsService* rewards_service, - unsigned int result, - double balance) override; + void OnRecoverWallet( + brave_rewards::RewardsService* rewards_service, + const int32_t result) override; private: std::string StdStrStrMapToJsonString( diff --git a/browser/ui/webui/brave_rewards_page_ui.cc b/browser/ui/webui/brave_rewards_page_ui.cc index 72a8c6f4f306..86aa6a92f729 100644 --- a/browser/ui/webui/brave_rewards_page_ui.cc +++ b/browser/ui/webui/brave_rewards_page_ui.cc @@ -217,9 +217,9 @@ class RewardsDOMHandler : public WebUIMessageHandler, brave_rewards::RewardsService* rewards_service, const uint32_t result, brave_rewards::Promotion promotion) override; - void OnRecoverWallet(brave_rewards::RewardsService* rewards_service, - unsigned int result, - double balance) override; + void OnRecoverWallet( + brave_rewards::RewardsService* rewards_service, + const int32_t result) override; void OnExcludedSitesChanged(brave_rewards::RewardsService* rewards_service, std::string publisher_id, bool excluded) override; @@ -754,23 +754,20 @@ void RewardsDOMHandler::GetWalletPassphrase(const base::ListValue* args) { void RewardsDOMHandler::RecoverWallet(const base::ListValue *args) { CHECK_EQ(1U, args->GetSize()); if (rewards_service_) { - const std::string passPhrase = args->GetList()[0].GetString(); - rewards_service_->RecoverWallet(passPhrase); + const std::string pass_phrase = args->GetList()[0].GetString(); + rewards_service_->RecoverWallet(pass_phrase); } } void RewardsDOMHandler::OnRecoverWallet( brave_rewards::RewardsService* rewards_service, - unsigned int result, - double balance) { - if (web_ui()->CanCallJavascript()) { - base::DictionaryValue recover; - recover.SetInteger("result", result); - recover.SetDouble("balance", balance); - - web_ui()->CallJavascriptFunctionUnsafe( - "brave_rewards.recoverWalletData", recover); + const int32_t result) { + if (!web_ui()->CanCallJavascript()) { + return; } + + web_ui()->CallJavascriptFunctionUnsafe( + "brave_rewards.recoverWalletData", base::Value(result)); } void RewardsDOMHandler::OnGetReconcileStamp(uint64_t reconcile_stamp) { diff --git a/browser/ui/webui/brave_webui_source.cc b/browser/ui/webui/brave_webui_source.cc index 04c299f5627c..3f6d503c3690 100644 --- a/browser/ui/webui/brave_webui_source.cc +++ b/browser/ui/webui/brave_webui_source.cc @@ -445,6 +445,7 @@ void CustomizeWebUIHTMLSource(const std::string &name, { "walletRecoverySuccess", IDS_BRAVE_REWARDS_LOCAL_WALLET_RECOVERY_SUCCESS }, // NOLINT { "walletRestored", IDS_BRAVE_REWARDS_LOCAL_WALLET_RESTORED }, { "walletRecoveryFail", IDS_BRAVE_REWARDS_LOCAL_WALLET_RECOVERY_FAIL }, // NOLINT + { "walletRecoveryOutdated", IDS_BRAVE_REWARDS_LOCAL_WALLET_RECOVERY_OUTDATED }, // NOLINT { "almostThere", IDS_BRAVE_REWARDS_LOCAL_ALMOST_THERE }, { "notQuite", IDS_BRAVE_REWARDS_LOCAL_NOT_QUITE }, { "proveHuman", IDS_BRAVE_REWARDS_LOCAL_PROVE_HUMAN }, diff --git a/components/brave_ads/browser/ads_service_browsertest.cc b/components/brave_ads/browser/ads_service_browsertest.cc index bb2ed370da76..517491b40445 100644 --- a/components/brave_ads/browser/ads_service_browsertest.cc +++ b/components/brave_ads/browser/ads_service_browsertest.cc @@ -180,37 +180,28 @@ class BraveAdsBrowserTest base::FilePath path; GetTestDataDir(&path); ASSERT_TRUE( - base::ReadFileToString(path.AppendASCII("register_persona_resp.json"), - ®istrarVK_)); - ASSERT_TRUE( - base::ReadFileToString(path.AppendASCII("verify_persona_resp.json"), - &verification_)); + base::ReadFileToString(path.AppendASCII("wallet_resp.json"), + &wallet_)); ASSERT_TRUE( base::ReadFileToString(path.AppendASCII("parameters_resp.json"), ¶meters_)); } - void GetTestResponse(const std::string& url, - int32_t method, - int* response_status_code, - std::string* response, - std::map* headers) { - std::vector tmp = base::SplitString( - url, - "/", - base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL); - const std::string persona_url = - braveledger_request_util::BuildUrl(REGISTER_PERSONA, PREFIX_V2); - if (url.find(persona_url) == 0 && tmp.size() == 6) { - *response = registrarVK_; - } else if (URLMatches(url, REGISTER_PERSONA, PREFIX_V2, - ServerTypes::LEDGER) && - tmp.size() == 7) { - *response = verification_; - } else if (URLMatches(url, "/wallet/", PREFIX_V2, - ServerTypes::BALANCE)) { + void GetTestResponse( + const std::string& url, + int32_t method, + int* response_status_code, + std::string* response, + std::map* headers) { + if (url.find("/v3/wallet/brave") != std::string::npos) { + *response = wallet_; + *response_status_code = net::HTTP_CREATED; + return; + } + + if (URLMatches(url, "/wallet/", PREFIX_V2, ServerTypes::BALANCE)) { *response = parameters_; + return; } } @@ -520,8 +511,7 @@ class BraveAdsBrowserTest std::unique_ptr brave_ads_have_arrived_notification_run_loop_; bool brave_ads_have_arrived_notification_was_already_shown_ = false; - std::string registrarVK_; - std::string verification_; + std::string wallet_; std::string parameters_; }; diff --git a/components/brave_rewards/browser/rewards_service.cc b/components/brave_rewards/browser/rewards_service.cc index e702bb3ef010..443a7c3600f7 100644 --- a/components/brave_rewards/browser/rewards_service.cc +++ b/components/brave_rewards/browser/rewards_service.cc @@ -77,7 +77,6 @@ void RewardsService::RegisterProfilePrefs(PrefRegistrySimple* registry) { registry->RegisterDoublePref(prefs::kStateAutoContributeAmount, 0.0); registry->RegisterUint64Pref(prefs::kStateNextReconcileStamp, 0ull); registry->RegisterUint64Pref(prefs::kStateCreationStamp, 0ull); - registry->RegisterStringPref(prefs::kStateAnonymousCardId, ""); registry->RegisterStringPref(prefs::kStateRecoverySeed, ""); registry->RegisterStringPref(prefs::kStatePaymentId, ""); registry->RegisterBooleanPref(prefs::kStateInlineTipRedditEnabled, false); diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index a30926103abc..65a61a970111 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -927,17 +927,6 @@ void RewardsServiceImpl::GetAutoContributeProperties( callback)); } -void RewardsServiceImpl::OnRecoverWallet( - ledger::Result result, - double balance) { - for (auto& observer : observers_) { - observer.OnRecoverWallet( - this, - static_cast(result), - balance); - } -} - void RewardsServiceImpl::OnReconcileComplete( const ledger::Result result, ledger::ContributionInfoPtr contribution) { @@ -1014,22 +1003,6 @@ void RewardsServiceImpl::OnPublisherStateLoaded( data); } -void RewardsServiceImpl::LoadNicewareList( - ledger::GetNicewareListCallback callback) { - if (!Connected()) { - return; - } - - std::string data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - - if (data.empty()) { - BLOG(0, "Failed to read in niceware list"); - } - callback(data.empty() ? ledger::Result::LEDGER_ERROR - : ledger::Result::LEDGER_OK, data); -} - void RewardsServiceImpl::LoadURL( const std::string& url, const std::vector& headers, @@ -1403,6 +1376,12 @@ void RewardsServiceImpl::RecoverWallet(const std::string& passPhrase) { AsWeakPtr())); } +void RewardsServiceImpl::OnRecoverWallet(const ledger::Result result) { + for (auto& observer : observers_) { + observer.OnRecoverWallet(this, static_cast(result)); + } +} + void RewardsServiceImpl::AttestPromotion( const std::string& promotion_id, const std::string& solution, @@ -2708,7 +2687,6 @@ void RewardsServiceImpl::HandleFlags(const std::string& options) { uphold->status = ledger::WalletStatus::VERIFIED; uphold->one_time_string = ""; uphold->user_name = "Brave Test"; - uphold->transferred = true; SaveExternalWallet(ledger::kWalletUphold, std::move(uphold)); continue; } @@ -3150,7 +3128,6 @@ void RewardsServiceImpl::SaveExternalWallet(const std::string& wallet_type, new_wallet.SetIntKey("status", static_cast(wallet->status)); new_wallet.SetStringKey("one_time_string", wallet->one_time_string); new_wallet.SetStringKey("user_name", wallet->user_name); - new_wallet.SetBoolKey("transferred", wallet->transferred); new_wallet.SetStringKey("verify_url", wallet->verify_url); new_wallet.SetStringKey("add_url", wallet->add_url); new_wallet.SetStringKey("withdraw_url", wallet->withdraw_url); @@ -3200,11 +3177,6 @@ RewardsServiceImpl::GetExternalWallets() { wallet->user_name = *user_name; } - auto transferred = it.second.FindBoolKey("transferred"); - if (transferred) { - wallet->transferred = *transferred; - } - auto* verify_url = it.second.FindStringKey("verify_url"); if (verify_url) { wallet->verify_url = *verify_url; diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index 09318a0fd915..ee71e92b0dee 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -344,7 +344,6 @@ class RewardsServiceImpl : public RewardsService, ledger::Result result); void OnLedgerStateLoaded(ledger::OnLoadCallback callback, std::pair data); - void LoadNicewareList(ledger::GetNicewareListCallback callback) override; void OnPublisherStateLoaded(ledger::OnLoadCallback callback, const std::string& data); void OnGetRewardsParameters( @@ -474,10 +473,9 @@ class RewardsServiceImpl : public RewardsService, GetAnonWalletStatusCallback callback, const ledger::Result result); + void OnRecoverWallet(const ledger::Result result); + // ledger::LedgerClient - void OnRecoverWallet( - ledger::Result result, - double balance); void OnReconcileComplete( const ledger::Result result, ledger::ContributionInfoPtr contribution) override; diff --git a/components/brave_rewards/browser/rewards_service_impl_unittest.cc b/components/brave_rewards/browser/rewards_service_impl_unittest.cc index 4fa9a84db204..9c6a22a3a2a1 100644 --- a/components/brave_rewards/browser/rewards_service_impl_unittest.cc +++ b/components/brave_rewards/browser/rewards_service_impl_unittest.cc @@ -28,9 +28,7 @@ class MockRewardsServiceObserver : public RewardsServiceObserver { MOCK_METHOD3(OnFetchPromotions, void(RewardsService*, const uint32_t, const std::vector& list)); - MOCK_METHOD3(OnRecoverWallet, void(RewardsService*, - unsigned int, - double)); + MOCK_METHOD2(OnRecoverWallet, void(RewardsService*, const int32_t)); MOCK_METHOD3(OnPromotionFinished, void(RewardsService*, const uint32_t, brave_rewards::Promotion)); diff --git a/components/brave_rewards/browser/rewards_service_observer.h b/components/brave_rewards/browser/rewards_service_observer.h index 259d89e9d3a5..3eeb13c52357 100644 --- a/components/brave_rewards/browser/rewards_service_observer.h +++ b/components/brave_rewards/browser/rewards_service_observer.h @@ -34,8 +34,7 @@ class RewardsServiceObserver : public base::CheckedObserver { const std::vector& list) {} virtual void OnRecoverWallet( RewardsService* rewards_service, - unsigned int result, - double balance) {} + const int32_t result) {} virtual void OnPromotionFinished( RewardsService* rewards_service, const uint32_t result, diff --git a/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.cc b/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.cc index 600421914a62..f6612c84c9ab 100644 --- a/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.cc +++ b/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.cc @@ -444,7 +444,6 @@ void RewardsBrowserTestContribution::SetUpUpholdWallet( wallet->status = status; wallet->one_time_string = ""; wallet->user_name = "Brave Test"; - wallet->transferred = true; rewards_service_->SaveExternalWallet("uphold", std::move(wallet)); } diff --git a/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc b/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc index 125b40fc6cbe..f11d1d39ac4e 100644 --- a/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc +++ b/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc @@ -140,12 +140,8 @@ void RewardsBrowserTestResponse::LoadMocks() { base::FilePath path; rewards_browsertest_util::GetTestDataDir(&path); ASSERT_TRUE(base::ReadFileToString( - path.AppendASCII("register_persona_resp.json"), - ®istrar_vk_)); - - ASSERT_TRUE(base::ReadFileToString( - path.AppendASCII("verify_persona_resp.json"), - &verification_)); + path.AppendASCII("wallet_resp.json"), + &wallet_)); ASSERT_TRUE(base::ReadFileToString( path.AppendASCII("promotions_resp.json"), @@ -202,6 +198,10 @@ void RewardsBrowserTestResponse::LoadMocks() { path.AppendASCII("uphold_commit_resp.json"), &uphold_commit_resp_)); + ASSERT_TRUE(base::ReadFileToString( + path.AppendASCII("uphold_addresses_resp.json"), + &uphold_addresses_resp_)); + std::vector publisher_keys { "bumpsmack.com", "duckduckgo.com", @@ -228,24 +228,9 @@ void RewardsBrowserTestResponse::Get( requests_.emplace_back(url, method); DCHECK(response_status_code && response); - std::vector tmp = base::SplitString( - url, - "/", - base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL); - const std::string persona_url = - braveledger_request_util::BuildUrl(REGISTER_PERSONA, PREFIX_V2); - if (url.find(persona_url) == 0 && tmp.size() == 6) { - *response = registrar_vk_; - return; - } - - if (URLMatches( - url, - REGISTER_PERSONA, - PREFIX_V2, - ServerTypes::LEDGER) && tmp.size() == 7) { - *response = verification_; + if (url.find("/v3/wallet/brave") != std::string::npos) { + *response = wallet_; + *response_status_code = net::HTTP_CREATED; return; } @@ -354,7 +339,12 @@ void RewardsBrowserTestResponse::Get( url, "commit", base::CompareCase::INSENSITIVE_ASCII)) { - *response = uphold_commit_resp_; + *response = uphold_commit_resp_; + } else if (base::EndsWith( + url, + "addresses", + base::CompareCase::INSENSITIVE_ASCII)) { + *response = uphold_addresses_resp_; } else { *response = rewards_browsertest_util::GetUpholdCard( external_balance_, diff --git a/components/brave_rewards/browser/test/common/rewards_browsertest_response.h b/components/brave_rewards/browser/test/common/rewards_browsertest_response.h index 0f4551c9ccd0..ec468215b40d 100644 --- a/components/brave_rewards/browser/test/common/rewards_browsertest_response.h +++ b/components/brave_rewards/browser/test/common/rewards_browsertest_response.h @@ -53,8 +53,7 @@ class RewardsBrowserTestResponse { void SetUserFundsBalance(const bool user_funds); private: - std::string registrar_vk_; - std::string verification_; + std::string wallet_; std::string promotions_; std::string promotion_empty_key_; std::string promotion_claim_; @@ -68,6 +67,7 @@ class RewardsBrowserTestResponse { std::string uphold_auth_resp_; std::string uphold_transactions_resp_; std::string uphold_commit_resp_; + std::string uphold_addresses_resp_; std::string user_funds_balance_resp_; std::vector requests_; diff --git a/components/brave_rewards/browser/test/rewards_state_browsertest.cc b/components/brave_rewards/browser/test/rewards_state_browsertest.cc index 45201cd84795..b436344ae7fb 100644 --- a/components/brave_rewards/browser/test/rewards_state_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_state_browsertest.cc @@ -219,9 +219,6 @@ IN_PROC_BROWSER_TEST_F(RewardsStateBrowserTest, State_2) { EXPECT_EQ( profile_->GetPrefs()->GetString("brave.rewards.wallet.seed"), "PgFfhazUJuf8dX+8ckTjrtK1KMLyrfXmKJFDiS1Ad3I="); - EXPECT_EQ( - profile_->GetPrefs()->GetString("brave.rewards.wallet.anonymous_card_id"), - "cf5b388c-eea2-4c98-bec2-f8daf39881a4"); EXPECT_EQ( profile_->GetPrefs()->GetUint64("brave.rewards.creation_stamp"), 1590484778ul); diff --git a/components/brave_rewards/common/pref_names.cc b/components/brave_rewards/common/pref_names.cc index 61ee50e6b1e4..d089c633c15b 100644 --- a/components/brave_rewards/common/pref_names.cc +++ b/components/brave_rewards/common/pref_names.cc @@ -47,7 +47,6 @@ const char kStateAutoContributeEnabled[] = "brave.rewards.ac.enabled"; const char kStateAutoContributeAmount[] = "brave.rewards.ac.amount"; const char kStateNextReconcileStamp[] = "brave.rewards.ac.next_reconcile_stamp"; const char kStateCreationStamp[] = "brave.rewards.creation_stamp"; -const char kStateAnonymousCardId[] = "brave.rewards.wallet.anonymous_card_id"; const char kStateRecoverySeed[] = "brave.rewards.wallet.seed"; const char kStatePaymentId[] = "brave.rewards.wallet.payment_id"; const char kStateInlineTipRedditEnabled[] = "brave.rewards.inline_tip.reddit"; diff --git a/components/brave_rewards/common/pref_names.h b/components/brave_rewards/common/pref_names.h index 03a0243e7810..af6ba6dfe27e 100644 --- a/components/brave_rewards/common/pref_names.h +++ b/components/brave_rewards/common/pref_names.h @@ -39,7 +39,6 @@ extern const char kStateAutoContributeEnabled[]; extern const char kStateAutoContributeAmount[]; extern const char kStateNextReconcileStamp[]; extern const char kStateCreationStamp[]; -extern const char kStateAnonymousCardId[]; extern const char kStateRecoverySeed[]; extern const char kStatePaymentId[]; extern const char kStateInlineTipRedditEnabled[]; diff --git a/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts b/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts index 125407c22ccb..9b074d1dbf39 100644 --- a/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts @@ -72,7 +72,7 @@ const rewardsReducer: Reducer = (state: Rewards.State case types.ON_MODAL_BACKUP_CLOSE: { state = { ...state } let ui = state.ui - ui.walletRecoverySuccess = null + ui.walletRecoveryStatus = null ui.modalBackup = false state = { ...state, diff --git a/components/brave_rewards/resources/android_page/storage.ts b/components/brave_rewards/resources/android_page/storage.ts index 84229582d94f..1bf94defaced 100644 --- a/components/brave_rewards/resources/android_page/storage.ts +++ b/components/brave_rewards/resources/android_page/storage.ts @@ -31,7 +31,7 @@ export const defaultState: Rewards.State = { modalRedirect: 'hide', paymentIdCheck: true, walletCorrupted: false, - walletRecoverySuccess: null, + walletRecoveryStatus: null, walletServerProblem: false, onBoardingDisplayed: false }, diff --git a/components/brave_rewards/resources/brave_rewards_static_resources.grd b/components/brave_rewards/resources/brave_rewards_static_resources.grd index 025b370cce81..3eb6793c7d2d 100644 --- a/components/brave_rewards/resources/brave_rewards_static_resources.grd +++ b/components/brave_rewards/resources/brave_rewards_static_resources.grd @@ -15,7 +15,6 @@ - diff --git a/components/brave_rewards/resources/page/actions/rewards_actions.ts b/components/brave_rewards/resources/page/actions/rewards_actions.ts index 65d5c3395b31..d9bebed30798 100644 --- a/components/brave_rewards/resources/page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/page/actions/rewards_actions.ts @@ -76,8 +76,8 @@ export const recoverWallet = (key: string) => action(types.RECOVER_WALLET, { key }) -export const onRecoverWalletData = (properties: Rewards.RecoverWallet) => action(types.ON_RECOVER_WALLET_DATA, { - properties +export const onRecoverWalletData = (result: number) => action(types.ON_RECOVER_WALLET_DATA, { + result }) export const onModalBackupClose = () => action(types.ON_MODAL_BACKUP_CLOSE) diff --git a/components/brave_rewards/resources/page/brave_rewards_page.tsx b/components/brave_rewards/resources/page/brave_rewards_page.tsx index a15a83f0a926..ee256a6b450f 100644 --- a/components/brave_rewards/resources/page/brave_rewards_page.tsx +++ b/components/brave_rewards/resources/page/brave_rewards_page.tsx @@ -76,8 +76,8 @@ window.cr.define('brave_rewards', function () { getActions().onWalletPassphrase(pass) } - function recoverWalletData (properties: Rewards.RecoverWallet) { - getActions().onRecoverWalletData(properties) + function recoverWalletData (result: number) { + getActions().onRecoverWalletData(result) } function promotionFinish (properties: Rewards.PromotionFinish) { diff --git a/components/brave_rewards/resources/page/components/pageWallet.tsx b/components/brave_rewards/resources/page/components/pageWallet.tsx index 2affa037dd62..5bd73ab74912 100644 --- a/components/brave_rewards/resources/page/components/pageWallet.tsx +++ b/components/brave_rewards/resources/page/components/pageWallet.tsx @@ -244,12 +244,10 @@ class PageWallet extends React.Component { } walletAlerts = (): AlertWallet | null => { - const { total } = this.props.rewardsData.balance const { - walletRecoverySuccess, + walletRecoveryStatus, walletServerProblem, - walletCorrupted, - onlyAnonWallet + walletCorrupted } = this.props.rewardsData.ui if (walletServerProblem) { @@ -259,14 +257,12 @@ class PageWallet extends React.Component { } } - if (walletRecoverySuccess) { - const batFormatString = onlyAnonWallet ? getLocale('batPoints') : getLocale('bat') - + if (walletRecoveryStatus === 0) { return { - node: <>{getLocale('walletRestored')} {getLocale('walletRecoverySuccess', { balance: total.toString(), currency: batFormatString })}, + node: <>{getLocale('walletRestored')} {getLocale('walletRecoverySuccess')}, type: 'success', onAlertClose: () => { - this.actions.onClearAlert('walletRecoverySuccess') + this.actions.onClearAlert('walletRecoveryStatus') } } } @@ -768,6 +764,22 @@ class PageWallet extends React.Component { return (balance.wallets['anonymous'] || 0) + (balance.wallets['blinded'] || 0) } + getBackupErrorMessage = () => { + const { ui } = this.props.rewardsData + const { walletRecoveryStatus } = ui + + // ledger::Result::CORRUPTED_DATA + if (walletRecoveryStatus === 17) { + return + } + + if (walletRecoveryStatus !== 0) { + return getLocale('walletRecoveryFail') + } + + return '' + } + render () { const { recoveryKey, @@ -777,7 +789,7 @@ class PageWallet extends React.Component { pendingContributionTotal } = this.props.rewardsData const { total } = balance - const { walletRecoverySuccess, emptyWallet, modalBackup, onlyAnonWallet } = ui + const { emptyWallet, modalBackup, onlyAnonWallet } = ui const pendingTotal = parseFloat((pendingContributionTotal || 0).toFixed(3)) @@ -836,7 +848,7 @@ class PageWallet extends React.Component { onVerify={this.onVerifyClick.bind(this, true)} onReset={this.onModalBackupOnReset} internalFunds={this.getInternalFunds()} - error={walletRecoverySuccess === false ? getLocale('walletRecoveryFail') : ''} + error={this.getBackupErrorMessage()} /> : null } diff --git a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts index 9d28b0b407e4..e8800bdbae54 100644 --- a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts @@ -79,7 +79,7 @@ const rewardsReducer: Reducer = (state: Rewards.State case types.ON_MODAL_BACKUP_CLOSE: { state = { ...state } let ui = state.ui - ui.walletRecoverySuccess = null + ui.walletRecoveryStatus = null ui.modalBackup = false state = { ...state, @@ -98,7 +98,7 @@ const rewardsReducer: Reducer = (state: Rewards.State } case types.ON_CLEAR_ALERT: { let ui = state.ui - if (!ui[action.payload.property]) { + if (ui[action.payload.property] === undefined) { break } diff --git a/components/brave_rewards/resources/page/reducers/wallet_reducer.ts b/components/brave_rewards/resources/page/reducers/wallet_reducer.ts index adaabf6f2b82..24a5d5b9af8a 100644 --- a/components/brave_rewards/resources/page/reducers/wallet_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/wallet_reducer.ts @@ -72,7 +72,7 @@ const walletReducer: Reducer = (state: Rewards.State, if (!key || key.length === 0) { let ui = state.ui - ui.walletRecoverySuccess = false + ui.walletRecoveryStatus = 0 state = { ...state, @@ -87,26 +87,24 @@ const walletReducer: Reducer = (state: Rewards.State, } case types.ON_RECOVER_WALLET_DATA: { state = { ...state } - const result = action.payload.properties.result + const result = action.payload.result let ui = state.ui - let balance = state.balance // TODO NZ check why enum can't be used inside Rewards namespace - ui.walletRecoverySuccess = result === 0 + ui.walletRecoveryStatus = result if (result === 0) { - balance.total = action.payload.properties.balance chrome.send('brave_rewards.getWalletPassphrase') chrome.send('brave_rewards.fetchPromotions') + chrome.send('brave_rewards.fetchBalance') getCurrentBalanceReport() - ui.emptyWallet = balance.total <= 0 ui.modalBackup = false ui.walletCorrupted = false + ui.emptyWallet = false } state = { ...state, - ui, - balance + ui } break } diff --git a/components/brave_rewards/resources/page/storage.ts b/components/brave_rewards/resources/page/storage.ts index b6dbdfcc73e7..24827ec32458 100644 --- a/components/brave_rewards/resources/page/storage.ts +++ b/components/brave_rewards/resources/page/storage.ts @@ -31,7 +31,7 @@ export const defaultState: Rewards.State = { modalRedirect: 'hide', paymentIdCheck: true, walletCorrupted: false, - walletRecoverySuccess: null, + walletRecoveryStatus: null, walletServerProblem: false, onBoardingDisplayed: false, promosDismissed: {} diff --git a/components/brave_rewards/resources/ui/components/alert/style.ts b/components/brave_rewards/resources/ui/components/alert/style.ts index eff90674bca0..c80b7f6c46ef 100644 --- a/components/brave_rewards/resources/ui/components/alert/style.ts +++ b/components/brave_rewards/resources/ui/components/alert/style.ts @@ -82,6 +82,10 @@ export const StyledContent = styled('div')` ${getColor}; color: var(--alert-content-color); + a { + color: var(--alert-content-color); + } + b { font-weight: 600; color: var(--alert-content-bold); diff --git a/components/brave_rewards/test/BUILD.gn b/components/brave_rewards/test/BUILD.gn index fa8ece34d8e6..1fff5edc3286 100644 --- a/components/brave_rewards/test/BUILD.gn +++ b/components/brave_rewards/test/BUILD.gn @@ -38,9 +38,7 @@ source_set("brave_rewards_unit_tests") { "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/client_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/publisher_settings_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/report_balance_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/wallet_info_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/test/niceware_partial_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_util_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util_unittest.cc", diff --git a/components/definitions/global.d.ts b/components/definitions/global.d.ts index 993a0b3056a4..7ccde6f7e743 100644 --- a/components/definitions/global.d.ts +++ b/components/definitions/global.d.ts @@ -52,7 +52,7 @@ declare global { walletCreateFailed: chrome.events.Event<() => void> parameters: chrome.events.Event<(properties: Rewards.RewardsParameters) => void> walletPassphrase: chrome.events.Event<(pass: string) => void> - recoverWalletData: chrome.events.Event<(properties: Rewards.RecoverWallet) => void> + recoverWalletData: chrome.events.Event<(result: number) => void> reconcileStamp: chrome.events.Event<(stamp: number) => void> addresses: chrome.events.Event<(addresses: Record) => void> contributeList: chrome.events.Event<(list: Rewards.Publisher[]) => void> diff --git a/components/definitions/rewards.d.ts b/components/definitions/rewards.d.ts index 92c3db653673..fd7c9f991301 100644 --- a/components/definitions/rewards.d.ts +++ b/components/definitions/rewards.d.ts @@ -73,7 +73,7 @@ declare namespace Rewards { promosDismissed?: { [key: string]: boolean } - walletRecoverySuccess: boolean | null + walletRecoveryStatus: number | null walletServerProblem: boolean walletCorrupted: boolean onBoardingDisplayed?: boolean diff --git a/components/resources/brave_components_strings.grd b/components/resources/brave_components_strings.grd index 0986fca87587..2bae23031c5b 100644 --- a/components/resources/brave_components_strings.grd +++ b/components/resources/brave_components_strings.grd @@ -351,9 +351,10 @@ Twitter Tip on the spot as you find gems. If you like, let people know with a quick tweet. - {{balance}} {{currency}} was recovered. Your wallet key has been verified and loaded successfully. + Your wallet key has been verified and loaded successfully. Wallet restored! Please re-enter keys or try different keys. + The restore key entered is not supported anymore. Please visit <a target="_blank" href="http://brave.com/faq#convert-old-keys">here</a> to get a new key. Almost thereā€¦ Prove that you are human! Hmmm, not quite... diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_bridge.cc b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.cc index d6c95344cdb4..51a6ce2efa0a 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_bridge.cc +++ b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.cc @@ -165,24 +165,6 @@ void BatLedgerClientMojoBridge::FetchFavIcon(const std::string& url, base::BindOnce(&OnFetchFavIcon, std::move(callback))); } -void OnLoadNicewareList( - const ledger::GetNicewareListCallback& callback, - const ledger::Result result, - const std::string& data) { - callback(result, data); -} - -void BatLedgerClientMojoBridge::LoadNicewareList( - ledger::GetNicewareListCallback callback) { - if (!Connected()) { - callback(ledger::Result::LEDGER_ERROR, ""); - return; - } - - bat_ledger_client_->LoadNicewareList( - base::BindOnce(&OnLoadNicewareList, std::move(callback))); -} - std::string BatLedgerClientMojoBridge::URIEncode(const std::string& value) { if (!Connected()) return ""; diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h index dd2f5fe16cd4..f2f6d67ebb14 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h +++ b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h @@ -139,8 +139,6 @@ class BatLedgerClientMojoBridge : void PendingContributionSaved(const ledger::Result result) override; - void LoadNicewareList(ledger::GetNicewareListCallback callback) override; - void OnLoadLedgerState(ledger::OnLoadCallback callback, const ledger::Result result, const std::string& data); void OnLoadPublisherState(ledger::OnLoadCallback callback, diff --git a/components/services/bat_ledger/bat_ledger_impl.cc b/components/services/bat_ledger/bat_ledger_impl.cc index 77c7e6002260..e38b02075a04 100644 --- a/components/services/bat_ledger/bat_ledger_impl.cc +++ b/components/services/bat_ledger/bat_ledger_impl.cc @@ -278,10 +278,9 @@ void BatLedgerImpl::GetWalletPassphrase(GetWalletPassphraseCallback callback) { // static void BatLedgerImpl::OnRecoverWallet( CallbackHolder* holder, - ledger::Result result, - double balance) { + ledger::Result result) { if (holder->is_valid()) - std::move(holder->get()).Run(result, balance); + std::move(holder->get()).Run(result); delete holder; } @@ -294,8 +293,7 @@ void BatLedgerImpl::RecoverWallet( ledger_->RecoverWallet(pass_phrase, std::bind( BatLedgerImpl::OnRecoverWallet, holder, - _1, - _2)); + _1)); } void BatLedgerImpl::SetRewardsMainEnabled(bool enabled) { diff --git a/components/services/bat_ledger/bat_ledger_impl.h b/components/services/bat_ledger/bat_ledger_impl.h index 22f9d2350daf..5f340ee59ad2 100644 --- a/components/services/bat_ledger/bat_ledger_impl.h +++ b/components/services/bat_ledger/bat_ledger_impl.h @@ -283,8 +283,7 @@ class BatLedgerImpl : static void OnRecoverWallet( CallbackHolder* holder, - ledger::Result result, - double balance); + ledger::Result result); static void OnGetRewardsParameters( CallbackHolder* holder, diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.cc b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.cc index bb82f333cb0b..77709ae1f910 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.cc +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.cc @@ -111,27 +111,6 @@ void LedgerClientMojoBridge::FetchFavIcon(const std::string& url, std::bind(LedgerClientMojoBridge::OnFetchFavIcon, holder, _1, _2)); } -// static -void LedgerClientMojoBridge::OnLoadNicewareList( - CallbackHolder* holder, - const ledger::Result result, - const std::string& data) { - DCHECK(holder); - if (holder->is_valid()) - std::move(holder->get()).Run(result, data); - delete holder; -} - -void LedgerClientMojoBridge::LoadNicewareList( - LoadNicewareListCallback callback) { - // deleted in OnLoadNicewareList - auto* holder = new CallbackHolder( - AsWeakPtr(), std::move(callback)); - ledger_client_->LoadNicewareList( - std::bind(LedgerClientMojoBridge::OnLoadNicewareList, - holder, _1, _2)); -} - void LedgerClientMojoBridge::URIEncode(const std::string& value, URIEncodeCallback callback) { std::move(callback).Run(ledger_client_->URIEncode(value)); diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h index 540fa79eb6f9..18d9d358f126 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h @@ -39,8 +39,6 @@ class LedgerClientMojoBridge : void FetchFavIcon(const std::string& url, const std::string& favicon_key, FetchFavIconCallback callback) override; - void LoadNicewareList(LoadNicewareListCallback callback) override; - void SetTimer(uint64_t time_offset, SetTimerCallback callback) override; void KillTimer(const uint32_t timer_id) override; void OnPanelPublisherInfo( @@ -196,11 +194,6 @@ class LedgerClientMojoBridge : bool success, const std::string& favicon_url); - static void OnLoadNicewareList( - CallbackHolder* holder, - const ledger::Result result, - const std::string& data); - static void OnLoadURL( CallbackHolder* holder, const ledger::UrlResponse& response); diff --git a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom index f918f5998a7d..2e2f55ce4c16 100644 --- a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom +++ b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom @@ -62,7 +62,7 @@ interface BatLedger { ClaimPromotion(string promotion_id, string payload) => (ledger.mojom.Result result, string response); AttestPromotion(string promotion_id, string solution) => (ledger.mojom.Result result, ledger.mojom.Promotion? promotion); GetWalletPassphrase() => (string wallet_passphrase); - RecoverWallet(string passPhrase) => (ledger.mojom.Result result, double balance); + RecoverWallet(string passPhrase) => (ledger.mojom.Result result); SetRewardsMainEnabled(bool enabled); SetPublisherMinVisitTime(int32 duration_in_seconds); @@ -172,8 +172,6 @@ interface BatLedgerClient { FetchFavIcon(string url, string favicon_key) => (bool success, string favicon_url); - LoadNicewareList() => (ledger.mojom.Result result, string data); - LoadURL(string url, array headers, string content, string content_type, ledger.mojom.UrlMethod method) => (ledger.mojom.UrlResponse response); diff --git a/components/test/brave_rewards/page/reducers/rewards_reducer_test.ts b/components/test/brave_rewards/page/reducers/rewards_reducer_test.ts index 2adaf6dec351..99d2af3e03ee 100644 --- a/components/test/brave_rewards/page/reducers/rewards_reducer_test.ts +++ b/components/test/brave_rewards/page/reducers/rewards_reducer_test.ts @@ -63,11 +63,11 @@ describe('rewards reducer', () => { it('import flow - existing state', () => { const initState: Rewards.State = { ...defaultState } initState.ui.emptyWallet = false - initState.ui.walletRecoverySuccess = true + initState.ui.walletRecoveryStatus = 1 const expectedState: Rewards.State = { ...defaultState } expectedState.ui.emptyWallet = false - expectedState.ui.walletRecoverySuccess = true + expectedState.ui.walletRecoveryStatus = 1 const assertion = reducers({ rewardsData: initState diff --git a/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts b/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts index b550cac3e906..0526f45a48f1 100644 --- a/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts +++ b/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts @@ -95,9 +95,7 @@ describe('wallet reducer', () => { const assertion = reducers({ ...defaultState }, { type: types.ON_RECOVER_WALLET_DATA, payload: { - properties: { - result: 2 // non-zero result - } + result: 2 } }) @@ -115,10 +113,7 @@ describe('wallet reducer', () => { const assertion = reducers({ ...defaultState }, { type: types.ON_RECOVER_WALLET_DATA, payload: { - properties: { - result: 0, - balance: 5 - } + result: 0 } }) @@ -129,17 +124,14 @@ describe('wallet reducer', () => { emptyWallet: false, modalBackup: false, walletCorrupted: false - }, - balance: { - total: 5, - wallets: {} } } - expect(chromeSpy).toHaveBeenCalledTimes(3) + expect(chromeSpy).toHaveBeenCalledTimes(4) expect(chromeSpy.mock.calls[0][0]).toEqual('brave_rewards.getWalletPassphrase') expect(chromeSpy.mock.calls[1][0]).toEqual('brave_rewards.fetchPromotions') - expect(chromeSpy.mock.calls[2][0]).toEqual('brave_rewards.getBalanceReport') + expect(chromeSpy.mock.calls[2][0]).toEqual('brave_rewards.fetchBalance') + expect(chromeSpy.mock.calls[3][0]).toEqual('brave_rewards.getBalanceReport') expect(assertion).toEqual({ rewardsData: expectedState diff --git a/test/data/rewards-data/register_persona_resp.json b/test/data/rewards-data/register_persona_resp.json deleted file mode 100644 index 6cc9a013a11f..000000000000 --- a/test/data/rewards-data/register_persona_resp.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "payload": { - "adFree": { - "currency": "BAT", - "fee": { - "BAT":20 - }, - "choices": { - "BAT": [10,15,20,30,50,100] - }, - "range": { - "BAT": [10,100] - }, - "days": 30 - } - }, - "registrarVK": "==========ANONLOGIN_VK_BEG==========\nx3EmZXFb2jD7OocZz6l7o638S45k2kKrX5BrWp1Ox+ ANJXSauJVPNHKl/mmakFwxbkwJkJzfXe+c9+jxFtuX6 1\n5xMuqWE8J7HIHbW/UEJwFELYjTWRF10x7LMd7s46MVT 4DC6LqGM8zLz1pCsHA3qab48gkpeiQpNZAdb9owFvU6 1\n1tADCD6LdrEDQQDhRy1ijjAfhV9uKwlKKuhD6xXyPAZ BLOzUy+ZZh48riPnAHnUGal+ceCclccZXmoXXx92WHW 1\n7VRDst4U4iaT/9QNCwajEaqgRNtKPV1Dp5QuMjP019h HucbxBMGGAZBNLXGzfKsTlF+wAdmOFAvBRAo8i2Azd 1\n5SLk8SphICEkF+CNhN5g7IX2ih+Tb6w14LLlwupKw7y 96ANsdHzg0pwo2DDWOyAh1YPnION196pIT9xwISFZTA 3ef5G5d2c8cctdK4LuaxlSeEf1OZ100Sy5un5EjuHJB 77yFnY61GM7PHd6q3TLs2QS6c9PfrXD2idxaFq2DMd 1 0\n===========ANONLOGIN_VK_END==========" -} diff --git a/test/data/rewards-data/uphold_addresses_resp.json b/test/data/rewards-data/uphold_addresses_resp.json new file mode 100644 index 000000000000..eb15cdd71b25 --- /dev/null +++ b/test/data/rewards-data/uphold_addresses_resp.json @@ -0,0 +1,11 @@ +[ + { + "formats":[ + { + "format":"uuid", + "value":"1299eee5-03cd-4094-859a-cacb0f3a9321" + } + ], + "type":"anonymous" + } +] diff --git a/test/data/rewards-data/verify_persona_resp.json b/test/data/rewards-data/verify_persona_resp.json deleted file mode 100644 index 4c29df7dff71..000000000000 --- a/test/data/rewards-data/verify_persona_resp.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "wallet": { - "paymentId": "50e7b589-ea9b-48ac-9f74-d7eb85c9ff51", - "addresses": { - "BAT": "0x8A32f8560df7A5167E29ADc920b5F01D135e1a01", - "BTC": "mr5xMnn8TwdDQp7ijSK4F3sGbteS3STxbh", - "CARD_ID": "3203f496-ef4e-4b5b-ace1-f914c41a241e", - "ETH": "0x8A32f8560df7A5167E29ADc920b5F01D135e1a01", - "LTC": "mkRxRoQPdoVm3CZqSPYPVqcQrzNfH2n54z" - } - }, - "payload": { - "adFree": { - "currency": "BAT", - "fee": { - "BAT": 20 - }, - "choices": { - "BAT": [10,15,20,30,50,100] - }, - "range": { - "BAT": [10,100] - }, - "days": 30 - } - }, - "verification": "9dTh21VGjNssqaruZb3wcp2ThFSq2Ft0mWf6C+f49g XLXrRC8OJo+SHNqB2lLnIFwqhdTQk9ixenOVJdpWwd 1 ATuhjeN/AQvYjrs5WaataUUa0dj68Unx3P32NOKB6gC\n" -} diff --git a/test/data/rewards-data/wallet_resp.json b/test/data/rewards-data/wallet_resp.json new file mode 100644 index 000000000000..23ff938dcee2 --- /dev/null +++ b/test/data/rewards-data/wallet_resp.json @@ -0,0 +1,9 @@ +{ + "paymentId": "50e7b589-ea9b-48ac-9f74-d7eb85c9ff51", + "walletProvider": { + "id": "", + "name": "brave" + }, + "altcurrency": "BAT", + "publicKey": "d4f76198e614973812bbffa78f0cd887cef3ade8ad8d96dc51f45eac8c09f245" +} diff --git a/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h b/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h index 5ef65af05e93..4309f2f021a9 100644 --- a/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h +++ b/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h @@ -41,9 +41,6 @@ class ConfirmationsClientMock : public ConfirmationsClient { MOCK_METHOD1(LoadPublisherState, void( ledger::OnLoadCallback callback)); - MOCK_METHOD1(LoadNicewareList, void( - ledger::GetNicewareListCallback callback)); - MOCK_METHOD2(SaveActivityInfo, void( ledger::PublisherInfoPtr publisher_info, ledger::PublisherInfoCallback callback)); @@ -56,10 +53,6 @@ class ConfirmationsClientMock : public ConfirmationsClient { MOCK_METHOD1(ClaimPromotion, void(const std::string& promotion_id)); - MOCK_METHOD2(OnRecoverWallet, void( - ledger::Result result, - double balance)); - MOCK_METHOD3(OnPanelPublisherInfo, void( ledger::Result result, ledger::PublisherInfoPtr, diff --git a/vendor/bat-native-ledger/BUILD.gn b/vendor/bat-native-ledger/BUILD.gn index 2d952ff230cd..26d3edf263a8 100644 --- a/vendor/bat-native-ledger/BUILD.gn +++ b/vendor/bat-native-ledger/BUILD.gn @@ -285,8 +285,6 @@ source_set("ledger") { "src/bat/ledger/internal/legacy/publisher_settings_properties.h", "src/bat/ledger/internal/legacy/report_balance_properties.cc", "src/bat/ledger/internal/legacy/report_balance_properties.h", - "src/bat/ledger/internal/legacy/unsigned_tx_properties.cc", - "src/bat/ledger/internal/legacy/unsigned_tx_properties.h", "src/bat/ledger/internal/legacy/wallet_info_properties.cc", "src/bat/ledger/internal/legacy/wallet_info_properties.h", "src/bat/ledger/internal/publisher/prefix_list_reader.cc", @@ -371,8 +369,6 @@ source_set("ledger") { "src/bat/ledger/internal/legacy/report_balance_state.h", "src/bat/ledger/internal/legacy/state_reader.h", "src/bat/ledger/internal/legacy/state_writer.h", - "src/bat/ledger/internal/legacy/unsigned_tx_state.cc", - "src/bat/ledger/internal/legacy/unsigned_tx_state.h", "src/bat/ledger/internal/legacy/wallet_info_state.cc", "src/bat/ledger/internal/legacy/wallet_info_state.h", "src/bat/ledger/internal/uphold/uphold.h", @@ -393,6 +389,8 @@ source_set("ledger") { "src/bat/ledger/internal/wallet/wallet.cc", "src/bat/ledger/internal/wallet/wallet_balance.h", "src/bat/ledger/internal/wallet/wallet_balance.cc", + "src/bat/ledger/internal/wallet/wallet_claim.h", + "src/bat/ledger/internal/wallet/wallet_claim.cc", "src/bat/ledger/internal/wallet/wallet_create.h", "src/bat/ledger/internal/wallet/wallet_create.cc", "src/bat/ledger/internal/wallet/wallet_recover.h", @@ -420,7 +418,6 @@ source_set("ledger") { "//url", rebase_path("bat-native-ads", dep_base), rebase_path("bat-native-confirmations", dep_base), - rebase_path("bat-native-anonize:anonize2", dep_base), rebase_path("bip39wally-core-native:bip39wally-core", dep_base), rebase_path("bat-native-tweetnacl:tweetnacl", dep_base), rebase_path("bat-native-rapidjson", dep_base), diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger.h b/vendor/bat-native-ledger/include/bat/ledger/ledger.h index 6da403c6918c..240ead969149 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger.h @@ -67,10 +67,6 @@ using GetMonthlyReportCallback = using GetAllMonthlyReportIdsCallback = std::function&)>; -using RecoverWalletCallback = std::function; - class LEDGER_EXPORT Ledger { public: static bool IsMediaLink(const std::string& url, @@ -223,7 +219,7 @@ class LEDGER_EXPORT Ledger { virtual void RecoverWallet( const std::string& pass_phrase, - RecoverWalletCallback callback) = 0; + ResultCallback callback) = 0; virtual void SetPublisherExclude( const std::string& publisher_id, diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h index da64a33c196d..fc9c885f3965 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h @@ -22,8 +22,6 @@ using PublisherInfoCallback = // TODO(nejczdovc) we should be providing result back as well using PublisherInfoListCallback = std::function; -using GetNicewareListCallback = - std::function; using FetchIconCallback = std::function; using LoadURLCallback = std::function; using OnLoadCallback = std::functionGetPaymentId()); + auto payment_id = base::Value(braveledger_state::GetPaymentId(ledger_)); base::Value payment_ids(base::Value::Type::LIST); payment_ids.Append(std::move(payment_id)); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc index 0aee32e2cf2b..ace1a77f9c31 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc @@ -13,6 +13,7 @@ #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/request/request_attestation.h" #include "bat/ledger/internal/response/response_attestation.h" +#include "bat/ledger/internal/state/state_util.h" using std::placeholders::_1; using std::placeholders::_2; @@ -74,7 +75,7 @@ void AttestationDesktop::Start( braveledger_request_util::GetStartAttestationDesktopUrl(); base::Value body(base::Value::Type::DICTIONARY); - body.SetStringKey("paymentId", ledger_->GetPaymentId()); + body.SetStringKey("paymentId", braveledger_state::GetPaymentId(ledger_)); std::string json; base::JSONWriter::Write(body, &json); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc index aed1c880e205..c62de301aaf0 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc @@ -12,6 +12,7 @@ #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/request/request_attestation.h" #include "bat/ledger/internal/response/response_attestation.h" +#include "bat/ledger/internal/state/state_util.h" using std::placeholders::_1; using std::placeholders::_2; @@ -86,7 +87,7 @@ void AttestationIOS::Start( const std::string& payload, StartCallback callback) { const std::string key = ParseStartPayload(payload); - const std::string payment_id = ledger_->GetPaymentId(); + const std::string payment_id = braveledger_state::GetPaymentId(ledger_); if (key.empty()) { BLOG(0, "Key is empty"); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc index ea3327cb65e2..610ff38ac078 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc @@ -200,70 +200,6 @@ bool getJSONMessage(const std::string& json, return false; } -std::vector generateSeed() { - std::vector vSeed(SEED_LENGTH); - std::random_device r; - std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; - auto rand = std::bind(std::uniform_int_distribution<>(0, UCHAR_MAX), - std::mt19937(seed)); - - std::generate_n(vSeed.begin(), SEED_LENGTH, rand); - return vSeed; -} - -std::vector getHKDF(const std::vector& seed) { - DCHECK(!seed.empty()); - std::vector out(SEED_LENGTH); - - const uint8_t info[] = {0}; - int hkdfRes = HKDF(&out.front(), - SEED_LENGTH, - EVP_sha512(), - &seed.front(), - seed.size(), - braveledger_ledger::g_hkdfSalt, - SALT_LENGTH, - info, - sizeof(info) / sizeof(info[0])); - - DCHECK(hkdfRes); - DCHECK(!seed.empty()); - - // We set the key_length to the length of the expected output and then take - // the result from the first key, which is the client write key. - - return out; -} - -bool getPublicKeyFromSeed(const std::vector& seed, - std::vector* publicKey, - std::vector* secretKey) { - DCHECK(!seed.empty()); - if (seed.empty()) { - return false; - } - publicKey->resize(crypto_sign_PUBLICKEYBYTES); - *secretKey = seed; - secretKey->resize(crypto_sign_SECRETKEYBYTES); - - crypto_sign_keypair(&publicKey->front(), &secretKey->front(), 1); - - DCHECK(!publicKey->empty() && !secretKey->empty()); - if (publicKey->empty() && secretKey->empty()) { - return false; - } - - return true; -} - -std::string uint8ToHex(const std::vector& in) { - std::ostringstream res; - for (size_t i = 0; i < in.size(); i++) { - res << std::setfill('0') << std::setw(sizeof(uint8_t) * 2) - << std::hex << static_cast(in[i]); - } - return res.str(); -} std::string stringify(std::string* keys, std::string* values, @@ -380,34 +316,4 @@ std::string toLowerCase(std::string word) { return word; } -uint8_t niceware_mnemonic_to_bytes( - const std::string& w, - std::vector* bytes_out, - size_t* written, - std::vector wordDictionary) { - std::vector wordList = base::SplitString( - toLowerCase(w), - WALLET_PASSPHRASE_DELIM, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - - std::vector buffer(wordList.size() * 2); - - for (uint8_t ix = 0; ix < wordList.size(); ix++) { - std::vector::iterator it = - std::find(wordDictionary.begin(), - wordDictionary.end(), wordList[ix]); - if (it != wordDictionary.end()) { - int wordIndex = std::distance(wordDictionary.begin(), it); - buffer[2 * ix] = floor(wordIndex / 256); - buffer[2 * ix + 1] = wordIndex % 256; - } else { - return INVALID_LEGACY_WALLET; - } - } - *bytes_out = buffer; - *written = NICEWARE_BYTES_WRITTEN; - return 0; -} - } // namespace braveledger_bat_helper diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h index 2f1511b7ec1b..b73c88c28f69 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h @@ -46,16 +46,6 @@ bool getJSONAddresses(const std::string& json, bool getJSONMessage(const std::string& json, std::string* message); -std::vector generateSeed(); - -std::vector getHKDF(const std::vector& seed); - -bool getPublicKeyFromSeed(const std::vector& seed, - std::vector* publicKey, - std::vector* secretKey); - -std::string uint8ToHex(const std::vector& in); - std::string stringify(std::string* keys, std::string* values, const unsigned int size); @@ -73,12 +63,6 @@ std::string sign( const std::string& key_id, const std::vector& secretKey); -uint8_t niceware_mnemonic_to_bytes( - const std::string& w, - std::vector* bytes_out, - size_t* written, - std::vector wordDictionary); - bool HasSameDomainAndPath( const std::string& url, const std::string& to_match, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.cc index 3bbe60116111..5130bb90a1f4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.cc @@ -4,14 +4,37 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include +#include +#include #include +#include +#include #include #include "base/base64.h" +#include "base/strings/stringprintf.h" #include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/static_values.h" #include "bat/ledger/internal/common/security_helper.h" +#include "tweetnacl.h" // NOLINT + +namespace { + +const uint8_t kHkdfSalt[] = { + 126, 244, 99, 158, 51, 68, 253, 80, 133, 183, 51, 180, 77, + 62, 74, 252, 62, 106, 96, 125, 241, 110, 134, 87, 190, 208, + 158, 84, 125, 69, 246, 207, 162, 247, 107, 172, 37, 34, 53, + 246, 105, 20, 215, 5, 248, 154, 179, 191, 46, 17, 6, 72, 210, + 91, 10, 169, 145, 248, 22, 147, 117, 24, 105, 12}; + +const int kSeedLength = 32; + +const int kSaltLength = 64; + +} // namespace + namespace braveledger_helper { std::string Security::GetBase64(const std::vector& data) { @@ -30,8 +53,6 @@ std::string Security::GetBase64(const std::vector& data) { } std::vector Security::GetSHA256(const std::string& string) { - DCHECK(!string.empty()); - std::vector string_sha256(SHA256_DIGEST_LENGTH); SHA256((uint8_t*)string.c_str(), string.length(), &string_sha256.front()); return string_sha256; @@ -56,11 +77,10 @@ std::string Security::Sign( header_values.push_back(value); } - std::vector secret_key = - braveledger_bat_helper::getHKDF(private_key); + std::vector secret_key = GetHKDF(private_key); std::vector public_key; std::vector new_secret_key; - bool success = braveledger_bat_helper::getPublicKeyFromSeed( + bool success = GetPublicKeyFromSeed( secret_key, &public_key, &new_secret_key); @@ -75,4 +95,99 @@ std::string Security::Sign( new_secret_key); } +std::vector Security::GenerateSeed() { + std::vector v_seed(kSeedLength); + std::random_device r; + std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; + auto rand = std::bind( + std::uniform_int_distribution<>(0, UCHAR_MAX), + std::mt19937(seed)); + + std::generate_n(v_seed.begin(), kSeedLength, rand); + return v_seed; +} + +std::string Security::Uint8ToHex(const std::vector& in) { + std::ostringstream res; + for (size_t i = 0; i < in.size(); i++) { + res << std::setfill('0') << std::setw(sizeof(uint8_t) * 2) + << std::hex << static_cast(in[i]); + } + return res.str(); +} + +bool Security::GetPublicKeyFromSeed( + const std::vector& seed, + std::vector* public_key, + std::vector* secret_key) { + DCHECK(public_key && secret_key && !seed.empty()); + if (seed.empty()) { + return false; + } + + public_key->resize(crypto_sign_PUBLICKEYBYTES); + *secret_key = seed; + secret_key->resize(crypto_sign_SECRETKEYBYTES); + + crypto_sign_keypair(&public_key->front(), &secret_key->front(), 1); + + DCHECK(!public_key->empty() && !secret_key->empty()); + if (public_key->empty() && secret_key->empty()) { + return false; + } + + return true; +} + +std::vector Security::GetHKDF(const std::vector& seed) { + DCHECK(!seed.empty()); + std::vector out(kSeedLength); + + const uint8_t info[] = {0}; + int hkdf_res = HKDF( + &out.front(), + kSeedLength, + EVP_sha512(), + &seed.front(), + seed.size(), + kHkdfSalt, + kSaltLength, + info, + sizeof(info) / sizeof(info[0])); + + DCHECK(hkdf_res); + DCHECK(!seed.empty()); + + // We set the key_length to the length of the expected output and then take + // the result from the first key, which is the client write key. + + return out; +} + +bool Security::IsSeedValid(const std::vector& seed) { + return seed.size() == kSeedLength; +} + +std::string Security::DigestValue(const std::string& body) { + const auto body_sha256 = Security::GetSHA256(body); + const auto body_sha256_base64 = Security::GetBase64(body_sha256); + + return base::StringPrintf("SHA-256=%s", body_sha256_base64.c_str()); +} + +std::string Security::GetPublicKeyHexFromSeed( + const std::vector& seed) { + std::vector secret_key = GetHKDF(seed); + std::vector public_key; + std::vector new_secret_key; + const bool success = + GetPublicKeyFromSeed(secret_key, &public_key, &new_secret_key); + + if (!success) { + return ""; + } + + return Uint8ToHex(public_key); +} + } // namespace braveledger_helper diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.h b/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.h index d4aa269f180b..942438b5474e 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/common/security_helper.h @@ -22,6 +22,23 @@ class Security { const std::vector>& headers, const std::string& key_id, const std::vector& private_key); + + static std::vector GenerateSeed(); + + static std::string Uint8ToHex(const std::vector& in); + + static bool GetPublicKeyFromSeed( + const std::vector& seed, + std::vector* public_key, + std::vector* secret_key); + + static std::vector GetHKDF(const std::vector& seed); + + static bool IsSeedValid(const std::vector& seed); + + static std::string DigestValue(const std::string& body); + + static std::string GetPublicKeyHexFromSeed(const std::vector& seed); }; } // namespace braveledger_helper diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.cc index 95a55f2e4951..e282d55fbafe 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.cc @@ -96,7 +96,7 @@ void ContributionAnonCard::SendTransaction( amount, order_id, destination, - ledger_->GetPaymentId(), + braveledger_state::GetPaymentId(ledger_), braveledger_state::GetRecoverySeed(ledger_)); auto url_callback = std::bind(&ContributionAnonCard::OnSendTransaction, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.cc index 7d802a83a3f0..b0b2317881f9 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.cc @@ -152,7 +152,7 @@ void CredentialsPromotion::Claim( return; } - const std::string payment_id = ledger_->GetPaymentId(); + const std::string payment_id = braveledger_state::GetPaymentId(ledger_); base::Value body(base::Value::Type::DICTIONARY); body.SetStringKey("paymentId", payment_id); body.SetKey("blindedCreds", base::Value(std::move(*blinded_creds))); @@ -466,12 +466,14 @@ void CredentialsPromotion::RedeemTokens( std::string url; std::vector headers; if (redeem.type == ledger::RewardsType::TRANSFER) { - payload = GenerateTransferTokensPayload(redeem, ledger_->GetPaymentId()); + payload = GenerateTransferTokensPayload( + redeem, + braveledger_state::GetPaymentId(ledger_)); url = braveledger_request_util::GetTransferTokens(); headers = braveledger_request_util::BuildSignHeaders( "post /v1/suggestions/claim", payload, - ledger_->GetPaymentId(), + braveledger_state::GetPaymentId(ledger_), braveledger_state::GetRecoverySeed(ledger_)); } else { if (redeem.publisher_key.empty()) { diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h index 2bd10a81654c..072a9fb826ab 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h @@ -34,9 +34,6 @@ class MockLedgerClient : public LedgerClient { MOCK_METHOD1(LoadPublisherState, void( ledger::OnLoadCallback callback)); - MOCK_METHOD1(LoadNicewareList, void( - ledger::GetNicewareListCallback callback)); - MOCK_METHOD3(OnPanelPublisherInfo, void( ledger::Result result, ledger::PublisherInfoPtr, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc index d055bd562a65..468ca7d3949f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc @@ -18,6 +18,7 @@ #include "bat/confirmations/confirmations.h" #include "bat/ledger/internal/api/api.h" #include "bat/ledger/internal/media/media.h" +#include "bat/ledger/internal/common/security_helper.h" #include "bat/ledger/internal/common/time_util.h" #include "bat/ledger/internal/publisher/prefix_list_reader.h" #include "bat/ledger/internal/publisher/publisher.h" @@ -430,19 +431,20 @@ void LedgerImpl::SetConfirmationsWalletInfo() { const auto recovery_seed = braveledger_state::GetRecoverySeed(this); const std::vector seed = - braveledger_bat_helper::getHKDF(recovery_seed); + braveledger_helper::Security::GetHKDF(recovery_seed); std::vector public_key; std::vector secret_key; - if (!braveledger_bat_helper::getPublicKeyFromSeed(seed, &public_key, + if (!braveledger_helper::Security::GetPublicKeyFromSeed(seed, &public_key, &secret_key)) { BLOG(0, "Failed to initialize confirmations due to invalid wallet"); return; } confirmations::WalletInfo wallet_info; - wallet_info.payment_id = GetPaymentId(); - wallet_info.private_key = braveledger_bat_helper::uint8ToHex(secret_key); + wallet_info.payment_id = braveledger_state::GetPaymentId(this); + wallet_info.private_key = + braveledger_helper::Security::Uint8ToHex(secret_key); if (!wallet_info.IsValid()) { BLOG(0, "Failed to initialize confirmations due to invalid wallet"); @@ -556,10 +558,6 @@ void LedgerImpl::OnRestorePublishers( bat_publisher_->OnRestorePublishers(result, callback); } -void LedgerImpl::LoadNicewareList(ledger::GetNicewareListCallback callback) { - ledger_client_->LoadNicewareList(callback); -} - void LedgerImpl::GetPublisherInfo( const std::string& publisher_key, ledger::PublisherInfoCallback callback) { @@ -752,28 +750,24 @@ std::string LedgerImpl::GetWalletPassphrase() const { void LedgerImpl::RecoverWallet( const std::string& pass_phrase, - ledger::RecoverWalletCallback callback) { + ledger::ResultCallback callback) { auto on_recover = std::bind(&LedgerImpl::OnRecoverWallet, this, _1, - _2, std::move(callback)); bat_wallet_->RecoverWallet(pass_phrase, std::move(on_recover)); } void LedgerImpl::OnRecoverWallet( const ledger::Result result, - const double balance, - ledger::RecoverWalletCallback callback) { - if (result != ledger::Result::LEDGER_OK) { - BLOG(0, "Failed to recover wallet"); - } + ledger::ResultCallback callback) { + BLOG_IF(0, result != ledger::Result::LEDGER_OK, "Failed to recover wallet"); if (result == ledger::Result::LEDGER_OK) { bat_database_->DeleteAllBalanceReports([](const ledger::Result _) {}); } - callback(result, balance); + callback(result); } void LedgerImpl::GetBalanceReport( @@ -929,30 +923,30 @@ void LedgerImpl::ResetReconcileStamp() { ledger_client_->ReconcileStampReset(); } -std::string LedgerImpl::GetPaymentId() { - return braveledger_state::GetPaymentId(this); -} - void LedgerImpl::GetRewardsInternalsInfo( ledger::RewardsInternalsInfoCallback callback) { ledger::RewardsInternalsInfoPtr info = ledger::RewardsInternalsInfo::New(); // Retrieve the payment id. - info->payment_id = GetPaymentId(); + info->payment_id = braveledger_state::GetPaymentId(this); // Retrieve the boot stamp. info->boot_stamp = GetCreationStamp(); // Retrieve the key info seed and validate it. const auto seed = braveledger_state::GetRecoverySeed(this); - if (seed.size() != SEED_LENGTH) { + if (!braveledger_helper::Security::IsSeedValid(seed)) { info->is_key_info_seed_valid = false; } else { - std::vector secret_key = braveledger_bat_helper::getHKDF(seed); + std::vector secret_key = + braveledger_helper::Security::GetHKDF(seed); std::vector public_key; std::vector new_secret_key; - info->is_key_info_seed_valid = braveledger_bat_helper::getPublicKeyFromSeed( - secret_key, &public_key, &new_secret_key); + info->is_key_info_seed_valid = + braveledger_helper::Security::GetPublicKeyFromSeed( + secret_key, + &public_key, + &new_secret_key); } callback(std::move(info)); @@ -966,9 +960,6 @@ uint64_t LedgerImpl::GetCreationStamp() { return braveledger_state::GetCreationStamp(this); } -void LedgerImpl::SetCreationStamp(uint64_t stamp) { - braveledger_state::SetCreationStamp(this, stamp); -} void LedgerImpl::SaveContributionInfo( ledger::ContributionInfoPtr info, ledger::ResultCallback callback) { @@ -1184,10 +1175,8 @@ void LedgerImpl::DisconnectWallet( bat_wallet_->DisconnectWallet(wallet_type, callback); } -void LedgerImpl::TransferAnonToExternalWallet( - ledger::ResultCallback callback, - const bool allow_zero_balance) { - bat_wallet_->TransferAnonToExternalWallet(allow_zero_balance, callback); +void LedgerImpl::ClaimFunds(ledger::ResultCallback callback) { + bat_wallet_->ClaimFunds(callback); } void LedgerImpl::ShowNotification( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h index 34c0cd1ab498..01c10d255198 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h @@ -183,8 +183,6 @@ class LedgerImpl : public ledger::Ledger { ledger::AutoContributePropertiesPtr GetAutoContributeProperties() override; - void LoadNicewareList(ledger::GetNicewareListCallback callback); - void SetConfirmationsWalletInfo(); void LoadLedgerState(ledger::OnLoadCallback callback); @@ -210,12 +208,11 @@ class LedgerImpl : public ledger::Ledger { void RecoverWallet( const std::string& pass_phrase, - ledger::RecoverWalletCallback callback) override; + ledger::ResultCallback callback) override; void OnRecoverWallet( const ledger::Result result, - double balance, - ledger::RecoverWalletCallback callback); + ledger::ResultCallback callback); virtual void LoadURL( const std::string& url, @@ -308,12 +305,8 @@ class LedgerImpl : public ledger::Ledger { void ResetReconcileStamp(); - virtual std::string GetPaymentId(); - uint64_t GetCreationStamp() override; - void SetCreationStamp(uint64_t stamp); - void SaveContributionInfo( ledger::ContributionInfoPtr info, ledger::ResultCallback callback); @@ -410,9 +403,7 @@ class LedgerImpl : public ledger::Ledger { const std::string& wallet_type, ledger::ResultCallback callback) override; - void TransferAnonToExternalWallet( - ledger::ResultCallback callback, - const bool allow_zero_balance = false); + void ClaimFunds(ledger::ResultCallback callback); void ShowNotification( const std::string& type, @@ -462,7 +453,7 @@ class LedgerImpl : public ledger::Ledger { void SetStringState(const std::string& name, const std::string& value); - std::string GetStringState(const std::string& name) const; + virtual std::string GetStringState(const std::string& name) const; void SetInt64State(const std::string& name, int64_t value); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h index 624efc140d95..2f3d1affdcb4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h @@ -115,8 +115,6 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD0(GetAutoContributeProperties, ledger::AutoContributePropertiesPtr()); - MOCK_METHOD1(LoadNicewareList, void(ledger::GetNicewareListCallback)); - MOCK_METHOD1(SetConfirmationsWalletInfo, void(const ledger::WalletInfoProperties&)); @@ -146,10 +144,7 @@ class MockLedgerImpl : public LedgerImpl { MOCK_CONST_METHOD0(GetWalletPassphrase, std::string()); MOCK_METHOD2(RecoverWallet, - void(const std::string&, ledger::RecoverWalletCallback)); - - MOCK_METHOD3(OnRecoverWallet, - void(const ledger::Result, double, ledger::RecoverWalletCallback)); + void(const std::string&, ledger::ResultCallback)); MOCK_METHOD6(LoadURL, void(const std::string&, @@ -239,16 +234,12 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD0(ResetReconcileStamp, void()); - MOCK_METHOD0(GetPaymentId, std::string()); - MOCK_METHOD1(GetConfirmationsWalletInfo, const confirmations::WalletInfo( const ledger::WalletInfoProperties&)); MOCK_METHOD0(GetCreationStamp, uint64_t()); - MOCK_METHOD1(SetCreationStamp, void(uint64_t)); - MOCK_METHOD6(SaveContributionInfo, void(const std::string&, const ledger::ActivityMonth, @@ -351,8 +342,7 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD2(DisconnectWallet, void(const std::string&, ledger::ResultCallback)); - MOCK_METHOD2(TransferAnonToExternalWallet, - void(ledger::ResultCallback, const bool)); + MOCK_METHOD1(ClaimFunds, void(ledger::ResultCallback)); MOCK_METHOD3(ShowNotification, void(const std::string&, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.cc deleted file mode 100644 index 5344deddabf7..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.cc +++ /dev/null @@ -1,33 +0,0 @@ -/* 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 http://mozilla.org/MPL/2.0/. */ - -#include "bat/ledger/internal/legacy/unsigned_tx_properties.h" - -namespace ledger { - -UnsignedTxProperties::UnsignedTxProperties() = default; - -UnsignedTxProperties::UnsignedTxProperties( - const UnsignedTxProperties& properties) { - amount = properties.amount; - currency = properties.currency; - destination = properties.destination; -} - -UnsignedTxProperties::~UnsignedTxProperties() = default; - -bool UnsignedTxProperties::operator==( - const UnsignedTxProperties& rhs) const { - return amount == rhs.amount && - currency == rhs.currency && - destination == rhs.destination; -} - -bool UnsignedTxProperties::operator!=( - const UnsignedTxProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.h deleted file mode 100644 index 9c1d56b5d423..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_properties.h +++ /dev/null @@ -1,32 +0,0 @@ -/* 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 http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVELEDGER_PROPERTIES_UNSIGNED_TX_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_UNSIGNED_TX_PROPERTIES_H_ - -#include - -namespace ledger { - -struct UnsignedTxProperties { - UnsignedTxProperties(); - UnsignedTxProperties( - const UnsignedTxProperties& properties); - ~UnsignedTxProperties(); - - bool operator==( - const UnsignedTxProperties& rhs) const; - - bool operator!=( - const UnsignedTxProperties& rhs) const; - - std::string amount; - std::string currency; - std::string destination; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_UNSIGNED_TX_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.cc deleted file mode 100644 index 1e47883a2ebe..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.cc +++ /dev/null @@ -1,178 +0,0 @@ -/* 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 http://mozilla.org/MPL/2.0/. */ - -#include "bat/ledger/internal/logging.h" -#include "bat/ledger/internal/legacy/unsigned_tx_state.h" -#include "base/json/json_reader.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kAmountKey[] = "amount"; -const char kCurrencyKey[] = "currency"; -const char kDenominationKey[] = "denomination"; -const char kDestinationKey[] = "destination"; -const char kUnsignedTxKey[] = "unsignedTx"; -const char kAmountPath[] = "denomination.amount"; -const char kCurrencyPath[] = "denomination.currency"; -const char kDestinationPath[] = "destination"; - -} // namespace - -UnsignedTxState::UnsignedTxState() = default; - -UnsignedTxState::~UnsignedTxState() = default; - -bool UnsignedTxState::FromJson( - const std::string& json, - UnsignedTxProperties* properties) const { - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - auto json_value = base::JSONReader::Read(json); - if (!json_value) { - NOTREACHED(); - return false; - } - - base::DictionaryValue* dictionary = nullptr; - json_value->GetAsDictionary(&dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - return FromDict(dictionary, properties); -} - -bool UnsignedTxState::FromJsonResponse( - const std::string& json, - UnsignedTxProperties* properties) const { - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - auto json_value = base::JSONReader::Read(json); - if (!json_value) { - return false; - } - - base::DictionaryValue* dictionary = nullptr; - json_value->GetAsDictionary(&dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - // Unsigned Tx - const auto* unsigned_tx_value = dictionary->FindKey(kUnsignedTxKey); - if (!unsigned_tx_value || !unsigned_tx_value->is_dict()) { - NOTREACHED(); - return false; - } - - const base::DictionaryValue* unsigned_tx_dictionary = nullptr; - unsigned_tx_value->GetAsDictionary(&unsigned_tx_dictionary); - if (!unsigned_tx_dictionary) { - NOTREACHED(); - return false; - } - - return FromDict(unsigned_tx_dictionary, properties); -} - -bool UnsignedTxState::FromDict( - const base::DictionaryValue* dictionary, - UnsignedTxProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - UnsignedTxProperties unsigned_tx_properties; - - // Amount - const auto* amount = dictionary->FindStringPath(kAmountPath); - if (!amount) { - return false; - } - unsigned_tx_properties.amount = *amount; - - // Currency - const auto* currency = dictionary->FindStringPath(kCurrencyPath); - if (!currency) { - return false; - } - unsigned_tx_properties.currency = *currency; - - // Destination - const auto* destination = dictionary->FindStringPath(kDestinationPath); - if (!destination) { - return false; - } - unsigned_tx_properties.destination = *destination; - - *properties = unsigned_tx_properties; - - return true; -} - -bool UnsignedTxState::ToJson( - JsonWriter* writer, - const UnsignedTxProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kDenominationKey); - writer->StartObject(); - - writer->String(kAmountKey); - writer->String(properties.amount.c_str()); - - writer->String(kCurrencyKey); - writer->String(properties.currency.c_str()); - writer->EndObject(); - - writer->String(kDestinationKey); - writer->String(properties.destination.c_str()); - - writer->EndObject(); - - return true; -} - -std::string UnsignedTxState::ToJson( - const UnsignedTxProperties& properties) const { - rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); - - if (!ToJson(&writer, properties)) { - NOTREACHED(); - return ""; - } - - return buffer.GetString(); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.h deleted file mode 100644 index 599a7059a1eb..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state.h +++ /dev/null @@ -1,49 +0,0 @@ -/* 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 http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVELEDGER_LEGACY_UNSIGNED_TX_STATE_H_ -#define BRAVELEDGER_LEGACY_UNSIGNED_TX_STATE_H_ - -#include - -#include "bat/ledger/internal/legacy/state_reader.h" -#include "bat/ledger/internal/legacy/state_writer.h" -#include "bat/ledger/internal/legacy/unsigned_tx_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class UnsignedTxState - : public state::Reader, - public state::Writer { - public: - UnsignedTxState(); - ~UnsignedTxState(); - - bool FromJson( - const std::string& json, - UnsignedTxProperties* properties) const override; - - bool FromJsonResponse( - const std::string& json, - UnsignedTxProperties* properties) const; - - bool FromDict( - const base::DictionaryValue* dictionary, - UnsignedTxProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const UnsignedTxProperties& properties) const override; - - std::string ToJson( - const UnsignedTxProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_LEGACY_UNSIGNED_TX_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state_unittest.cc deleted file mode 100644 index dc04caa23561..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/legacy/unsigned_tx_state_unittest.cc +++ /dev/null @@ -1,84 +0,0 @@ -/* 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 http://mozilla.org/MPL/2.0/. */ - -#include "bat/ledger/internal/legacy/unsigned_tx_state.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=UnsignedTxStateTest.* - -namespace ledger { - -TEST(UnsignedTxStateTest, ToJsonSerialization) { - // Arrange - UnsignedTxProperties unsigned_tx_properties; - unsigned_tx_properties.amount = "Amount"; - unsigned_tx_properties.currency = "Currency"; - unsigned_tx_properties.destination = "Destination"; - - // Act - const UnsignedTxState unsigned_tx_state; - const std::string json = unsigned_tx_state.ToJson(unsigned_tx_properties); - - // Assert - UnsignedTxProperties expected_unsigned_tx_properties; - unsigned_tx_state.FromJson(json, &expected_unsigned_tx_properties); - EXPECT_EQ(expected_unsigned_tx_properties, unsigned_tx_properties); -} - -TEST(UnsignedTxStateTest, FromJsonDeserialization) { - // Arrange - UnsignedTxProperties unsigned_tx_properties; - unsigned_tx_properties.amount = "Amount"; - unsigned_tx_properties.currency = "Currency"; - unsigned_tx_properties.destination = "Destination"; - - const std::string json = "{\"denomination\":{\"amount\":\"Amount\",\"currency\":\"Currency\"},\"destination\":\"Destination\"}"; // NOLINT - - // Act - UnsignedTxProperties expected_unsigned_tx_properties; - const UnsignedTxState unsigned_tx_state; - unsigned_tx_state.FromJson(json, &expected_unsigned_tx_properties); - - // Assert - EXPECT_EQ(expected_unsigned_tx_properties, unsigned_tx_properties); -} - -TEST(UnsignedTxStateTest, FromJsonResponseDeserialization) { - // Arrange - UnsignedTxProperties unsigned_tx_properties; - unsigned_tx_properties.amount = "Amount"; - unsigned_tx_properties.currency = "Currency"; - unsigned_tx_properties.destination = "Destination"; - - const std::string json = "{\"unsignedTx\":{\"denomination\":{\"amount\":\"Amount\",\"currency\":\"Currency\"},\"destination\":\"Destination\"}}"; // NOLINT - - // Act - UnsignedTxProperties expected_unsigned_tx_properties; - const UnsignedTxState unsigned_tx_state; - unsigned_tx_state.FromJsonResponse(json, &expected_unsigned_tx_properties); - - // Assert - EXPECT_EQ(expected_unsigned_tx_properties, unsigned_tx_properties); -} - -TEST(UnsignedTxStateTest, FromInvalidJsonResponseDeserialization) { - // Arrange - UnsignedTxProperties unsigned_tx_properties; - unsigned_tx_properties.amount = "Amount"; - unsigned_tx_properties.currency = "Currency"; - unsigned_tx_properties.destination = "Destination"; - - const std::string json = "FOOBAR"; - - // Act - UnsignedTxProperties expected_unsigned_tx_properties; - const UnsignedTxState unsigned_tx_state; - unsigned_tx_state.FromJsonResponse(json, &expected_unsigned_tx_properties); - - // Assert - EXPECT_NE(expected_unsigned_tx_properties, unsigned_tx_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc index 7cf18dadade6..fcb7d007abad 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc @@ -25,6 +25,7 @@ #include "bat/ledger/internal/request/request_util.h" #include "bat/ledger/internal/response/response_promotion.h" #include "bat/ledger/internal/state/state_keys.h" +#include "bat/ledger/internal/state/state_util.h" #include "bat/ledger/internal/static_values.h" #include "brave_base/random.h" @@ -126,7 +127,8 @@ void Promotion::Initialize() { void Promotion::Fetch(ledger::FetchPromotionCallback callback) { // make sure wallet/client state is sane here as this is the first // panel call. - const std::string& wallet_payment_id = ledger_->GetPaymentId(); + const std::string& wallet_payment_id = + braveledger_state::GetPaymentId(ledger_); const std::string& passphrase = ledger_->GetWalletPassphrase(); if (wallet_payment_id.empty() || passphrase.empty()) { BLOG(0, "Corrupted wallet"); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.cc index ca109f1b0734..500b277b9da1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.cc @@ -28,36 +28,6 @@ PromotionTransfer::PromotionTransfer(bat_ledger::LedgerImpl* ledger) : PromotionTransfer::~PromotionTransfer() = default; void PromotionTransfer::Start(ledger::ResultCallback callback) { - // we only need to call old anon api once - if (ledger_->GetBooleanState(ledger::kStateAnonTransferChecked)) { - GetEligiblePromotion(callback); - return; - } - - auto transfer_callback = std::bind(&PromotionTransfer::OnAnonExternalWallet, - this, - _1, - callback); - - ledger_->TransferAnonToExternalWallet( - transfer_callback, - true); -} - -void PromotionTransfer::OnAnonExternalWallet( - const ledger::Result result, - ledger::ResultCallback callback) { - if (result != ledger::Result::LEDGER_OK) { - BLOG(0, "Initial transfer failed"); - callback(ledger::Result::LEDGER_ERROR); - return; - } - - ledger_->SetBooleanState(ledger::kStateAnonTransferChecked, true); - GetEligiblePromotion(callback); -} - -void PromotionTransfer::GetEligiblePromotion(ledger::ResultCallback callback) { auto tokens_callback = std::bind(&PromotionTransfer::GetEligibleTokens, this, _1, @@ -67,6 +37,7 @@ void PromotionTransfer::GetEligiblePromotion(ledger::ResultCallback callback) { GetEligiblePromotions(), tokens_callback); } + void PromotionTransfer::GetEligibleTokens( ledger::PromotionList promotions, ledger::ResultCallback callback) { diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.h b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.h index 36d795ad2cf5..75cf31ba336f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_transfer.h @@ -28,12 +28,6 @@ class PromotionTransfer { void Start(ledger::ResultCallback callback); private: - void OnAnonExternalWallet( - const ledger::Result result, - ledger::ResultCallback callback); - - void GetEligiblePromotion(ledger::ResultCallback callback); - void GetEligibleTokens( ledger::PromotionList promotions, ledger::ResultCallback callback); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_unittest.cc index de4203579276..3f96b8e25f89 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_unittest.cc @@ -13,6 +13,7 @@ #include "bat/ledger/internal/ledger_client_mock.h" #include "bat/ledger/internal/ledger_impl_mock.h" #include "bat/ledger/internal/promotion/promotion.h" +#include "bat/ledger/internal/state/state_keys.h" #include "bat/ledger/ledger.h" #include "testing/gtest/include/gtest/gtest.h" @@ -68,7 +69,7 @@ class PromotionTest : public testing::Test { void SetUp() override { const std::string payment_id = "this_is_id"; - ON_CALL(*mock_ledger_impl_, GetPaymentId()) + ON_CALL(*mock_ledger_impl_, GetStringState(ledger::kStatePaymentId)) .WillByDefault(testing::Return(payment_id)); const std::string wallet_passphrase = "phrase"; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc index a05fb21b5782..a2d296308788 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc @@ -216,7 +216,7 @@ void EmptyBalance::ReportResults( R"({"amount": %f})", total); - const std::string payment_id = ledger->GetPaymentId(); + const std::string payment_id = braveledger_state::GetPaymentId(ledger); auto url_callback = std::bind(&EmptyBalance::Sent, _1, ledger); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc index 60c33511aa6f..77f63a8503f0 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc @@ -69,4 +69,22 @@ std::string GetBatlossURL( return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); } +std::string GetCreateWalletURL() { + return BuildUrl("/wallet/brave", PREFIX_V3, ServerTypes::kPromotion); +} + +std::string GetRecoverWalletURL(const std::string& public_key) { + const std::string& path = base::StringPrintf( + "/wallet/recover/%s", + public_key.c_str()); + return BuildUrl(path, PREFIX_V3, ServerTypes::kPromotion); +} + +std::string GetClaimWalletURL(const std::string& payment_id) { + const std::string& path = base::StringPrintf( + "/wallet/uphold/%s/claim", + payment_id.c_str()); + return BuildUrl(path, PREFIX_V3, ServerTypes::kPromotion); +} + } // namespace braveledger_request_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h index 987fc7ab12b0..545d8309e005 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h @@ -29,6 +29,12 @@ std::string GetTransferTokens(); std::string GetBatlossURL(const std::string& payment_id, const int32_t version); +std::string GetCreateWalletURL(); + +std::string GetRecoverWalletURL(const std::string& public_key); + +std::string GetClaimWalletURL(const std::string& payment_id); + } // namespace braveledger_request_util #endif // BRAVELEDGER_COMMON_PROMOTION_REQUESTS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc index 015f36c4617e..a00c5d1f95dd 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc @@ -217,24 +217,16 @@ std::string BuildUrl( return url + prefix + path; } -std::string DigestValue(const std::string& body) { - const auto body_sha256 = braveledger_helper::Security::GetSHA256(body); - const auto body_sha256_base64 = - braveledger_helper::Security::GetBase64(body_sha256); - - return base::StringPrintf("SHA-256=%s", body_sha256_base64.c_str()); -} - std::string SignatureHeaderValue( const std::string& data, const std::string& body, const std::string key_id, const std::vector& private_key, const bool idempotency_key) { - DCHECK(!body.empty()); DCHECK(!private_key.empty()); - auto digest_header_value = DigestValue(body); + auto digest_header_value = + braveledger_helper::Security::DigestValue(body); std::vector> headers; headers.push_back({{"digest", digest_header_value}}); @@ -256,7 +248,8 @@ std::map GetSignHeaders( const std::string& key_id, const std::vector& private_key, const bool idempotency_key) { - const std::string digest_header = DigestValue(body).c_str(); + const std::string digest_header = + braveledger_helper::Security::DigestValue(body).c_str(); const std::string signature_header = SignatureHeaderValue( data, body, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h index 69e3d8ffee1f..e34edccb69e3 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h @@ -13,8 +13,8 @@ namespace braveledger_request_util { enum class ServerTypes { - LEDGER, - BALANCE, + LEDGER, // TODO remove me + BALANCE, // TODO remove me kPublisher, kPromotion, kPayments, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc index 778e1a74d565..cfb2448ee2d8 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc @@ -14,186 +14,40 @@ namespace braveledger_response_util { // Request Url: -// GET /wallet/{payment_id}/balance -// -// Success: -// OK (200) -// -// Response Format: -// { -// "altcurrency": "BAT", -// "probi": "0", -// "cardBalance": "0", -// "balance": "0.0000", -// "unconfirmed": "0.0000", -// "rates": { -// "AED": 0.864759348, -// "ARS": 16.3201969584, -// "AUD": 0.3420872568, -// "BAT": 1, -// "BCH": 0.00096277302, -// "BRL": 1.17166716, -// "BTC": 0.0000247753512, -// "BTG": 0.0267530566176, -// "CAD": 0.3193696512, -// "CHF": 0.2209298328, -// "CNY": 1.663407144, -// "DASH": 0.0030994899048, -// "DKK": 1.5428430288, -// "ETH": 0.000987728323025758, -// "EUR": 0.2069541144, -// "GBP": 0.1864519992, -// "HKD": 1.8247023792, -// "ILS": 0.8132238864, -// "INR": 17.927590572, -// "JPY": 25.1176738968, -// "KES": 25.0625197224, -// "LBA": 19.393739703459637, -// "LTC": 0.0052345069128, -// "MXN": 5.3096381712, -// "NOK": 2.2435171776, -// "NZD": 0.3647860272, -// "PHP": 11.8485109368, -// "PLN": 0.926880192, -// "SEK": 2.178867708, -// "SGD": 0.3270167424, -// "USD": 0.23624649565116654, -// "XAG": 0.0128360428272, -// "XAU": 0.00013620204, -// "XPD": 0.0001530524808, -// "XPT": 0.0002889696384, -// "XRP": 1.21298311296 -// }, -// "parameters": { -// "adFree": { -// "currency": "BAT", -// "fee": { -// "BAT": 10 -// }, -// "choices": { -// "BAT": [ -// 5, -// 10, -// 15, -// 20, -// 25, -// 50, -// 100 -// ] -// }, -// "range": { -// "BAT": [ -// 5, -// 100 -// ] -// }, -// "days": 30 -// }, -// "defaultTipChoices": [ -// "1", -// "10", -// "50" -// ], -// "defaultMonthlyChoices": [ -// "1", -// "10", -// "50" -// ] -// } -// } - -ledger::BalancePtr ParseWalletFetchBalance( - const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid payment id"); - return nullptr; - } - - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized payment id"); - return nullptr; - } - - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return nullptr; - } - - // Service Unavailable (503) - if (response.status_code == net::HTTP_SERVICE_UNAVAILABLE) { - BLOG(0, "No conversion rate yet in ratios service"); - return nullptr; - } - - if (response.status_code != net::HTTP_OK) { - return nullptr; - } - - base::Optional value = base::JSONReader::Read(response.body); - if (!value || !value->is_dict()) { - return nullptr; - } - - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - BLOG(0, "Invalid JSON"); - return nullptr; - } - - ledger::BalancePtr balance = ledger::Balance::New(); - - double total_anon = 0.0; - const auto* total = dictionary->FindStringKey("balance"); - if (total) { - const bool success = base::StringToDouble(*total, &total_anon); - if (!success) { - total_anon = 0.0; - } - } - balance->total = total_anon; - - std::string user_funds = "0"; - const auto* funds = dictionary->FindStringKey("cardBalance"); - if (funds) { - user_funds = *funds; - } - balance->user_funds = user_funds; - - return balance; -} - -// Request Url: -// GET /v2/wallet?publicKey={public_key_hex} +// POST /v3/wallet/brave // // Success: -// OK (200) +// OK (201) // // Response Format: // { -// "paymentId": +// "paymentId": "37742974-3b80-461a-acfb-937e105e5af4", +// "walletProvider": { +// "id": "", +// "name": "brave" +// }, +// "altcurrency": "BAT", +// "publicKey": "90035db3b131044c7c845bfa987946258ef4dc947ba" // } -ledger::Result ParseWalletRecoverKey( +ledger::Result ParseCreateWallet( const ledger::UrlResponse& response, std::string* payment_id) { DCHECK(payment_id); // Bad Request (400) if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Required query parameter 'publicKey' must use hex format"); + BLOG(0, "Invalid request"); return ledger::Result::LEDGER_ERROR; } - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized payment id"); - return ledger::Result::LEDGER_ERROR; + // Service Unavailable (503) + if (response.status_code == net::HTTP_SERVICE_UNAVAILABLE) { + BLOG(0, "No conversion rate yet in ratios service"); + return ledger::Result::BAD_REGISTRATION_RESPONSE; } - if (response.status_code != net::HTTP_OK) { + if (response.status_code != net::HTTP_CREATED) { return ledger::Result::LEDGER_ERROR; } @@ -209,122 +63,37 @@ ledger::Result ParseWalletRecoverKey( return ledger::Result::LEDGER_ERROR; } - const auto* payment_id_str = dictionary->FindStringKey("paymentId"); - if (!payment_id_str || payment_id_str->empty()) { - BLOG(0, "Missing payment id"); + const auto* payment_id_string = dictionary->FindStringKey("paymentId"); + if (!payment_id_string || payment_id_string->empty()) { + BLOG(1, "Payment id is wrong"); return ledger::Result::LEDGER_ERROR; } - *payment_id = *payment_id_str; + *payment_id = *payment_id_string; return ledger::Result::LEDGER_OK; } // Request Url: -// GET /v2/wallet/{recovery_id} +// GET /v3/wallet/recover/{public_key} // // Success: // OK (200) // // Response Format: // { -// "altcurrency": "BAT", -// "paymentStamp": 0, -// "httpSigningPubKey": -// "84b6a82c717e108c40f6ff18fa09e85d3993c4ed758a41053949a0e8da9f25a8", -// "rates": { -// "AED": 0.905958048, -// "ARS": 17.081127192, -// "AUD": 0.3522734456, -// "BAT": 1, -// "BCH": 0.0009752786864, -// "BRL": 1.213567456, -// "BTC": 0.0000252978648, -// "BTG": 0.026993897092, -// "CAD": 0.33037428, -// "CHF": 0.2331956536, -// "CNY": 1.7415299728, -// "DASH": 0.0031886679752, -// "DKK": 1.6197490064, -// "ETH": 0.001015345366037685, -// "EUR": 0.2172355792, -// "GBP": 0.193402756, -// "HKD": 1.911496996, -// "ILS": 0.8474698384, -// "INR": 18.6620156, -// "JPY": 26.45546964, -// "KES": 26.2795314624, -// "LBA": 19.075019334880125, -// "LTC": 0.0053489630712, -// "MXN": 5.40715038, -// "NOK": 2.301841792, -// "NZD": 0.3769695088, -// "PHP": 12.32719052, -// "PLN": 0.9668805944, -// "SEK": 2.2717344472, -// "SGD": 0.341497744, -// "USD": 0.2470464500588899, -// "XAG": 0.0135806002016, -// "XAU": 0.0001447135536, -// "XPD": 0.0001603332648, -// "XPT": 0.0003027160704, -// "XRP": 1.22896001176 -// }, -// "addresses": { -// "BAT": "0x51DA9199BE5dc5Cd322DF866a46Bf0B606f1C809", -// "BTC": "mqnyP8CCY2bNNr2etDuQGK8aMdtLiZgTqN", -// "CARD_ID": "1c8dbc44-1851-4c9e-96f4-b35d41f2984d", -// "ETH": "0x51DA9199BE5dc5Cd322DF866a46Bf0B606f1C809", -// "LTC": "myTdNu6wcMLrkok2WMq1HXPZRKPX27avUu" -// }, -// "parameters": { -// "adFree": { -// "currency": "BAT", -// "fee": { -// "BAT": 10 -// }, -// "choices": { -// "BAT": [ -// 5, -// 10, -// 15, -// 20, -// 25, -// 50, -// 100 -// ] -// }, -// "range": { -// "BAT": [ -// 5, -// 100 -// ] -// }, -// "days": 30 -// }, -// "defaultTipChoices": [ -// "1", -// "10", -// "50" -// ], -// "defaultMonthlyChoices": [ -// "1", -// "10", -// "50" -// ] -// }, -// "balance": "0.0000", -// "cardBalance": "0", -// "probi": "0", -// "unconfirmed": "0.0000" +// "paymentId": "d59d4b69-f66e-4ee8-9c88-1c522e02ffd3", +// "walletProvider": { +// "id": "a9d12d76-2b6d-4f8b-99df-bb801bff9407", +// "name": "uphold" +// }, +// "altcurrency": "BAT", +// "publicKey": "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745" // } ledger::Result ParseRecoverWallet( const ledger::UrlResponse& response, - std::string* card_id, - double* balance) { - DCHECK(card_id && balance); - + std::string* payment_id) { // Bad Request (400) if (response.status_code == net::HTTP_BAD_REQUEST) { BLOG(0, "Invalid request"); @@ -333,20 +102,8 @@ ledger::Result ParseRecoverWallet( // Not Found (404) if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized currency or payment id"); - return ledger::Result::LEDGER_ERROR; - } - - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; - } - - // Service Unavailable (503) - if (response.status_code == net::HTTP_SERVICE_UNAVAILABLE) { - BLOG(0, "No conversion rate yet in ratios service"); - return ledger::Result::LEDGER_ERROR; + BLOG(0, "Not found"); + return ledger::Result::NOT_FOUND; } if (response.status_code != net::HTTP_OK) { @@ -365,154 +122,115 @@ ledger::Result ParseRecoverWallet( return ledger::Result::LEDGER_ERROR; } - const auto* balance_str = dictionary->FindStringKey("balance"); - if (!balance_str) { - BLOG(0, "Missing balance"); - return ledger::Result::LEDGER_ERROR; - } - - const auto* card_id_str = dictionary->FindStringPath("addresses.CARD_ID"); - if (!card_id_str || card_id_str->empty()) { - BLOG(0, "Missing card id"); + const auto* payment_id_string = dictionary->FindStringKey("paymentId"); + if (!payment_id_string || payment_id_string->empty()) { + BLOG(0, "Payment id is missing"); return ledger::Result::LEDGER_ERROR; } - const bool success = base::StringToDouble(*balance_str, balance); - if (!success) { - *balance = 0.0; - } - - *card_id = *card_id_str; - + *payment_id = *payment_id_string; return ledger::Result::LEDGER_OK; } // Request Url: -// POST /v2/registrar/persona/{user_id} +// POST /v3/wallet/uphold/{payment_id}/claim // // Success: -// OK (200) +// OK (201) // // Response Format: -// { -// "wallet": { -// "paymentId": "f60c8c19-a7ef-4e3f-9810-137b7e0313bf", -// "addresses": { -// "BAT": "0x32B38C1459E86ced1B1B7e6c60FCdd309530f790", -// "BTC": "mngKw1NC5R3NEmCJAf5FuaSEXNDubBkM2t", -// "CARD_ID": "a698d76b-f5aa-42a4-bf2d-8994563c7f2f", -// "ETH": "0x32B38C1459E86ced1B1B7e6c60FCdd309530f790", -// "LTC": "mtD1hALT2ZjBjidTJVmR3W6nt569bEPRpP" -// } -// }, -// "payload": { -// "adFree": { -// "currency": "BAT", -// "fee": { -// "BAT": 10 -// }, -// "choices": { -// "BAT": [ -// 5, -// 10, -// 15, -// 20, -// 25, -// 50, -// 100 -// ] -// }, -// "range": { -// "BAT": [ -// 5, -// 100 -// ] -// }, -// "days": 30 -// }, -// "defaultTipChoices": [ -// "1", -// "10", -// "50" -// ], -// "defaultMonthlyChoices": [ -// "1", -// "10", -// "50" -// ] -// }, -// "verification": "315GcEJ/VBfh3J/NEy1tYMM7hsGorjq+ACBxdOslroH 9d+yn7vqSow\n" -// } - -ledger::Result ParseWalletRegisterPersona( - const ledger::UrlResponse& response, - std::string* payment_id, - std::string* card_id) { - DCHECK(payment_id && card_id); +// {Empty body} +ledger::Result CheckClaimWallet(const ledger::UrlResponse& response) { // Bad Request (400) if (response.status_code == net::HTTP_BAD_REQUEST) { BLOG(0, "Invalid request"); return ledger::Result::LEDGER_ERROR; } - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized registrar"); + // Forbidden (403) + if (response.status_code == net::HTTP_FORBIDDEN) { + BLOG(0, "Forbidden"); return ledger::Result::NOT_FOUND; } - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - base::Optional value = base::JSONReader::Read(response.body); - if (!value || !value->is_dict()) { - BLOG(0, "Invalid JSON"); + // Not Found (404) + if (response.status_code == net::HTTP_NOT_FOUND) { + BLOG(0, "Not found"); return ledger::Result::LEDGER_ERROR; } - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; + // Conflict (409) + if (response.status_code == net::HTTP_CONFLICT) { + BLOG(0, "Not found"); + return ledger::Result::ALREADY_EXISTS; } - const auto* payment_id_string = - dictionary->FindStringPath("wallet.paymentId"); - if (!payment_id_string || payment_id_string->empty()) { - BLOG(0, "Missing payment id"); + // Internal Server Error (500) + if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Internal server error"); return ledger::Result::LEDGER_ERROR; } - const auto* card_id_string = - dictionary->FindStringPath("wallet.addresses.CARD_ID"); - if (!card_id_string || card_id_string->empty()) { - BLOG(0, "Missing card id"); + if (response.status_code != net::HTTP_CREATED) { return ledger::Result::LEDGER_ERROR; } - *payment_id = *payment_id_string; - *card_id = *card_id_string; - return ledger::Result::LEDGER_OK; } // Request Url: -// GET /v2/registrar/persona +// GET /wallet/{payment_id}/balance // // Success: // OK (200) // // Response Format: // { -// "payload": { +// "altcurrency": "BAT", +// "probi": "0", +// "cardBalance": "0", +// "balance": "0.0000", +// "unconfirmed": "0.0000", +// "rates": { +// "AED": 0.864759348, +// "ARS": 16.3201969584, +// "AUD": 0.3420872568, +// "BAT": 1, +// "BCH": 0.00096277302, +// "BRL": 1.17166716, +// "BTC": 0.0000247753512, +// "BTG": 0.0267530566176, +// "CAD": 0.3193696512, +// "CHF": 0.2209298328, +// "CNY": 1.663407144, +// "DASH": 0.0030994899048, +// "DKK": 1.5428430288, +// "ETH": 0.000987728323025758, +// "EUR": 0.2069541144, +// "GBP": 0.1864519992, +// "HKD": 1.8247023792, +// "ILS": 0.8132238864, +// "INR": 17.927590572, +// "JPY": 25.1176738968, +// "KES": 25.0625197224, +// "LBA": 19.393739703459637, +// "LTC": 0.0052345069128, +// "MXN": 5.3096381712, +// "NOK": 2.2435171776, +// "NZD": 0.3647860272, +// "PHP": 11.8485109368, +// "PLN": 0.926880192, +// "SEK": 2.178867708, +// "SGD": 0.3270167424, +// "USD": 0.23624649565116654, +// "XAG": 0.0128360428272, +// "XAU": 0.00013620204, +// "XPD": 0.0001530524808, +// "XPT": 0.0002889696384, +// "XRP": 1.21298311296 +// }, +// "parameters": { // "adFree": { // "currency": "BAT", // "fee": { @@ -547,87 +265,70 @@ ledger::Result ParseWalletRegisterPersona( // "10", // "50" // ] -// }, -// "registrarVK": "==========ANONLOGIN_VK_BEG======= ..." +// } // } -ledger::Result CheckWalletRequestCredentials( - const ledger::UrlResponse& response) { +ledger::BalancePtr ParseWalletFetchBalance( + const ledger::UrlResponse& response) { // Bad Request (400) if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid registrar type"); - return ledger::Result::LEDGER_ERROR; + BLOG(0, "Invalid payment id"); + return nullptr; } // Not Found (404) if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized registrar"); - return ledger::Result::LEDGER_ERROR; + BLOG(0, "Unrecognized payment id"); + return nullptr; } // Internal Server Error (500) if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; + return nullptr; } - if (response.status_code != net::HTTP_OK) { - return ledger::Result::BAD_REGISTRATION_RESPONSE; + // Service Unavailable (503) + if (response.status_code == net::HTTP_SERVICE_UNAVAILABLE) { + BLOG(0, "No conversion rate yet in ratios service"); + return nullptr; } - return ledger::Result::LEDGER_OK; -} - -// Request Url: -// GET /v2/wallet/{payment_id}/claim -// -// Success: -// OK (200) -// -// Format Response (error): -// { -// "statusCode": 500, -// "error": "Internal Server Error", -// "message": "An internal server error occurred" -// } - -ledger::Result CheckTransferAnonToExternalWallet( - const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; + if (response.status_code != net::HTTP_OK) { + return nullptr; } - // Forbidden (403) - if (response.status_code == net::HTTP_FORBIDDEN) { - BLOG(0, "Invalid card or providerLinkingId"); - return ledger::Result::LEDGER_ERROR; + base::Optional value = base::JSONReader::Read(response.body); + if (!value || !value->is_dict()) { + return nullptr; } - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized payment id"); - return ledger::Result::LEDGER_ERROR; + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return nullptr; } - // Conflict (409) - if (response.status_code == net::HTTP_CONFLICT) { - BLOG(0, "Maximum member associations or other conflict"); - return ledger::Result::ALREADY_EXISTS; - } + ledger::BalancePtr balance = ledger::Balance::New(); - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; + double total_anon = 0.0; + const auto* total = dictionary->FindStringKey("balance"); + if (total) { + const bool success = base::StringToDouble(*total, &total_anon); + if (!success) { + total_anon = 0.0; + } } + balance->total = total_anon; - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; + std::string user_funds = "0"; + const auto* funds = dictionary->FindStringKey("cardBalance"); + if (funds) { + user_funds = *funds; } + balance->user_funds = user_funds; - return ledger::Result::LEDGER_OK; + return balance; } } // namespace braveledger_response_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h index 30fb7b776575..9701534b856c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h @@ -12,27 +12,17 @@ namespace braveledger_response_util { -ledger::BalancePtr ParseWalletFetchBalance(const ledger::UrlResponse& response); - -ledger::Result ParseWalletRecoverKey( +ledger::Result ParseCreateWallet( const ledger::UrlResponse& response, std::string* payment_id); ledger::Result ParseRecoverWallet( const ledger::UrlResponse& response, - std::string* card_id, - double* balance); - -ledger::Result ParseWalletRegisterPersona( - const ledger::UrlResponse& response, - std::string* payment_id, - std::string* card_id); + std::string* payment_id); -ledger::Result CheckWalletRequestCredentials( - const ledger::UrlResponse& response); +ledger::Result CheckClaimWallet(const ledger::UrlResponse& response); -ledger::Result CheckTransferAnonToExternalWallet( - const ledger::UrlResponse& response); +ledger::BalancePtr ParseWalletFetchBalance(const ledger::UrlResponse& response); } // namespace braveledger_response_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_keys.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_keys.h index 5dc09756260c..dff8c2a3d49f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_keys.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_keys.h @@ -29,7 +29,6 @@ namespace ledger { const char kStateAutoContributeAmount[] = "ac.amount"; const char kStateNextReconcileStamp[] = "ac.next_reconcile_stamp"; const char kStateCreationStamp[] = "creation_stamp"; - const char kStateAnonymousCardId[] = "wallet.anonymous_card_id"; const char kStateRecoverySeed[] = "wallet.seed"; const char kStatePaymentId[] = "wallet.payment_id"; const char kStateInlineTipRedditEnabled[] = "inline_tip.reddit"; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_migration_v2.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_migration_v2.cc index cd8a2f388b53..a0d8e85418f2 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_migration_v2.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_migration_v2.cc @@ -70,10 +70,6 @@ void StateMigrationV2::OnLoadState( ledger::kStateCreationStamp, legacy_state_->GetCreationStamp()); - ledger_->SetStringState( - ledger::kStateAnonymousCardId, - legacy_state_->GetCardIdAddress()); - const auto seed = legacy_state_->GetRecoverySeed(); ledger_->SetStringState( ledger::kStateRecoverySeed, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.cc index e42e1385d81d..c80da89911f3 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.cc @@ -204,18 +204,6 @@ void SetCreationStamp(bat_ledger::LedgerImpl* ledger, const uint64_t stamp) { ledger->SetUint64State(ledger::kStateCreationStamp, stamp); } -std::string GetAnonymousCardId(bat_ledger::LedgerImpl* ledger) { - DCHECK(ledger); - return ledger->GetStringState(ledger::kStateAnonymousCardId); -} - -void SetAnonymousCardId( - bat_ledger::LedgerImpl* ledger, - const std::string& id) { - DCHECK(ledger); - ledger->SetStringState(ledger::kStateAnonymousCardId, id); -} - std::vector GetRecoverySeed(bat_ledger::LedgerImpl* ledger) { DCHECK(ledger); const std::string& seed = ledger->GetStringState(ledger::kStateRecoverySeed); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.h index 0efe2c1af0c5..6d2dff055378 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_util.h @@ -74,12 +74,6 @@ uint64_t GetCreationStamp(bat_ledger::LedgerImpl* ledger); void SetCreationStamp(bat_ledger::LedgerImpl* ledger, const uint64_t stamp); -std::string GetAnonymousCardId(bat_ledger::LedgerImpl* ledger); - -void SetAnonymousCardId( - bat_ledger::LedgerImpl* ledger, - const std::string& id); - std::vector GetRecoverySeed(bat_ledger::LedgerImpl* ledger); void SetRecoverySeed( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h b/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h index f3c3c4837672..eefdc3489e9a 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h @@ -15,30 +15,9 @@ #define PREFIX_V3 "/v3" #define PREFIX_V4 "/v4" #define PREFIX_V5 "/v5" -#define REGISTER_PERSONA "/registrar/persona" -#define RECOVER_WALLET_PUBLIC_KEY "/wallet?publicKey=" -#define GET_PROMOTION_CAPTCHA "/captchas/" -#define GET_PROMOTION_ATTESTATION "/attestations/" - -#define REGISTRARVK_FIELDNAME "registrarVK" -#define VERIFICATION_FIELDNAME "verification" -#define SURVEYOR_ID "surveyorId" -#define SURVEYOR_IDS "surveyorIds" - -#define LEDGER_CURRENCY "BAT" #define SIGNATURE_ALGORITHM "ed25519" -#define LEDGER_STATE_FILENAME "6e16793f-52e1-41fb-b6a2-24b99b47e8f8" -#define LEDGER_PUBLISHER_STATE_FILENAME "ee1e6705-bc4f-4aba-b03c-57cc8cb2ae4d" -#define PUBLISHERS_DB_NAME "d2c799cd-f37f-4230-9a04-ca23ba5be240" -#define MEDIA_CACHE_DB_NAME "9956db89-9105-420b-9ad4-49348bc536af" - -// TODO(samartnik): remove as soon as we move on new safetynet check API -#define SAFETYNET_ERROR_MESSAGE \ -"Error profile and integrity must both be true" -#define SAFETYNET_ERROR_CODE 422 - #define YOUTUBE_MEDIA_TYPE "youtube" #define TWITCH_MEDIA_TYPE "twitch" #define TWITTER_MEDIA_TYPE "twitter" @@ -58,29 +37,12 @@ #define REDDIT_USER_URL "https://www.reddit.com/user/" #define OLD_REDDIT_DOMAIN "old.reddit.com" #define MEDIA_DELIMITER "_" -#define WALLET_PASSPHRASE_DELIM " " -#define DICTIONARY_DELIMITER "," -#define NICEWARE_BYTES_WRITTEN 32 - -#define SEED_LENGTH 32 -#define SALT_LENGTH 64 - -#define INVALID_LEGACY_WALLET -1 #define TWITCH_MINIMUM_SECONDS 10 #define TWITCH_MAXIMUM_SECONDS_CHUNK 120 -#define VOTE_BATCH_SIZE 10 - namespace braveledger_ledger { -static const uint8_t g_hkdfSalt[] = { - 126, 244, 99, 158, 51, 68, 253, 80, 133, 183, 51, 180, 77, - 62, 74, 252, 62, 106, 96, 125, 241, 110, 134, 87, 190, 208, - 158, 84, 125, 69, 246, 207, 162, 247, 107, 172, 37, 34, 53, - 246, 105, 20, 215, 5, 248, 154, 179, 191, 46, 17, 6, 72, 210, - 91, 10, 169, 145, 248, 22, 147, 117, 24, 105, 12}; - static const uint64_t _default_min_page_time_before_logging_a_visit = 8; static const uint64_t _milliseconds_day = 24 * 60 * 60 * 1000; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/test/niceware_partial_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/test/niceware_partial_unittest.cc deleted file mode 100644 index 676203fb01e7..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/test/niceware_partial_unittest.cc +++ /dev/null @@ -1,204 +0,0 @@ -/* 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 http://mozilla.org/MPL/2.0/. */ - -#include "base/strings/string_split.h" -#include "brave/components/brave_rewards/resources/grit/brave_rewards_resources.h" -#include "bat/ledger/internal/bat_helper.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/resource/resource_bundle.h" - -// npm run test -- brave_unit_tests --filter=NicewarePartialUnitTest.* - -std::string getHexBytes(std::vector seed) { - return braveledger_bat_helper::uint8ToHex(seed); -} - -TEST(NicewarePartialUnitTest, InvalidNumberOfWords) { - // != 16 words - const std::string& passPhrase = "rickshaw fleecy handwrote" - " diurnal coarsest rose outreasoning coined jowly" - " undefiled parched kielbasa decapitate ninetales"; - std::vector nSeed; - size_t written = 0; - // get wordlist - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result != 0 && written == 0); -} - -TEST(NicewarePartialUnitTest, InvalidWordInList) { - // contains a word not in the list - ninetales - const std::string& passPhrase = "sherlock rickshaw fleecy handwrote" - " diurnal coarsest rose outreasoning coined jowly" - " undefiled parched kielbasa decapitate ninetales" - " vermonter"; - std::vector nSeed; - size_t written = 0; - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result != 0 && written == 0); -} - -TEST(NicewarePartialUnitTest, ValidWordListPassOne) { - const std::string& passPhrase = "sherlock rickshaw fleecy handwrote" - " diurnal coarsest rose outreasoning coined jowly undefiled parched" - " kielbasa decapitate throughout vermonter"; - std::vector nSeed; - size_t written = 0; - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result == 0 && getHexBytes(nSeed) == - "c874bcc95057603c3ce024babe889753258a74aaec759bcb7641330ee251f549"); -} - -TEST(NicewarePartialUnitTest, ValidWordListPassTwo) { - const std::string& passPhrase = "unskillfully robber quadraphonic" - " horsed breviary punish beta wrapper whale betokened" - " calix cableway combatted jury palliate senegalese"; - std::vector nSeed; - size_t written = 0; - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result == 0 && getHexBytes(nSeed) == - "f14ebdc3ae2965ee1728ad2910aefdeafa4e10be1b2f1a822644753e9ab7c62b"); -} - -TEST(NicewarePartialUnitTest, ValidWordListPassThree) { - const std::string& passPhrase = "hemline crumby foothill sui" - " vaporizing permutational pakistan rattish maturational" - " beading bucketing nonzebra religiosity ridable amazement" - " peening"; - std::vector nSeed; - size_t written = 0; - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result == 0 && getHexBytes(nSeed) == - "62c62f615234d9f4f4319f4f9a82b12d82d50e5b188791b4b786bcd203f19de7"); -} - -TEST(NicewarePartialUnitTest, ValidWordListPassFour) { - const std::string& passPhrase = "A"; - std::vector nSeed; - size_t written = 0; - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result == 0 && getHexBytes(nSeed) == "0000"); -} - -TEST(NicewarePartialUnitTest, ValidWordListPassFive) { - const std::string& passPhrase = "zyzzyva"; - std::vector nSeed; - size_t written = 0; - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result == 0 && getHexBytes(nSeed) == "ffff"); -} - -TEST(NicewarePartialUnitTest, ValidWordListPassSix) { - const std::string& passPhrase = "A bioengineering Balloted gobbledegooK" - " cReneled Written depriving zyzzyva"; - std::vector nSeed; - size_t written = 0; - const std::string word_list = - ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); - auto data_split = base::SplitString( - word_list, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - int result = braveledger_bat_helper::niceware_mnemonic_to_bytes( - passPhrase, - &nSeed, - &written, - data_split); - - ASSERT_TRUE(result == 0 && getHexBytes(nSeed) == - "000011d40c8c5af72e53fe3c36a9ffff"); -} diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.cc index 987739a558bc..b36c69439422 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.cc @@ -196,19 +196,7 @@ void Uphold::WalletAuthorization( authorization_->Authorize(args, callback); } -void Uphold::TransferAnonToExternalWallet( - ledger::ExternalWalletCallback callback) { - auto transfer_callback = std::bind( - &Uphold::OnTransferAnonToExternalWalletCallback, - this, - _1, - callback); - - // transfer funds from anon wallet to uphold - ledger_->TransferAnonToExternalWallet(transfer_callback); -} - -void Uphold::GenerateExternalWallet(ledger::ExternalWalletCallback callback) { +void Uphold::GenerateExternalWallet(ledger::ResultCallback callback) { wallet_->Generate(callback); } @@ -216,20 +204,6 @@ void Uphold::CreateCard(CreateCardCallback callback) { card_->CreateIfNecessary(callback); } -void Uphold::OnTransferAnonToExternalWalletCallback( - const ledger::Result result, - ledger::ExternalWalletCallback callback) { - auto wallets = ledger_->GetExternalWallets(); - auto wallet_ptr = GetWallet(std::move(wallets)); - if (result == ledger::Result::LEDGER_OK || - result == ledger::Result::ALREADY_EXISTS) { - wallet_ptr->transferred = true; - ledger_->SaveExternalWallet(ledger::kWalletUphold, wallet_ptr->Clone()); - } - - callback(ledger::Result::LEDGER_OK, std::move(wallet_ptr)); -} - void Uphold::DisconnectWallet() { BLOG(1, "Disconnecting wallet"); auto wallets = ledger_->GetExternalWallets(); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.h b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.h index 95ad3a3a5395..ba73977975be 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.h @@ -61,9 +61,7 @@ class Uphold { const std::map& args, ledger::ExternalWalletAuthorizationCallback callback); - void TransferAnonToExternalWallet(ledger::ExternalWalletCallback callback); - - void GenerateExternalWallet(ledger::ExternalWalletCallback callback); + void GenerateExternalWallet(ledger::ResultCallback callback); void CreateCard(CreateCardCallback callback); @@ -88,10 +86,6 @@ class Uphold { const ledger::UrlResponse& response, FetchBalanceCallback callback); - void OnTransferAnonToExternalWalletCallback( - const ledger::Result result, - ledger::ExternalWalletCallback callback); - void SaveTransferFee(ledger::TransferFeePtr transfer_fee); void OnTransferFeeCompleted( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.cc index 90a44c305e7e..d77c75cdd608 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.cc @@ -25,7 +25,7 @@ UpholdWallet::UpholdWallet(bat_ledger::LedgerImpl* ledger, Uphold* uphold) : UpholdWallet::~UpholdWallet() = default; -void UpholdWallet::Generate(ledger::ExternalWalletCallback callback) { +void UpholdWallet::Generate(ledger::ResultCallback callback) { auto wallets = ledger_->GetExternalWallets(); ledger::ExternalWalletPtr wallet; if (wallets.empty()) { @@ -67,30 +67,30 @@ void UpholdWallet::Generate(ledger::ExternalWalletCallback callback) { return; } - callback(ledger::Result::LEDGER_OK, std::move(wallet)); + callback(ledger::Result::LEDGER_OK); } void UpholdWallet::OnGenerate( const ledger::Result result, const User& user, - ledger::ExternalWalletCallback callback) { + ledger::ResultCallback callback) { auto wallets = ledger_->GetExternalWallets(); auto wallet_ptr = GetWallet(std::move(wallets)); if (result == ledger::Result::EXPIRED_TOKEN) { uphold_->DisconnectWallet(); - callback(result, std::move(wallet_ptr)); + callback(result); return; } if (user.bat_not_allowed) { BLOG(0, "BAT not allowed"); - callback(ledger::Result::BAT_NOT_ALLOWED, std::move(wallet_ptr)); + callback(ledger::Result::BAT_NOT_ALLOWED); return; } if (!wallet_ptr || result != ledger::Result::LEDGER_OK) { BLOG(0, "Wallet not generated"); - callback(result, std::move(wallet_ptr)); + callback(result); return; } @@ -114,23 +114,22 @@ void UpholdWallet::OnGenerate( } if (user.verified) { - ledger_->TransferTokens([](const ledger::Result){}); - uphold_->TransferAnonToExternalWallet(callback); + ledger_->ClaimFunds(callback); return; } - callback(ledger::Result::LEDGER_OK, std::move(wallet_ptr)); + callback(ledger::Result::LEDGER_OK); } void UpholdWallet::OnCreateCard( const ledger::Result result, const std::string& address, - ledger::ExternalWalletCallback callback) { + ledger::ResultCallback callback) { auto wallets = ledger_->GetExternalWallets(); auto wallet_ptr = GetWallet(std::move(wallets)); if (result != ledger::Result::LEDGER_OK || !wallet_ptr) { BLOG(0, "Card not created"); - callback(result, std::move(wallet_ptr)); + callback(result); return; } @@ -139,12 +138,11 @@ void UpholdWallet::OnCreateCard( ledger_->SaveExternalWallet(ledger::kWalletUphold, wallet_ptr->Clone()); if (wallet_ptr->status == ledger::WalletStatus::VERIFIED) { - ledger_->TransferTokens([](const ledger::Result){}); - uphold_->TransferAnonToExternalWallet(callback); + ledger_->ClaimFunds(callback); return; } - callback(ledger::Result::LEDGER_OK, std::move(wallet_ptr)); + callback(ledger::Result::LEDGER_OK); } ledger::WalletStatus UpholdWallet::GetNewStatus( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.h index fd9ae5b6ced5..c529a0960796 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_wallet.h @@ -23,18 +23,18 @@ class UpholdWallet { ~UpholdWallet(); - void Generate(ledger::ExternalWalletCallback callback); + void Generate(ledger::ResultCallback callback); private: void OnGenerate( const ledger::Result result, const User& user, - ledger::ExternalWalletCallback callback); + ledger::ResultCallback callback); void OnCreateCard( const ledger::Result result, const std::string& address, - ledger::ExternalWalletCallback callback); + ledger::ResultCallback callback); ledger::WalletStatus GetNewStatus( const ledger::WalletStatus old_status, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc index b9b493e20b75..6cc3455aeab3 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc @@ -8,33 +8,16 @@ #include #include -#include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "base/strings/stringprintf.h" #include "base/values.h" #include "bat/ledger/global_constants.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/legacy/unsigned_tx_properties.h" -#include "bat/ledger/internal/legacy/unsigned_tx_state.h" -#include "bat/ledger/internal/legacy/wallet_info_properties.h" -#include "bat/ledger/internal/request/request_util.h" -#include "bat/ledger/internal/response/response_wallet.h" #include "bat/ledger/internal/state/state_keys.h" #include "bat/ledger/internal/state/state_util.h" #include "bat/ledger/internal/uphold/uphold.h" -#include "bat/ledger/internal/uphold/uphold_util.h" -#include "bat/ledger/internal/wallet/wallet_balance.h" -#include "bat/ledger/internal/wallet/wallet_create.h" -#include "bat/ledger/internal/wallet/wallet_recover.h" #include "bat/ledger/internal/wallet/wallet_util.h" #include "wally_bip39.h" // NOLINT -using std::placeholders::_1; -using std::placeholders::_2; -using std::placeholders::_3; - namespace braveledger_wallet { Wallet::Wallet(bat_ledger::LedgerImpl* ledger) : @@ -42,52 +25,55 @@ Wallet::Wallet(bat_ledger::LedgerImpl* ledger) : create_(std::make_unique(ledger)), recover_(std::make_unique(ledger)), balance_(std::make_unique(ledger)), + claim_(std::make_unique(ledger)), uphold_(std::make_unique(ledger)) { } -Wallet::~Wallet() { -} +Wallet::~Wallet() = default; void Wallet::CreateWalletIfNecessary(ledger::ResultCallback callback) { - const auto payment_id = ledger_->GetPaymentId(); - const auto stamp = ledger_->GetCreationStamp(); - - if (!payment_id.empty() && stamp != 0) { - BLOG(1, "Wallet already exists"); - callback(ledger::Result::WALLET_CREATED); - return; - } - create_->Start(std::move(callback)); } std::string Wallet::GetWalletPassphrase() const { const auto seed = braveledger_state::GetRecoverySeed(ledger_); - std::string passPhrase; - if (seed.size() == 0) { - return passPhrase; + std::string pass_phrase; + if (seed.empty()) { + BLOG(0, "Seed is empty"); + return pass_phrase; } char* words = nullptr; - int result = bip39_mnemonic_from_bytes(nullptr, - &seed.front(), - seed.size(), - &words); - if (result != 0) { - DCHECK(false); + const int result = bip39_mnemonic_from_bytes( + nullptr, + &seed.front(), + seed.size(), + &words); - return passPhrase; + if (result != 0) { + BLOG(0, "Bip39 failed: " << result); + NOTREACHED(); + return pass_phrase; } - passPhrase = words; + + pass_phrase = words; wally_free_string(words); - return passPhrase; + return pass_phrase; } void Wallet::RecoverWallet( const std::string& pass_phrase, - ledger::RecoverWalletCallback callback) { - recover_->Start(pass_phrase, std::move(callback)); + ledger::ResultCallback callback) { + recover_->Start( + pass_phrase, + [this, callback](const ledger::Result result) { + if (result == ledger::Result::LEDGER_OK) { + DisconnectAllWallets(callback); + return; + } + callback(result); + }); } void Wallet::FetchBalance(ledger::FetchBalanceCallback callback) { @@ -98,10 +84,22 @@ void Wallet::GetExternalWallet( const std::string& wallet_type, ledger::ExternalWalletCallback callback) { if (wallet_type == ledger::kWalletUphold) { - uphold_->GenerateExternalWallet(callback); + uphold_->GenerateExternalWallet( + [this, callback, wallet_type](const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK && + result != ledger::Result::CONTINUE) { + callback(result, nullptr); + return; + } + + auto wallets = ledger_->GetExternalWallets(); + auto wallet = GetWallet(wallet_type, std::move(wallets)); + callback(ledger::Result::LEDGER_OK, std::move(wallet)); + }); return; } + NOTREACHED(); callback(ledger::Result::LEDGER_ERROR, nullptr); } @@ -119,7 +117,11 @@ void Wallet::ExternalWalletAuthorization( if (wallet_type == ledger::kWalletUphold) { uphold_->WalletAuthorization(args, callback); + return; } + + NOTREACHED(); + callback(ledger::Result::LEDGER_ERROR, {}); } void Wallet::DisconnectWallet( @@ -142,205 +144,35 @@ void Wallet::DisconnectWallet( } wallet_ptr = ResetWallet(std::move(wallet_ptr)); - ledger_->SaveExternalWallet(wallet_type, std::move(wallet_ptr)); callback(ledger::Result::LEDGER_OK); } -void Wallet::OnTransferAnonToExternalWallet( - const ledger::UrlResponse& response, - ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckTransferAnonToExternalWallet(response); - - callback(result); -} - -void Wallet::TransferAnonToExternalWallet( - const bool allow_zero_balance, - ledger::ResultCallback callback) { - FetchBalance(std::bind(&Wallet::OnTransferAnonToExternalWalletBalance, - this, - _1, - _2, - allow_zero_balance, - callback)); -} - -void Wallet::OnTransferAnonToExternalWalletBalance( - ledger::Result result, - ledger::BalancePtr properties, - const bool allow_zero_balance, - ledger::ResultCallback callback) { - if (result != ledger::Result::LEDGER_OK || !properties) { - BLOG(0, "Anon funds transfer failed"); - callback(ledger::Result::LEDGER_ERROR); - return; - } - - if (!allow_zero_balance && properties->user_funds == "0") { - BLOG(0, "Zero balance not allowed"); - callback(ledger::Result::LEDGER_ERROR); - return; - } - - auto wallets = ledger_->GetExternalWallets(); - auto wallet_ptr = braveledger_uphold::GetWallet(std::move(wallets)); - - if (!wallet_ptr) { - BLOG(0, "Wallet is null"); - callback(ledger::Result::LEDGER_ERROR); - return; - } - - if (!wallet_ptr->anon_address.empty()) { - BLOG(1, "Anon address already exists"); - OnTransferAnonToExternalWalletAddress( - ledger::Result::ALREADY_EXISTS, - properties->user_funds, - callback); - return; - } - - auto anon_callback = - std::bind(&Wallet::OnTransferAnonToExternalWalletAddress, - this, - _1, - properties->user_funds, - callback); - - uphold_->CreateAnonAddressIfNecessary(anon_callback); -} - -std::string Wallet::GetClaimPayload( - const std::string& user_funds, - const std::string& address, - const std::string& anon_address) { - ledger::UnsignedTxProperties unsigned_tx; - unsigned_tx.amount = user_funds; - if (unsigned_tx.amount.empty()) { - unsigned_tx.amount = "0"; - } - unsigned_tx.currency = "BAT"; - unsigned_tx.destination = address; - const ledger::UnsignedTxState unsigned_tx_state; - const std::string octets = unsigned_tx_state.ToJson(unsigned_tx); - - std::string header_digest = "SHA-256=" + - braveledger_bat_helper::getBase64( - braveledger_bat_helper::getSHA256(octets)); - - std::vector header_keys; - header_keys.push_back("digest"); - std::vector header_values; - header_values.push_back(header_digest); - - const auto seed = braveledger_state::GetRecoverySeed(ledger_); - std::vector secret_key = braveledger_bat_helper::getHKDF(seed); - std::vector public_key; - std::vector new_secret_key; - bool success = braveledger_bat_helper::getPublicKeyFromSeed( - secret_key, - &public_key, - &new_secret_key); - if (!success) { - return ""; - } - - std::string header_signature = braveledger_bat_helper::sign( - header_keys, - header_values, - "primary", - new_secret_key); - - base::Value payload(base::Value::Type::DICTIONARY); - - base::Value signed_tx(base::Value::Type::DICTIONARY); - signed_tx.SetStringKey("octets", octets); - - base::Value denomination(base::Value::Type::DICTIONARY); - denomination.SetStringKey("amount", unsigned_tx.amount); - denomination.SetStringKey("currency", unsigned_tx.currency); - - base::Value body(base::Value::Type::DICTIONARY); - body.SetStringKey("destination", address); - body.SetKey("denomination", std::move(denomination)); - signed_tx.SetKey("body", std::move(body)); - - base::Value headers(base::Value::Type::DICTIONARY); - headers.SetStringKey("digest", header_digest); - headers.SetStringKey("signature", header_signature); - signed_tx.SetKey("headers", std::move(headers)); - - payload.SetKey("signedTx", std::move(signed_tx)); - payload.SetStringKey("anonymousAddress", anon_address); - - std::string json; - base::JSONWriter::Write(payload, &json); - - return json; -} - -void Wallet::OnTransferAnonToExternalWalletAddress( - ledger::Result result, - const std::string& user_funds, - ledger::ResultCallback callback) { - auto wallets = ledger_->GetExternalWallets(); - auto wallet_ptr = braveledger_uphold::GetWallet(std::move(wallets)); - if (!wallet_ptr) { - BLOG(0, "Wallet is null"); - callback(ledger::Result::LEDGER_ERROR); - return; - } - - if ((result != ledger::Result::LEDGER_OK && - result != ledger::Result::ALREADY_EXISTS) - || wallet_ptr->anon_address.empty()) { - BLOG(0, "Anon funds transfer failed"); - callback(ledger::Result::LEDGER_ERROR); - return; - } - - const std::string path = base::StringPrintf( - "/wallet/%s/claim", - ledger_->GetPaymentId().c_str()); - - const std::string url = braveledger_request_util::BuildUrl( - path, - PREFIX_V2); - - auto transfer_callback = std::bind(&Wallet::OnTransferAnonToExternalWallet, - this, - _1, - callback); - - const std::string payload = GetClaimPayload( - user_funds, - wallet_ptr->address, - wallet_ptr->anon_address); - - if (payload.empty()) { - BLOG(0, "Payload is empty"); - callback(ledger::Result::LEDGER_ERROR); - return; - } +void Wallet::ClaimFunds(ledger::ResultCallback callback) { + // Anonymous funds claim + claim_->Start([this, callback](const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK && + result != ledger::Result::ALREADY_EXISTS) { + BLOG(0, "Claiming anon funds failed"); + callback(ledger::Result::CONTINUE); + return; + } - std::vector wallet_header; - wallet_header.push_back("Content-Type: application/json; charset=UTF-8"); + // tokens claim + ledger_->TransferTokens([callback](const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(0, "Claiming tokens failed"); + callback(ledger::Result::CONTINUE); + return; + } - ledger_->LoadURL( - url, - wallet_header, - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - transfer_callback); + callback(ledger::Result::LEDGER_OK); + }); + }); } void Wallet::GetAnonWalletStatus(ledger::ResultCallback callback) { - const std::string payment_id = ledger_->GetPaymentId(); + const std::string payment_id = braveledger_state::GetPaymentId(ledger_); const std::string passphrase = GetWalletPassphrase(); const uint64_t stamp = ledger_->GetCreationStamp(); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h index 001537bc208b..c0e6a580c2d6 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h @@ -11,50 +11,37 @@ #include #include #include -#include +#include "bat/ledger/internal/wallet/wallet_balance.h" +#include "bat/ledger/internal/wallet/wallet_claim.h" +#include "bat/ledger/internal/wallet/wallet_create.h" +#include "bat/ledger/internal/wallet/wallet_recover.h" #include "bat/ledger/ledger.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_wallet { -class Create; -} - -namespace braveledger_wallet { -class Recover; -} - -namespace braveledger_wallet { -class Balance; -} - -namespace braveledger_uphold { -class Uphold; -} - namespace braveledger_wallet { class Wallet { public: explicit Wallet(bat_ledger::LedgerImpl* ledger); - ~Wallet(); void CreateWalletIfNecessary(ledger::ResultCallback callback); void RecoverWallet( const std::string& pass_phrase, - ledger::RecoverWalletCallback callback); + ledger::ResultCallback callback); std::string GetWalletPassphrase() const; void FetchBalance(ledger::FetchBalanceCallback callback); - void GetExternalWallet(const std::string& wallet_type, - ledger::ExternalWalletCallback callback); + void GetExternalWallet( + const std::string& wallet_type, + ledger::ExternalWalletCallback callback); void ExternalWalletAuthorization( const std::string& wallet_type, @@ -65,39 +52,18 @@ class Wallet { const std::string& wallet_type, ledger::ResultCallback callback); - void TransferAnonToExternalWallet( - const bool allow_zero_balance, - ledger::ResultCallback callback); + void ClaimFunds(ledger::ResultCallback callback); void GetAnonWalletStatus(ledger::ResultCallback callback); void DisconnectAllWallets(ledger::ResultCallback callback); private: - void OnTransferAnonToExternalWallet( - const ledger::UrlResponse& response, - ledger::ResultCallback callback); - - void OnTransferAnonToExternalWalletBalance( - ledger::Result result, - ledger::BalancePtr properties, - const bool allow_zero_balance, - ledger::ResultCallback callback); - - std::string GetClaimPayload( - const std::string& user_funds, - const std::string& address, - const std::string& anon_address); - - void OnTransferAnonToExternalWalletAddress( - ledger::Result result, - const std::string& user_funds, - ledger::ResultCallback callback); - bat_ledger::LedgerImpl* ledger_; // NOT OWNED std::unique_ptr create_; std::unique_ptr recover_; std::unique_ptr balance_; + std::unique_ptr claim_; std::unique_ptr uphold_; }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc index 15332f7f0503..dbea2f9dc2a6 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc @@ -38,13 +38,13 @@ void WalletBalance::Fetch(ledger::FetchBalanceCallback callback) { // if we don't have user funds in anon card anymore // we can skip balance server ping if (!braveledger_state::GetFetchOldBalanceEnabled(ledger_)) { - auto balance = ledger::WalletBalance::New(); + auto balance = ledger::Balance::New(); balance->user_funds = "0"; GetUnblindedTokens(std::move(balance), callback); return; } - std::string payment_id = ledger_->GetPaymentId(); + const std::string payment_id = braveledger_state::GetPaymentId(ledger_); std::string path = base::StringPrintf( "/wallet/%s/balance", @@ -106,7 +106,7 @@ void WalletBalance::OnGetUnblindedTokens( ledger::Balance info, ledger::FetchBalanceCallback callback, ledger::UnblindedTokenList list) { - auto info_ptr = ledger::WalletBalance::New(info); + auto info_ptr = ledger::Balance::New(info); double total = 0.0; for (auto & item : list) { total+=item->value; @@ -146,7 +146,7 @@ void WalletBalance::OnUpholdFetchBalance(ledger::Balance info, ledger::FetchBalanceCallback callback, ledger::Result result, double balance) { - ledger::BalancePtr info_ptr = ledger::WalletBalance::New(info); + ledger::BalancePtr info_ptr = ledger::Balance::New(info); if (result == ledger::Result::LEDGER_ERROR) { BLOG(0, "Can't get uphold balance"); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h index ce6729792e35..f75ad6c2fa94 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h @@ -53,10 +53,11 @@ class WalletBalance { ledger::BalancePtr balance, ledger::FetchBalanceCallback callback); - void OnUpholdFetchBalance(ledger::Balance info, - ledger::FetchBalanceCallback callback, - ledger::Result result, - double balance); + void OnUpholdFetchBalance( + ledger::Balance info, + ledger::FetchBalanceCallback callback, + const ledger::Result result, + const double balance); std::unique_ptr uphold_; bat_ledger::LedgerImpl* ledger_; // NOT OWNED diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc new file mode 100644 index 000000000000..a217744a52cf --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc @@ -0,0 +1,210 @@ +/* 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 http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/wallet/wallet_claim.h" + +#include +#include +#include + +#include "base/base64.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "base/values.h" +#include "bat/ledger/internal/common/security_helper.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_promotion.h" +#include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/response/response_wallet.h" +#include "bat/ledger/internal/state/state_keys.h" +#include "bat/ledger/internal/state/state_util.h" +#include "bat/ledger/internal/uphold/uphold_util.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace { + +std::string GeneratePayload( + const std::string& user_funds, + const std::string& address, + const std::string& anon_address, + const std::vector& seed) { + const std::string amount = user_funds.empty() ? "0" : user_funds; + + base::Value denomination(base::Value::Type::DICTIONARY); + denomination.SetStringKey("amount", amount); + denomination.SetStringKey("currency", "BAT"); + + base::Value octets(base::Value::Type::DICTIONARY); + octets.SetKey("denomination", std::move(denomination)); + octets.SetStringKey("destination", address); + std::string octets_json; + base::JSONWriter::Write(octets, &octets_json); + + const std::string header_digest = + braveledger_helper::Security::DigestValue(octets_json); + + std::vector> headers; + headers.push_back({{"digest", header_digest}}); + + const std::string header_signature = braveledger_helper::Security::Sign( + headers, + "primary", + seed); + + base::Value signed_reqeust(base::Value::Type::DICTIONARY); + signed_reqeust.SetStringKey("octets", octets_json); + signed_reqeust.SetKey("body", std::move(octets)); + + base::Value headers_dict(base::Value::Type::DICTIONARY); + headers_dict.SetStringKey("digest", header_digest); + headers_dict.SetStringKey("signature", header_signature); + signed_reqeust.SetKey("headers", std::move(headers_dict)); + + std::string signed_request_json; + base::JSONWriter::Write(signed_reqeust, &signed_request_json); + + std::string signed_request_base64; + base::Base64Encode(signed_request_json, &signed_request_base64); + + base::Value payload(base::Value::Type::DICTIONARY); + payload.SetStringKey("signedLinkingRequest", signed_request_base64); + payload.SetStringKey("anonymousAddress", anon_address); + std::string json; + base::JSONWriter::Write(payload, &json); + + return json; +} + +} // namespace + +namespace braveledger_wallet { + +WalletClaim::WalletClaim(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), + uphold_(std::make_unique(ledger)) { +} + +WalletClaim::~WalletClaim() = default; + +void WalletClaim::Start(ledger::ResultCallback callback) { + ledger_->FetchBalance(std::bind(&WalletClaim::OnBalance, + this, + _1, + _2, + callback)); +} + +void WalletClaim::OnBalance( + const ledger::Result result, + ledger::BalancePtr balance, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK || !balance) { + BLOG(0, "Anon funds transfer failed"); + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (ledger_->GetBooleanState(ledger::kStateAnonTransferChecked) && + balance->user_funds == "0") { + BLOG(1, "Second ping with zero balance"); + callback(ledger::Result::LEDGER_OK); + return; + } + + auto wallets = ledger_->GetExternalWallets(); + auto wallet_ptr = braveledger_uphold::GetWallet(std::move(wallets)); + + if (!wallet_ptr) { + BLOG(0, "Wallet is null"); + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (!wallet_ptr->anon_address.empty()) { + BLOG(1, "Anon address already exists"); + TransferFunds( + ledger::Result::LEDGER_OK, + balance->user_funds, + callback); + return; + } + + auto anon_callback = std::bind(&WalletClaim::TransferFunds, + this, + _1, + balance->user_funds, + callback); + + uphold_->CreateAnonAddressIfNecessary(anon_callback); +} + +void WalletClaim::TransferFunds( + const ledger::Result result, + const std::string user_funds, + ledger::ResultCallback callback) { + auto wallets = ledger_->GetExternalWallets(); + auto wallet_ptr = braveledger_uphold::GetWallet(std::move(wallets)); + if (!wallet_ptr) { + BLOG(0, "Wallet is null"); + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (result != ledger::Result::LEDGER_OK || + wallet_ptr->anon_address.empty()) { + BLOG(0, "Anon address is missing"); + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto url_callback = std::bind(&WalletClaim::OnTransferFunds, + this, + _1, + callback); + + const std::string url = braveledger_request_util::GetClaimWalletURL( + braveledger_state::GetPaymentId(ledger_)); + + const std::string payload = GeneratePayload( + user_funds, + wallet_ptr->address, + wallet_ptr->anon_address, + braveledger_state::GetRecoverySeed(ledger_)); + + ledger_->LoadURL( + url, + {}, + payload, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void WalletClaim::OnTransferFunds( + const ledger::UrlResponse& response, + ledger::ResultCallback callback) { + BLOG(6, ledger::UrlResponseToString(__func__, response)); + + const auto result = braveledger_response_util::CheckClaimWallet( + response); + + if (result == ledger::Result::LEDGER_OK) { + ledger_->SetBooleanState(ledger::kStateAnonTransferChecked, true); + callback(ledger::Result::LEDGER_OK); + return; + } + + if (result == ledger::Result::ALREADY_EXISTS) { + ledger_->SetBooleanState(ledger::kStateAnonTransferChecked, true); + callback(ledger::Result::ALREADY_EXISTS); + return; + } + + callback(ledger::Result::LEDGER_ERROR); +} + +} // namespace braveledger_wallet diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h new file mode 100644 index 000000000000..abdddd9cd4a4 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h @@ -0,0 +1,48 @@ +/* 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 http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_WALLET_WALLET_CLAIM_H_ +#define BRAVELEDGER_WALLET_WALLET_CLAIM_H_ + +#include +#include + +#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/uphold/uphold.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_wallet { + +class WalletClaim { + public: + explicit WalletClaim(bat_ledger::LedgerImpl* ledger); + ~WalletClaim(); + + void Start(ledger::ResultCallback callback); + + private: + void OnBalance( + const ledger::Result result, + ledger::BalancePtr properties, + ledger::ResultCallback callback); + + void TransferFunds( + const ledger::Result result, + const std::string user_funds, + ledger::ResultCallback callback); + + void OnTransferFunds( + const ledger::UrlResponse& response, + ledger::ResultCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr uphold_; +}; + +} // namespace braveledger_wallet +#endif // BRAVELEDGER_WALLET_WALLET_CLAIM_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc index 5729fd37d931..3a9065238dee 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc @@ -5,271 +5,89 @@ #include "bat/ledger/internal/wallet/wallet_create.h" -#include +#include -#include "base/guid.h" #include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "base/values.h" -#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/common/security_helper.h" #include "bat/ledger/internal/common/time_util.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/legacy/wallet_info_properties.h" +#include "bat/ledger/internal/request/request_promotion.h" #include "bat/ledger/internal/request/request_util.h" #include "bat/ledger/internal/response/response_wallet.h" #include "bat/ledger/internal/state/state_util.h" -#include "anon/anon.h" - using std::placeholders::_1; -using std::placeholders::_2; -using std::placeholders::_3; - -namespace { - -std::string GetAnonizeProof( - const std::string& registrarVK, - const std::string& id, - std::string* preFlight) { - DCHECK(preFlight); - - const char* cred = makeCred(id.c_str()); - if (!cred) { - return ""; - } - - *preFlight = cred; - // should fix in - // https://github.com/brave-intl/bat-native-anonize/issues/11 - free((void*)cred); // NOLINT - - const char* proof_temp = registerUserMessage( - preFlight->c_str(), - registrarVK.c_str()); - - if (!proof_temp) { - return ""; - } - - std::string proof = proof_temp; - // should fix in - // https://github.com/brave-intl/bat-native-anonize/issues/11 - free((void*)proof_temp); // NOLINT - - return proof; -} - -std::string StringifyRequestCredentials( - const std::string& proof, - const std::string& label, - const std::string& public_key, - const std::string& digest, - const std::string& signature, - const std::string& octets) { - base::Value headers(base::Value::Type::DICTIONARY); - headers.SetStringKey("digest", digest); - headers.SetStringKey("signature", signature); - - base::Value body(base::Value::Type::DICTIONARY); - body.SetStringKey("currency", LEDGER_CURRENCY); - body.SetStringKey("label", label); - body.SetStringKey("publicKey", public_key); - - base::Value request(base::Value::Type::DICTIONARY); - request.SetKey("headers", std::move(headers)); - request.SetKey("body", std::move(body)); - request.SetStringKey("octets", octets); - - base::Value payload(base::Value::Type::DICTIONARY); - payload.SetStringKey("requestType", "httpSignature"); - payload.SetStringKey("proof", proof); - payload.SetKey("request", std::move(request)); - - std::string json; - base::JSONWriter::Write(payload, &json); - - return json; -} - -} // namespace namespace braveledger_wallet { -WalletCreate::WalletCreate(bat_ledger::LedgerImpl* ledger) : - ledger_(ledger) { - initAnonize(); +WalletCreate::WalletCreate(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { } -WalletCreate::~Create() = default; +WalletCreate::~WalletCreate() = default; void WalletCreate::Start(ledger::ResultCallback callback) { - auto req_callback = std::bind(&WalletCreate::RequestCredentialsCallback, - this, - _1, - std::move(callback)); - - const std::string url = - braveledger_request_util::BuildUrl(REGISTER_PERSONA, PREFIX_V2); - - ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, req_callback); -} - -void WalletCreate::RequestCredentialsCallback( - const ledger::UrlResponse& response, - ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckWalletRequestCredentials(response); - if (result != ledger::Result::LEDGER_OK) { - BLOG(0, "Can't get wallet info"); - callback(ledger::Result::BAD_REGISTRATION_RESPONSE); - return; - } - - // Anonize2 limit is 31 octets - std::string user_id = base::GenerateGUID(); - user_id.erase( - std::remove(user_id.begin(), user_id.end(), '-'), user_id.end()); - user_id.erase(12, 1); - - std::string registrar_vk; - if (!braveledger_bat_helper::getJSONValue(REGISTRARVK_FIELDNAME, - response.body, - ®istrar_vk)) { - BLOG(0, "Bad registration response"); - callback(ledger::Result::BAD_REGISTRATION_RESPONSE); - return; - } + const auto payment_id = braveledger_state::GetPaymentId(ledger_); + const auto stamp = ledger_->GetCreationStamp(); - DCHECK(!registrar_vk.empty()); - - std::string pre_flight; - const std::string proof = GetAnonizeProof(registrar_vk, user_id, &pre_flight); - - if (proof.empty()) { - BLOG(0, "Proof is empty"); - callback(ledger::Result::BAD_REGISTRATION_RESPONSE); + if (!payment_id.empty() && stamp != 0) { + BLOG(1, "Wallet already exists"); + callback(ledger::Result::WALLET_CREATED); return; } - std::vector key_info_seed = braveledger_bat_helper::generateSeed(); - + auto key_info_seed = braveledger_helper::Security::GenerateSeed(); braveledger_state::SetRecoverySeed(ledger_, key_info_seed); - std::vector secretKey = - braveledger_bat_helper::getHKDF(key_info_seed); - std::vector publicKey; - std::vector newSecretKey; - braveledger_bat_helper::getPublicKeyFromSeed(secretKey, - &publicKey, - &newSecretKey); - std::string label = base::GenerateGUID(); - std::string public_key_hex = braveledger_bat_helper::uint8ToHex(publicKey); - std::string keys[3] = {"currency", "label", "publicKey"}; - std::string values[3] = {LEDGER_CURRENCY, label, public_key_hex}; - std::string octets = braveledger_bat_helper::stringify(keys, values, 3); - std::string digest = "SHA-256=" + - braveledger_bat_helper::getBase64( - braveledger_bat_helper::getSHA256(octets)); - - std::vector header_keys; - header_keys.push_back("digest"); - std::vector header_values; - header_values.push_back(digest); - std::string signature = braveledger_bat_helper::sign( - header_keys, - header_values, - "primary", - newSecretKey); + const std::string public_key_hex = + braveledger_helper::Security::GetPublicKeyHexFromSeed(key_info_seed); - std::string payload = StringifyRequestCredentials( - proof, - label, - public_key_hex, - digest, - signature, - octets); - std::vector registerHeaders; - registerHeaders.push_back("Content-Type: application/json; charset=UTF-8"); - - // We should use simple callbacks on iOS - const std::string url = braveledger_request_util::BuildUrl( - (std::string)REGISTER_PERSONA + "/" + user_id, PREFIX_V2); - auto on_register = std::bind(&WalletCreate::RegisterPersonaCallback, + auto url_callback = std::bind(&WalletCreate::OnCreate, this, _1, - user_id, - pre_flight, - registrar_vk, - std::move(callback)); + callback); + + const auto headers = braveledger_request_util::BuildSignHeaders( + "post /v3/wallet/brave", + "", + public_key_hex, + braveledger_state::GetRecoverySeed(ledger_)); + const std::string url = braveledger_request_util::GetCreateWalletURL(); ledger_->LoadURL( url, - registerHeaders, - payload, + headers, + "", "application/json; charset=utf-8", ledger::UrlMethod::POST, - on_register); + url_callback); } -void WalletCreate::RegisterPersonaCallback( - const ledger::UrlResponse& response, - const std::string& user_id, - const std::string& pre_flight, - const std::string& registrar_vk, - ledger::ResultCallback callback) { +void WalletCreate::OnCreate( + const ledger::UrlResponse& response, + ledger::ResultCallback callback) { BLOG(6, ledger::UrlResponseToString(__func__, response)); std::string payment_id; - std::string card_id; - const ledger::Result result = - braveledger_response_util::ParseWalletRegisterPersona( - response, - &payment_id, - &card_id); - if (result != ledger::Result::LEDGER_OK) { - BLOG(0, "Can't get wallet info"); - callback(ledger::Result::BAD_REGISTRATION_RESPONSE); - return; - } + const auto result = braveledger_response_util::ParseCreateWallet( + response, + &payment_id); - BLOG(0, response.body); - - std::string verification; - if (!braveledger_bat_helper::getJSONValue(VERIFICATION_FIELDNAME, - response.body, - &verification)) { - BLOG(0, "Verification is missing"); - callback(ledger::Result::BAD_REGISTRATION_RESPONSE); + if (result != ledger::Result::LEDGER_OK) { + callback(result); return; } - const char* masterUserToken = registerUserFinal( - user_id.c_str(), - verification.c_str(), - pre_flight.c_str(), - registrar_vk.c_str()); - - if (masterUserToken != nullptr) { - // should fix in - // https://github.com/brave-intl/bat-native-anonize/issues/11 - free((void*)masterUserToken); // NOLINT - } else if (!ledger::is_testing) { - BLOG(0, "Master token error"); - callback(ledger::Result::REGISTRATION_VERIFICATION_FAILED); - return; - } + braveledger_state::SetPaymentId(ledger_, payment_id); ledger_->SetRewardsMainEnabled(true); ledger_->SetAutoContributeEnabled(true); - braveledger_state::SetPaymentId(ledger_, payment_id); - braveledger_state::SetAnonymousCardId(ledger_, card_id); + ledger_->ResetReconcileStamp(); if (!ledger::is_testing) { braveledger_state::SetFetchOldBalanceEnabled(ledger_, false); } - ledger_->SetCreationStamp(braveledger_time_util::GetCurrentTimeStamp()); - ledger_->ResetReconcileStamp(); + braveledger_state::SetCreationStamp( + ledger_, + braveledger_time_util::GetCurrentTimeStamp()); braveledger_state::SetInlineTippingPlatformEnabled( ledger_, ledger::InlineTipsPlatforms::REDDIT, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h index afffa95f8381..51f7542b99b9 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h @@ -8,10 +8,7 @@ #include -#include -#include #include -#include #include "bat/ledger/ledger.h" @@ -29,17 +26,10 @@ class WalletCreate { void Start(ledger::ResultCallback callback); private: - void RequestCredentialsCallback( + void OnCreate( const ledger::UrlResponse& response, ledger::ResultCallback callback); - void RegisterPersonaCallback( - const ledger::UrlResponse& response, - const std::string& user_id, - const std::string& pre_flight, - const std::string& registrar_vk, - ledger::ResultCallback callback); - bat_ledger::LedgerImpl* ledger_; // NOT OWNED }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc index c5d39f8e6b59..d57151a45d6f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc @@ -2,190 +2,113 @@ * 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 "bat/ledger/internal/wallet/wallet_recover.h" #include +#include "base/json/json_reader.h" #include "base/strings/string_split.h" -#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/common/security_helper.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/legacy/wallet_info_properties.h" +#include "bat/ledger/internal/request/request_promotion.h" #include "bat/ledger/internal/request/request_util.h" #include "bat/ledger/internal/response/response_wallet.h" #include "bat/ledger/internal/state/state_keys.h" #include "bat/ledger/internal/state/state_util.h" -#include "anon/anon.h" #include "wally_bip39.h" // NOLINT using std::placeholders::_1; -using std::placeholders::_2; -using std::placeholders::_3; namespace braveledger_wallet { WalletRecover::WalletRecover(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { - initAnonize(); } -WalletRecover::~WalletRecover() { -} +WalletRecover::~WalletRecover() = default; void WalletRecover::Start( const std::string& pass_phrase, - ledger::RecoverWalletCallback callback) { + ledger::ResultCallback callback) { if (pass_phrase.empty()) { BLOG(0, "Pass phrase is empty"); - callback(ledger::Result::LEDGER_ERROR, 0); + callback(ledger::Result::LEDGER_ERROR); return; } - size_t written = 0; auto phrase_split = base::SplitString( pass_phrase, - WALLET_PASSPHRASE_DELIM, + " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); if (phrase_split.size() == 16) { - // use niceware for legacy wallet passphrases - ledger_->LoadNicewareList(std::bind(&WalletRecover::OnNicewareListLoaded, - this, - pass_phrase, - _1, - _2, - std::move(callback))); + BLOG(0, "Pass phrase is niceware, update to bip39"); + callback(ledger::Result::CORRUPTED_DATA); return; } - std::vector newSeed; - newSeed.resize(32); + std::vector new_seed; + new_seed.resize(32); + size_t written = 0; const int result = bip39_mnemonic_to_bytes( nullptr, pass_phrase.c_str(), - &newSeed.front(), - newSeed.size(), + &new_seed.front(), + new_seed.size(), &written); - ContinueRecover(result, &written, newSeed, std::move(callback)); -} - -void WalletRecover::OnNicewareListLoaded( - const std::string& pass_phrase, - ledger::Result result, - const std::string& data, - ledger::RecoverWalletCallback callback) { - auto phrase_split = base::SplitString( - pass_phrase, - WALLET_PASSPHRASE_DELIM, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - - if (result == ledger::Result::LEDGER_OK && phrase_split.size() == 16) { - std::vector seed; - seed.resize(32); - size_t written = 0; - - auto data_split = base::SplitString( - data, - DICTIONARY_DELIMITER, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - uint8_t nwResult = braveledger_bat_helper::niceware_mnemonic_to_bytes( - pass_phrase, - &seed, - &written, - data_split); - ContinueRecover(nwResult, &written, seed, std::move(callback)); + if (result != 0 || written == 0) { + BLOG(0, "Result: " << result << " Size: " << written); + callback(ledger::Result::LEDGER_ERROR); return; } - BLOG(0, "Failed to load niceware list"); - callback(result, 0); - return; -} - -void WalletRecover::ContinueRecover( - int result, - size_t* written, - const std::vector& newSeed, - ledger::RecoverWalletCallback callback) { - if (result != 0 || *written == 0) { - BLOG(1, "Result: " << result << " Size: " << *written); - callback(ledger::Result::LEDGER_ERROR, 0); - return; - } - - std::vector secretKey = braveledger_bat_helper::getHKDF(newSeed); - std::vector publicKey; - std::vector newSecretKey; - braveledger_bat_helper::getPublicKeyFromSeed(secretKey, - &publicKey, - &newSecretKey); - std::string publicKeyHex = braveledger_bat_helper::uint8ToHex(publicKey); - - auto on_load = std::bind(&WalletRecover::RecoverWalletPublicKeyCallback, - this, - _1, - newSeed, - std::move(callback)); - const auto url = braveledger_request_util::BuildUrl( - (std::string)RECOVER_WALLET_PUBLIC_KEY + publicKeyHex, - PREFIX_V2); - ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, std::move(on_load)); -} - -void WalletRecover::RecoverWalletPublicKeyCallback( - const ledger::UrlResponse& response, - const std::vector& new_seed, - ledger::RecoverWalletCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); + const std::string public_key_hex = + braveledger_helper::Security::GetPublicKeyHexFromSeed(new_seed); - std::string recovery_id; - const auto result = - braveledger_response_util::ParseWalletRecoverKey(response, &recovery_id); - if (result == ledger::Result::LEDGER_ERROR) { - callback(result, 0.0); - return; - } - - auto recover_callback = std::bind(&WalletRecover::RecoverWalletCallback, + auto url_callback = std::bind(&WalletRecover::OnRecover, this, _1, - recovery_id, new_seed, - std::move(callback)); - const std::string url = braveledger_request_util::BuildUrl - ("/wallet/" + recovery_id, PREFIX_V2); - ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, recover_callback); + callback); + + const std::string url = + braveledger_request_util::GetRecoverWalletURL(public_key_hex); + ledger_->LoadURL( + url, + {}, + "", + "application/json; charset=utf-8", + ledger::UrlMethod::GET, + url_callback); } -void WalletRecover::RecoverWalletCallback( +void WalletRecover::OnRecover( const ledger::UrlResponse& response, - const std::string& recovery_id, const std::vector& new_seed, - ledger::RecoverWalletCallback callback) { + ledger::ResultCallback callback) { BLOG(6, ledger::UrlResponseToString(__func__, response)); - double balance = 0.0; - std::string card_id; + std::string payment_id; const auto result = braveledger_response_util::ParseRecoverWallet( response, - &card_id, - &balance); + &payment_id); + if (result != ledger::Result::LEDGER_OK) { - callback(result, balance); + callback(result); return; } braveledger_state::SetRecoverySeed(ledger_, new_seed); - braveledger_state::SetPaymentId(ledger_, recovery_id); - braveledger_state::SetAnonymousCardId(ledger_, card_id); + braveledger_state::SetPaymentId(ledger_, payment_id); braveledger_state::SetFetchOldBalanceEnabled(ledger_, true); + ledger_->SetBooleanState(ledger::kStateAnonTransferChecked, false); ledger_->SetUint64State(ledger::kStatePromotionLastFetchStamp, 0); ledger_->SetConfirmationsWalletInfo(); - callback(ledger::Result::LEDGER_OK, balance); + callback(ledger::Result::LEDGER_OK); } } // namespace braveledger_wallet diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h index 6ddef2370f32..4129bf76df84 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h @@ -8,8 +8,6 @@ #include -#include -#include #include #include @@ -28,32 +26,13 @@ class WalletRecover { void Start( const std::string& pass_phrase, - ledger::RecoverWalletCallback callback); + ledger::ResultCallback callback); private: - void OnNicewareListLoaded( - const std::string& pass_phrase, - ledger::Result result, - const std::string& data, - ledger::RecoverWalletCallback callback); - - void ContinueRecover( - int result, - size_t* written, - const std::vector& newSeed, - ledger::RecoverWalletCallback callback); - - - void RecoverWalletPublicKeyCallback( - const ledger::UrlResponse& response, - const std::vector& new_seed, - ledger::RecoverWalletCallback callback); - - void RecoverWalletCallback( + void OnRecover( const ledger::UrlResponse& response, - const std::string& recovery_id, const std::vector& new_seed, - ledger::RecoverWalletCallback callback); + ledger::ResultCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc index dc0d2e9c3fef..5b9f4111071e 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc @@ -53,7 +53,6 @@ TEST(WalletUtilTest, ResetWalletVerifiedWallet) { wallet->user_name = "3"; wallet->one_time_string = "4"; wallet->status = ledger::WalletStatus::VERIFIED; - wallet->transferred = true; auto reset_wallet = braveledger_wallet::ResetWallet(std::move(wallet)); diff --git a/vendor/brave-ios/BUILD.gn b/vendor/brave-ios/BUILD.gn index 1284d91e7e63..5dc3220d1259 100644 --- a/vendor/brave-ios/BUILD.gn +++ b/vendor/brave-ios/BUILD.gn @@ -175,10 +175,8 @@ ios_framework_bundle("brave_rewards_ios_framework") { bundle_data("resources") { ads_dir = "//brave/vendor/bat-native-ads" - ledger_dir = "//brave/vendor/bat-native-ledger" sources = [ "$ads_dir/data/resources/catalog-schema.json", - "$ledger_dir/niceware/wordlist", "Ledger/Data/migrate.sql" ] outputs = [ diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.mm b/vendor/brave-ios/Ledger/BATBraveLedger.mm index dc942fcb6e3d..7eae24b4f521 100644 --- a/vendor/brave-ios/Ledger/BATBraveLedger.mm +++ b/vendor/brave-ios/Ledger/BATBraveLedger.mm @@ -500,7 +500,7 @@ - (void)recoverWalletUsingPassphrase:(NSString *)passphrase completion:(void (^) // - LEDGER_OK: Good to go // - LEDGER_ERROR: Recovery failed ledger->RecoverWallet(std::string(passphrase.UTF8String), - ^(const ledger::Result result, const double balance) { + ^(const ledger::Result result) { const auto strongSelf = weakSelf; if (!strongSelf) { return; } NSError *error = nil; @@ -1111,19 +1111,6 @@ - (void)allContributions:(void (^)(NSArray *contributions }); } -- (void)loadNicewareList:(ledger::GetNicewareListCallback)callback -{ - NSError *error; - const auto bundle = [NSBundle bundleForClass:[BATBraveLedger class]]; - const auto path = [bundle pathForResource:@"wordlist" ofType:nil]; - const auto contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; - if (error || contents.length == 0) { - callback(ledger::Result::LEDGER_ERROR, ""); - } else { - callback(ledger::Result::LEDGER_OK, std::string(contents.UTF8String)); - } -} - #pragma mark - Reporting - (void)setSelectedTabId:(UInt32)selectedTabId diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h index 25b148b97071..53fbdc71764b 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h @@ -19,7 +19,6 @@ class NativeLedgerClient : public ledger::LedgerClient { void FetchFavIcon(const std::string & url, const std::string & favicon_key, ledger::FetchIconCallback callback) override; void KillTimer(const uint32_t timer_id) override; void LoadLedgerState(ledger::OnLoadCallback callback) override; - void LoadNicewareList(ledger::GetNicewareListCallback callback) override; void LoadPublisherState(ledger::OnLoadCallback callback) override; void LoadState(const std::string & name, ledger::OnLoadCallback callback) override; void LoadURL(const std::string & url, const std::vector & headers, const std::string & content, const std::string & contentType, const ledger::UrlMethod method, ledger::LoadURLCallback callback) override; diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm index fe33c3125cc0..114430bf28c3 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm @@ -23,9 +23,6 @@ void NativeLedgerClient::LoadLedgerState(ledger::OnLoadCallback callback) { [bridge_ loadLedgerState:callback]; } -void NativeLedgerClient::LoadNicewareList(ledger::GetNicewareListCallback callback) { - [bridge_ loadNicewareList:callback]; -} void NativeLedgerClient::LoadPublisherState(ledger::OnLoadCallback callback) { [bridge_ loadPublisherState:callback]; } diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h index 5733f32604ea..f884566937cd 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h @@ -12,7 +12,6 @@ - (void)fetchFavIcon:(const std::string &)url faviconKey:(const std::string &)favicon_key callback:(ledger::FetchIconCallback)callback; - (void)killTimer:(const uint32_t)timer_id; - (void)loadLedgerState:(ledger::OnLoadCallback)callback; -- (void)loadNicewareList:(ledger::GetNicewareListCallback)callback; - (void)loadPublisherState:(ledger::OnLoadCallback)callback; - (void)loadState:(const std::string &)name callback:(ledger::OnLoadCallback)callback; - (void)loadURL:(const std::string &)url headers:(const std::vector &)headers content:(const std::string &)content contentType:(const std::string &)contentType method:(const ledger::UrlMethod)method callback:(ledger::LoadURLCallback)callback; diff --git a/vendor/brave-ios/Ledger/Models/BATExternalWallet+DictionaryValue.mm b/vendor/brave-ios/Ledger/Models/BATExternalWallet+DictionaryValue.mm index eeb0a4785831..29b6ecd146cf 100644 --- a/vendor/brave-ios/Ledger/Models/BATExternalWallet+DictionaryValue.mm +++ b/vendor/brave-ios/Ledger/Models/BATExternalWallet+DictionaryValue.mm @@ -13,10 +13,10 @@ - (instancetype)initWithDictionaryValue:(NSDictionary *)dictionary if ((self = [self initWithExternalWallet:defaultWallet])) { self.token = dictionary[@"token"] ?: @""; self.address = dictionary[@"address"] ?: @""; + self.anonAddress = dictionary[@"anon_address"] ?: @""; self.status = static_cast([dictionary[@"status"] integerValue]); self.oneTimeString = dictionary[@"one_time_string"] ?: @""; self.userName = dictionary[@"user_name"] ?: @""; - self.transferred = [dictionary[@"transferred"] boolValue]; self.verifyUrl = dictionary[@"verify_url"] ?: @""; self.addUrl = dictionary[@"add_url"] ?: @""; self.withdrawUrl = dictionary[@"withdraw_url"] ?: @""; @@ -30,10 +30,10 @@ - (NSDictionary *)dictionaryValue return @{ @"token": self.token, @"address": self.address, + @"anon_address": self.anonAddress, @"status": @(self.status), @"one_time_string": self.oneTimeString, @"user_name": self.userName, - @"transferred": @(self.transferred), @"verify_url": self.verifyUrl, @"add_url": self.addUrl, @"withdraw_url": self.withdrawUrl, @@ -43,8 +43,8 @@ - (NSDictionary *)dictionaryValue - (NSString *)description { - return [NSString stringWithFormat:@"%@: token: %@, address: %@, status: %ld, ots: %@, username: %@, transferred: %d, verifyUrl: %@, addUrl: %@, withdrawUrl: %@, accountUrl: %@", - [super description], self.token, self.address, self.status, self.oneTimeString, self.userName, self.transferred, self.verifyUrl, self.addUrl, self.withdrawUrl, self.accountUrl]; + return [NSString stringWithFormat:@"%@: token: %@, address: %@, anonAddress: %@, status: %ld, ots: %@, username: %@, verifyUrl: %@, addUrl: %@, withdrawUrl: %@, accountUrl: %@", + [super description], self.token, self.address, self.anonAddress, self.status, self.oneTimeString, self.userName, self.verifyUrl, self.addUrl, self.withdrawUrl, self.accountUrl]; } @end From 4c0ed64f7ad7a21b484e7f344b21ecdb6919acf8 Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Tue, 21 Jul 2020 22:26:55 +0200 Subject: [PATCH 3/4] Implements new balance api --- .../browser/ads_service_browsertest.cc | 14 --- .../common/rewards_browsertest_response.cc | 6 +- test/data/rewards-data/balance_resp.json | 35 +----- .../rewards-data/user_funds_balance_resp.json | 35 +----- .../internal/request/request_promotion.cc | 7 ++ .../internal/request/request_promotion.h | 2 + .../ledger/internal/request/request_util.cc | 28 ----- .../ledger/internal/request/request_util.h | 1 - .../internal/response/response_wallet.cc | 118 +++--------------- .../internal/response/response_wallet.h | 2 +- .../ledger/internal/wallet/wallet_balance.cc | 23 +--- 11 files changed, 44 insertions(+), 227 deletions(-) diff --git a/components/brave_ads/browser/ads_service_browsertest.cc b/components/brave_ads/browser/ads_service_browsertest.cc index 517491b40445..e5cd91f18426 100644 --- a/components/brave_ads/browser/ads_service_browsertest.cc +++ b/components/brave_ads/browser/ads_service_browsertest.cc @@ -102,15 +102,6 @@ std::unique_ptr HandleRequest( return std::move(http_response); } -bool URLMatches(const std::string& url, - const std::string& path, - const std::string& prefix, - const ServerTypes& server) { - const std::string target_url = - braveledger_request_util::BuildUrl(path, prefix, server); - return (url.find(target_url) == 0); -} - } // namespace class BraveAdsBrowserTest @@ -198,11 +189,6 @@ class BraveAdsBrowserTest *response_status_code = net::HTTP_CREATED; return; } - - if (URLMatches(url, "/wallet/", PREFIX_V2, ServerTypes::BALANCE)) { - *response = parameters_; - return; - } } bool SetUpUserDataDirectory() override { diff --git a/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc b/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc index f11d1d39ac4e..03fe3a069b72 100644 --- a/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc +++ b/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc @@ -236,9 +236,9 @@ void RewardsBrowserTestResponse::Get( if (URLMatches( url, - "/wallet/", - PREFIX_V2, - ServerTypes::BALANCE)) { + "/wallet/uphold", + PREFIX_V3, + ServerTypes::kPromotion)) { if (user_funds_balance_) { *response = user_funds_balance_resp_; } else { diff --git a/test/data/rewards-data/balance_resp.json b/test/data/rewards-data/balance_resp.json index 488215d513d1..e50ad7c2adf0 100644 --- a/test/data/rewards-data/balance_resp.json +++ b/test/data/rewards-data/balance_resp.json @@ -1,31 +1,6 @@ { - "altcurrency": "BAT", - "probi": "0", - "balance": "0.0000", - "unconfirmed": "0.0000", - "parameters": { - "adFree": { - "currency": "BAT", - "fee": { - "BAT": 20 - }, - "choices": { - "BAT": [ - 10, - 15, - 20, - 30, - 50, - 100 - ] - }, - "range": { - "BAT": [ - 10, - 100 - ] - }, - "days": 30 - } - } -} \ No newline at end of file + "total": 0, + "spendable": 0, + "confirmed": 0, + "unconfirmed": 0 +} diff --git a/test/data/rewards-data/user_funds_balance_resp.json b/test/data/rewards-data/user_funds_balance_resp.json index 016ca09807fb..d6e23c66cf77 100644 --- a/test/data/rewards-data/user_funds_balance_resp.json +++ b/test/data/rewards-data/user_funds_balance_resp.json @@ -1,33 +1,6 @@ { - "altcurrency": "BAT", - "probi": "0", - "balance": "20.0000", - "cardBalance": "20.0", - "probi": "20000000000000000000", - "unconfirmed": "0.0000", - "parameters": { - "adFree": { - "currency": "BAT", - "fee": { - "BAT": 0 - }, - "choices": { - "BAT": [ - 10, - 15, - 20, - 30, - 50, - 100 - ] - }, - "range": { - "BAT": [ - 10, - 100 - ] - }, - "days": 30 - } - } + "total": 0, + "spendable": 0, + "confirmed": 20.0, + "unconfirmed": 0 } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc index 77f63a8503f0..c5c0a8ec411f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc @@ -87,4 +87,11 @@ std::string GetClaimWalletURL(const std::string& payment_id) { return BuildUrl(path, PREFIX_V3, ServerTypes::kPromotion); } +std::string GetBalanceWalletURL(const std::string& payment_id) { + const std::string path = base::StringPrintf( + "/wallet/uphold/%s", + payment_id.c_str()); + return BuildUrl(path, PREFIX_V3, ServerTypes::kPromotion); +} + } // namespace braveledger_request_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h index 545d8309e005..4ee5b6b40b45 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h @@ -35,6 +35,8 @@ std::string GetRecoverWalletURL(const std::string& public_key); std::string GetClaimWalletURL(const std::string& payment_id); +std::string GetBalanceWalletURL(const std::string& payment_id); + } // namespace braveledger_request_util #endif // BRAVELEDGER_COMMON_PROMOTION_REQUESTS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc index a00c5d1f95dd..9353bcb186d5 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc @@ -17,13 +17,6 @@ const char kStaging[] = "https://ledger-staging.mercury.basicattentiontoken.org"; const char kProduction[] = "https://ledger.mercury.basicattentiontoken.org"; -namespace balance { -const char kDevelopment[] = "https://balance.rewards.brave.software"; -const char kStaging[] = - "https:kP/balance-staging.mercury.basicattentiontoken.org"; -const char kProduction[] = "https://balance.mercury.basicattentiontoken.org"; -} // namespace balance - namespace publisher { const char kDevelopment[] = "https://rewards-dev.brave.software"; const char kStaging[] = "https://rewards-stg.bravesoftware.com"; @@ -54,23 +47,6 @@ const char kStaging[] = "https://pcdn.bravesoftware.com"; const char kProduction[] = "https://pcdn.brave.com"; } // namespace cdn -std::string BuildBalanceUrl() { - std::string url; - switch (ledger::_environment) { - case ledger::Environment::DEVELOPMENT: - url = balance::kDevelopment; - break; - case ledger::Environment::STAGING: - url = balance::kStaging; - break; - case ledger::Environment::PRODUCTION: - url = balance::kProduction; - break; - } - - return url; -} - std::string BuildPublisherUrl() { std::string url; switch (ledger::_environment) { @@ -179,10 +155,6 @@ std::string BuildUrl( const ServerTypes& server) { std::string url; switch (server) { - case ServerTypes::BALANCE: { - url = BuildBalanceUrl(); - break; - } case ServerTypes::kPublisher: { url = BuildPublisherUrl(); break; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h index e34edccb69e3..0f1b9422593a 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h @@ -14,7 +14,6 @@ namespace braveledger_request_util { enum class ServerTypes { LEDGER, // TODO remove me - BALANCE, // TODO remove me kPublisher, kPromotion, kPayments, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc index cfb2448ee2d8..92cab7d0a92b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc @@ -5,9 +5,12 @@ #include "bat/ledger/internal/response/response_wallet.h" +#include + #include "base/json/json_reader.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" +#include "bat/ledger/global_constants.h" #include "bat/ledger/internal/logging.h" #include "net/http/http_status_code.h" @@ -180,96 +183,20 @@ ledger::Result CheckClaimWallet(const ledger::UrlResponse& response) { } // Request Url: -// GET /wallet/{payment_id}/balance +// GET /v3/wallet/uphold/{payment_id} // // Success: // OK (200) // // Response Format: // { -// "altcurrency": "BAT", -// "probi": "0", -// "cardBalance": "0", -// "balance": "0.0000", -// "unconfirmed": "0.0000", -// "rates": { -// "AED": 0.864759348, -// "ARS": 16.3201969584, -// "AUD": 0.3420872568, -// "BAT": 1, -// "BCH": 0.00096277302, -// "BRL": 1.17166716, -// "BTC": 0.0000247753512, -// "BTG": 0.0267530566176, -// "CAD": 0.3193696512, -// "CHF": 0.2209298328, -// "CNY": 1.663407144, -// "DASH": 0.0030994899048, -// "DKK": 1.5428430288, -// "ETH": 0.000987728323025758, -// "EUR": 0.2069541144, -// "GBP": 0.1864519992, -// "HKD": 1.8247023792, -// "ILS": 0.8132238864, -// "INR": 17.927590572, -// "JPY": 25.1176738968, -// "KES": 25.0625197224, -// "LBA": 19.393739703459637, -// "LTC": 0.0052345069128, -// "MXN": 5.3096381712, -// "NOK": 2.2435171776, -// "NZD": 0.3647860272, -// "PHP": 11.8485109368, -// "PLN": 0.926880192, -// "SEK": 2.178867708, -// "SGD": 0.3270167424, -// "USD": 0.23624649565116654, -// "XAG": 0.0128360428272, -// "XAU": 0.00013620204, -// "XPD": 0.0001530524808, -// "XPT": 0.0002889696384, -// "XRP": 1.21298311296 -// }, -// "parameters": { -// "adFree": { -// "currency": "BAT", -// "fee": { -// "BAT": 10 -// }, -// "choices": { -// "BAT": [ -// 5, -// 10, -// 15, -// 20, -// 25, -// 50, -// 100 -// ] -// }, -// "range": { -// "BAT": [ -// 5, -// 100 -// ] -// }, -// "days": 30 -// }, -// "defaultTipChoices": [ -// "1", -// "10", -// "50" -// ], -// "defaultMonthlyChoices": [ -// "1", -// "10", -// "50" -// ] -// } +// "total": 0.0 +// "spendable": 0.0 +// "confirmed": 0.0 +// "unconfirmed": 0.0 // } -ledger::BalancePtr ParseWalletFetchBalance( - const ledger::UrlResponse& response) { +ledger::BalancePtr ParseWalletBalance(const ledger::UrlResponse& response) { // Bad Request (400) if (response.status_code == net::HTTP_BAD_REQUEST) { BLOG(0, "Invalid payment id"); @@ -282,12 +209,6 @@ ledger::BalancePtr ParseWalletFetchBalance( return nullptr; } - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return nullptr; - } - // Service Unavailable (503) if (response.status_code == net::HTTP_SERVICE_UNAVAILABLE) { BLOG(0, "No conversion rate yet in ratios service"); @@ -300,6 +221,7 @@ ledger::BalancePtr ParseWalletFetchBalance( base::Optional value = base::JSONReader::Read(response.body); if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); return nullptr; } @@ -311,22 +233,14 @@ ledger::BalancePtr ParseWalletFetchBalance( ledger::BalancePtr balance = ledger::Balance::New(); - double total_anon = 0.0; - const auto* total = dictionary->FindStringKey("balance"); - if (total) { - const bool success = base::StringToDouble(*total, &total_anon); - if (!success) { - total_anon = 0.0; - } + const auto confirmed = dictionary->FindDoubleKey("confirmed"); + if (confirmed) { + balance->total = *confirmed; } - balance->total = total_anon; - std::string user_funds = "0"; - const auto* funds = dictionary->FindStringKey("cardBalance"); - if (funds) { - user_funds = *funds; - } - balance->user_funds = user_funds; + balance->user_funds = balance->total; + balance->wallets.insert( + std::make_pair(ledger::kWalletAnonymous, balance->total)); return balance; } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h index 9701534b856c..27243c11fb25 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h @@ -22,7 +22,7 @@ ledger::Result ParseRecoverWallet( ledger::Result CheckClaimWallet(const ledger::UrlResponse& response); -ledger::BalancePtr ParseWalletFetchBalance(const ledger::UrlResponse& response); +ledger::BalancePtr ParseWalletBalance(const ledger::UrlResponse& response); } // namespace braveledger_response_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc index dbea2f9dc2a6..e50a1d9ddcae 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc @@ -10,11 +10,9 @@ #include #include -#include "base/json/json_reader.h" -#include "base/strings/stringprintf.h" #include "bat/ledger/global_constants.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/request/request_promotion.h" #include "bat/ledger/internal/response/response_wallet.h" #include "bat/ledger/internal/state/state_util.h" #include "bat/ledger/internal/static_values.h" @@ -22,7 +20,6 @@ using std::placeholders::_1; using std::placeholders::_2; -using std::placeholders::_3; namespace braveledger_wallet { @@ -31,8 +28,7 @@ WalletBalance::WalletBalance(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { } -WalletBalance::~WalletBalance() { -} +WalletBalance::~WalletBalance() = default; void WalletBalance::Fetch(ledger::FetchBalanceCallback callback) { // if we don't have user funds in anon card anymore @@ -46,13 +42,9 @@ void WalletBalance::Fetch(ledger::FetchBalanceCallback callback) { const std::string payment_id = braveledger_state::GetPaymentId(ledger_); - std::string path = base::StringPrintf( - "/wallet/%s/balance", - payment_id.c_str()); - const std::string url = braveledger_request_util::BuildUrl( - path, - PREFIX_V2, - braveledger_request_util::ServerTypes::BALANCE); + const std::string url = braveledger_request_util::GetBalanceWalletURL( + braveledger_state::GetPaymentId(ledger_)); + auto load_callback = std::bind(&WalletBalance::OnFetch, this, _1, @@ -66,16 +58,13 @@ void WalletBalance::OnFetch( BLOG(6, ledger::UrlResponseToString(__func__, response)); ledger::BalancePtr balance = - braveledger_response_util::ParseWalletFetchBalance(response); + braveledger_response_util::ParseWalletBalance(response); if (!balance) { BLOG(0, "Couldn't fetch wallet balance"); callback(ledger::Result::LEDGER_ERROR, nullptr); return; } - balance->wallets.insert( - std::make_pair(ledger::kWalletAnonymous, balance->total)); - if (balance->total == 0.0) { braveledger_state::SetFetchOldBalanceEnabled(ledger_, false); } From e35df1b5ff9a99b6a159dd5a820aef08d4788efe Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Fri, 24 Jul 2020 13:32:04 +0200 Subject: [PATCH 4/4] Removes ledger server --- .../ledger/internal/request/request_util.cc | 26 ------------------- .../ledger/internal/request/request_util.h | 5 ++-- 2 files changed, 2 insertions(+), 29 deletions(-) diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc index 9353bcb186d5..de6ffd985e6e 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc @@ -12,11 +12,6 @@ namespace braveledger_request_util { -const char kDevelopment[] = "https://ledger.rewards.brave.software"; -const char kStaging[] = - "https://ledger-staging.mercury.basicattentiontoken.org"; -const char kProduction[] = "https://ledger.mercury.basicattentiontoken.org"; - namespace publisher { const char kDevelopment[] = "https://rewards-dev.brave.software"; const char kStaging[] = "https://rewards-stg.bravesoftware.com"; @@ -64,23 +59,6 @@ std::string BuildPublisherUrl() { return url; } -std::string BuildLedgerUrl() { - std::string url; - switch (ledger::_environment) { - case ledger::Environment::DEVELOPMENT: - url = kDevelopment; - break; - case ledger::Environment::STAGING: - url = kStaging; - break; - case ledger::Environment::PRODUCTION: - url = kProduction; - break; - } - - return url; -} - std::string BuildPromotionUrl() { std::string url; switch (ledger::_environment) { @@ -159,10 +137,6 @@ std::string BuildUrl( url = BuildPublisherUrl(); break; } - case ServerTypes::LEDGER: { - url = BuildLedgerUrl(); - break; - } case ServerTypes::kPromotion: { url = BuildPromotionUrl(); break; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h index 0f1b9422593a..0f198ce26da4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h @@ -13,7 +13,6 @@ namespace braveledger_request_util { enum class ServerTypes { - LEDGER, // TODO remove me kPublisher, kPromotion, kPayments, @@ -23,8 +22,8 @@ enum class ServerTypes { std::string BuildUrl( const std::string& path, - const std::string& prefix = "", - const ServerTypes& server = ServerTypes::LEDGER); + const std::string& prefix, + const ServerTypes& server); std::map GetSignHeaders( const std::string& url,