From 28d731e25efbb955098f5f5b857cbc7ee1d4574c Mon Sep 17 00:00:00 2001 From: Brian Clifton Date: Wed, 22 Jan 2020 12:31:00 -0800 Subject: [PATCH 1/2] Merge pull request #4372 from brave/ac-delay Adds delays for suggestion api --- browser/ui/webui/brave_rewards_page_ui.cc | 10 + .../database/database_contribution_info.cc | 114 +++- .../database/database_contribution_info.h | 19 + .../database_contribution_info_publishers.cc | 56 +- .../database_contribution_info_publishers.h | 5 + .../database/publisher_info_database.cc | 47 ++ .../database/publisher_info_database.h | 15 + .../publisher_info_database_unittest.cc | 4 +- .../browser/rewards_service_impl.cc | 133 +++++ .../browser/rewards_service_impl.h | 28 + .../browser/rewards_service_observer.h | 1 + .../resources/page/actions/rewards_actions.ts | 2 + .../resources/page/brave_rewards_page.tsx | 7 +- .../resources/page/constants/rewards_types.ts | 3 +- .../page/reducers/publishers_reducer.ts | 3 + .../bat_ledger_client_mojo_proxy.cc | 66 +++ .../bat_ledger/bat_ledger_client_mojo_proxy.h | 20 + .../public/cpp/ledger_client_mojo_proxy.cc | 106 ++++ .../public/cpp/ledger_client_mojo_proxy.h | 36 ++ .../public/interfaces/bat_ledger.mojom | 10 + .../internal/confirmations_client_mock.h | 20 + .../include/bat/ledger/ledger_client.h | 26 + .../include/bat/ledger/mojom_structs.h | 3 + .../bat/ledger/public/interfaces/ledger.mojom | 19 +- .../internal/contribution/contribution.cc | 130 +++-- .../internal/contribution/contribution.h | 20 + .../contribution/contribution_unblinded.cc | 545 +++++++++++++----- .../contribution/contribution_unblinded.h | 88 ++- .../contribution_unblinded_unittest.cc | 53 +- .../bat/ledger/internal/ledger_client_mock.h | 20 + .../src/bat/ledger/internal/ledger_impl.cc | 54 ++ .../src/bat/ledger/internal/ledger_impl.h | 29 +- .../bat/ledger/internal/ledger_impl_mock.h | 10 + vendor/brave-ios/Ledger/BATBraveLedger.mm | 25 + .../Ledger/Generated/NativeLedgerClient.h | 5 + .../Ledger/Generated/NativeLedgerClient.mm | 15 + .../Generated/NativeLedgerClientBridge.h | 5 + 37 files changed, 1511 insertions(+), 241 deletions(-) diff --git a/browser/ui/webui/brave_rewards_page_ui.cc b/browser/ui/webui/brave_rewards_page_ui.cc index 841f33b30c33..c92d89112f8d 100644 --- a/browser/ui/webui/brave_rewards_page_ui.cc +++ b/browser/ui/webui/brave_rewards_page_ui.cc @@ -251,6 +251,8 @@ class RewardsDOMHandler : public WebUIMessageHandler, void OnUnblindedTokensReady( brave_rewards::RewardsService* rewards_service) override; + void ReconcileStampReset() override; + // RewardsNotificationsServiceObserver implementation void OnNotificationAdded( brave_rewards::RewardsNotificationService* rewards_notification_service, @@ -1700,6 +1702,14 @@ void RewardsDOMHandler::OnUnblindedTokensReady( web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.unblindedTokensReady"); } +void RewardsDOMHandler::ReconcileStampReset() { + if (!web_ui()->CanCallJavascript()) { + return; + } + + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.reconcileStampReset"); +} + } // namespace BraveRewardsPageUI::BraveRewardsPageUI(content::WebUI* web_ui, diff --git a/components/brave_rewards/browser/database/database_contribution_info.cc b/components/brave_rewards/browser/database/database_contribution_info.cc index e824decdc0e8..63a71fb7e37d 100644 --- a/components/brave_rewards/browser/database/database_contribution_info.cc +++ b/components/brave_rewards/browser/database/database_contribution_info.cc @@ -331,7 +331,7 @@ bool DatabaseContributionInfo::InsertOrUpdate( statement.BindString(0, info->contribution_id); statement.BindDouble(1, info->amount); statement.BindInt(2, static_cast(info->type)); - statement.BindInt(3, info->step); + statement.BindInt(3, static_cast(info->step)); statement.BindInt(4, info->retry_count); if (info->created_at == 0) { @@ -360,17 +360,18 @@ bool DatabaseContributionInfo::GetOneTimeTips( return false; } - const std::string query = + const std::string query = base::StringPrintf( "SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " "ci.amount, ci.created_at, spi.status, pi.provider " - "FROM contribution_info as ci " + "FROM %s as ci " "INNER JOIN contribution_info_publishers AS cp " "ON cp.contribution_id = ci.contribution_id " "INNER JOIN publisher_info AS pi ON cp.publisher_key = pi.publisher_id " "LEFT JOIN server_publisher_info AS spi " "ON spi.publisher_key = pi.publisher_id " - "WHERE strftime('%m', datetime(ci.created_at, 'unixepoch')) = ? AND " - "strftime('%Y', datetime(ci.created_at, 'unixepoch')) = ? AND ci.type = ?"; + "WHERE strftime('%%m', datetime(ci.created_at, 'unixepoch')) = ? AND " + "strftime('%%Y', datetime(ci.created_at, 'unixepoch')) = ? AND ci.type = ?", + table_name_); sql::Statement statement(db->GetUniqueStatement(query.c_str())); @@ -399,4 +400,107 @@ bool DatabaseContributionInfo::GetOneTimeTips( return true; } +bool DatabaseContributionInfo::GetNotCompletedRecords( + sql::Database* db, + ledger::ContributionInfoList* list) { + DCHECK(list && db); + if (!list || !db) { + return false; + } + + const std::string query = base::StringPrintf( + "SELECT ci.contribution_id, ci.amount, ci.type, ci.step, ci.retry_count " + "FROM %s as ci WHERE ci.step > 0", + table_name_); + + sql::Statement statement(db->GetUniqueStatement(query.c_str())); + + while (statement.Step()) { + auto info = ledger::ContributionInfo::New(); + info->contribution_id = statement.ColumnString(0); + info->amount = statement.ColumnDouble(1); + info->type = static_cast(statement.ColumnInt64(2)); + info->step = static_cast(statement.ColumnInt(3)); + info->retry_count = statement.ColumnInt(4); + publishers_->GetRecords( + db, + info->contribution_id, + &info->publishers); + + list->push_back(std::move(info)); + } + + return true; +} + +ledger::ContributionInfoPtr DatabaseContributionInfo::GetRecord( + sql::Database* db, + const std::string& contribution_id) { + DCHECK(db); + if (!db || contribution_id.empty()) { + return nullptr; + } + + const std::string query = base::StringPrintf( + "SELECT ci.contribution_id, ci.amount, ci.type, ci.step, ci.retry_count " + "FROM %s as ci " + "WHERE ci.contribution_id = ?", + table_name_); + + sql::Statement statement(db->GetUniqueStatement(query.c_str())); + + statement.BindString(0, contribution_id); + + if (!statement.Step()) { + return nullptr; + } + + auto info = ledger::ContributionInfo::New(); + info->contribution_id = statement.ColumnString(0); + info->amount = statement.ColumnDouble(1); + info->type = static_cast(statement.ColumnInt64(2)); + info->step = static_cast(statement.ColumnInt(3)); + info->retry_count = statement.ColumnInt(4); + publishers_->GetRecords( + db, + info->contribution_id, + &info->publishers); + + return info; +} + +bool DatabaseContributionInfo::UpdateStepAndCount( + sql::Database* db, + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count) { + DCHECK(db); + if (!db || contribution_id.empty()) { + return false; + } + + const std::string query = base::StringPrintf( + "UPDATE %s SET step=?, retry_count=? WHERE contribution_id = ?;", + table_name_); + + sql::Statement statement( + db->GetCachedStatement(SQL_FROM_HERE, query.c_str())); + + statement.BindInt(0, static_cast(step)); + statement.BindInt(1, retry_count); + statement.BindString(2, contribution_id); + + return statement.Run(); +} + +bool DatabaseContributionInfo::UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key) { + return publishers_->UpdateContributedAmount( + db, + contribution_id, + publisher_key); +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/database/database_contribution_info.h b/components/brave_rewards/browser/database/database_contribution_info.h index 4501262b3620..db3bca17f8cb 100644 --- a/components/brave_rewards/browser/database/database_contribution_info.h +++ b/components/brave_rewards/browser/database/database_contribution_info.h @@ -38,6 +38,25 @@ class DatabaseContributionInfo: public DatabaseTable { const ledger::ActivityMonth month, const int year); + bool GetNotCompletedRecords( + sql::Database* db, + ledger::ContributionInfoList* list); + + ledger::ContributionInfoPtr GetRecord( + sql::Database* db, + const std::string& contribution_id); + + bool UpdateStepAndCount( + sql::Database* db, + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count); + + bool UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key); + private: const char* table_name_ = "contribution_info"; const int minimum_version_ = 2; diff --git a/components/brave_rewards/browser/database/database_contribution_info_publishers.cc b/components/brave_rewards/browser/database/database_contribution_info_publishers.cc index 7ee351ee290c..cc65fdd569bd 100644 --- a/components/brave_rewards/browser/database/database_contribution_info_publishers.cc +++ b/components/brave_rewards/browser/database/database_contribution_info_publishers.cc @@ -119,8 +119,12 @@ bool DatabaseContributionInfoPublishers::InsertOrUpdate( return false; } - const std::string query = base::StringPrintf( - "INSERT OR REPLACE INTO %s " + const std::string query_delete = base::StringPrintf( + "DELETE FROM %s WHERE contribution_id = ? AND publisher_key = ?", + table_name_); + + const std::string query_insert = base::StringPrintf( + "INSERT INTO %s " "(contribution_id, publisher_key, total_amount, contributed_amount) " "VALUES (?, ?, ?, ?)", table_name_); @@ -131,14 +135,20 @@ bool DatabaseContributionInfoPublishers::InsertOrUpdate( } for (const auto& publisher : info->publishers) { - sql::Statement statement( - db->GetCachedStatement(SQL_FROM_HERE, query.c_str())); - - statement.BindString(0, publisher->contribution_id); - statement.BindString(1, publisher->publisher_key); - statement.BindDouble(2, publisher->total_amount); - statement.BindDouble(3, publisher->contributed_amount); - statement.Run(); + sql::Statement statement_delete( + db->GetUniqueStatement(query_delete.c_str())); + + statement_delete.BindString(0, publisher->contribution_id); + statement_delete.BindString(1, publisher->publisher_key); + statement_delete.Run(); + + sql::Statement statement_insert( + db->GetUniqueStatement(query_insert.c_str())); + statement_insert.BindString(0, publisher->contribution_id); + statement_insert.BindString(1, publisher->publisher_key); + statement_insert.BindDouble(2, publisher->total_amount); + statement_insert.BindDouble(3, publisher->contributed_amount); + statement_insert.Run(); } return transaction.Commit(); @@ -175,4 +185,30 @@ bool DatabaseContributionInfoPublishers::GetRecords( return true; } +bool DatabaseContributionInfoPublishers::UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key) { + DCHECK(db); + if (!db || contribution_id.empty() || publisher_key.empty()) { + return false; + } + + const std::string query = base::StringPrintf( + "UPDATE %s SET contributed_amount=" + "(SELECT total_amount WHERE contribution_id = ? AND publisher_key = ?) " + "WHERE contribution_id = ? AND publisher_key = ?;", + table_name_); + + sql::Statement statement( + db->GetCachedStatement(SQL_FROM_HERE, query.c_str())); + + statement.BindString(0, contribution_id); + statement.BindString(1, publisher_key); + statement.BindString(2, contribution_id); + statement.BindString(3, publisher_key); + + return statement.Run(); +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/database/database_contribution_info_publishers.h b/components/brave_rewards/browser/database/database_contribution_info_publishers.h index 2b89942c579d..a0c0207a10de 100644 --- a/components/brave_rewards/browser/database/database_contribution_info_publishers.h +++ b/components/brave_rewards/browser/database/database_contribution_info_publishers.h @@ -38,6 +38,11 @@ class DatabaseContributionInfoPublishers: public DatabaseTable { const std::string& contribution_id, ledger::ContributionPublisherList* list); + bool UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key); + private: const char* table_name_ = "contribution_info_publishers"; const int minimum_version_ = 11; diff --git a/components/brave_rewards/browser/database/publisher_info_database.cc b/components/brave_rewards/browser/database/publisher_info_database.cc index 5f2394a9823d..1478517fa3b8 100644 --- a/components/brave_rewards/browser/database/publisher_info_database.cc +++ b/components/brave_rewards/browser/database/publisher_info_database.cc @@ -175,6 +175,53 @@ void PublisherInfoDatabase::GetOneTimeTips( contribution_info_->GetOneTimeTips(&GetDB(), list, month, year); } +void PublisherInfoDatabase::GetIncompleteContributions( + ledger::ContributionInfoList* list) { + DCHECK(list); + if (!IsInitialized() || !list) { + return; + } + + contribution_info_->GetNotCompletedRecords(&GetDB(), list); +} + +ledger::ContributionInfoPtr PublisherInfoDatabase::GetContributionInfo( + const std::string& contribution_id) { + if (!IsInitialized()) { + return nullptr; + } + + return contribution_info_->GetRecord(&GetDB(), contribution_id); +} + +bool PublisherInfoDatabase::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count) { + if (!IsInitialized()) { + return false; + } + + return contribution_info_->UpdateStepAndCount( + &GetDB(), + contribution_id, + step, + retry_count); +} + +bool PublisherInfoDatabase::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key) { + if (!IsInitialized()) { + return false; + } + + return contribution_info_->UpdateContributedAmount( + &GetDB(), + contribution_id, + publisher_key); +} + /** * * PUBLISHER INFO diff --git a/components/brave_rewards/browser/database/publisher_info_database.h b/components/brave_rewards/browser/database/publisher_info_database.h index e250a040fbbc..ddf8d10512b7 100644 --- a/components/brave_rewards/browser/database/publisher_info_database.h +++ b/components/brave_rewards/browser/database/publisher_info_database.h @@ -139,6 +139,21 @@ class PublisherInfoDatabase { bool DeleteActivityInfo(const std::string& publisher_key, uint64_t reconcile_stamp); + void GetIncompleteContributions( + ledger::ContributionInfoList* list); + + ledger::ContributionInfoPtr GetContributionInfo( + const std::string& contribution_id); + + bool UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count); + + bool UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key); + // Vacuums the database. This will cause sqlite to defragment and collect // unused space in the file. It can be VERY SLOW. void Vacuum(); diff --git a/components/brave_rewards/browser/database/publisher_info_database_unittest.cc b/components/brave_rewards/browser/database/publisher_info_database_unittest.cc index 4ab8bea75a53..20172d72e6f4 100644 --- a/components/brave_rewards/browser/database/publisher_info_database_unittest.cc +++ b/components/brave_rewards/browser/database/publisher_info_database_unittest.cc @@ -161,7 +161,7 @@ TEST_F(PublisherInfoDatabaseTest, InsertOrUpdateContributionInfo) { info->contribution_id = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; info->amount = 5.0; info->type = ledger::RewardsType::AUTO_CONTRIBUTE; - info->step = -1; + info->step = ledger::ContributionStep::STEP_COMPLETED; info->retry_count = -1; info->created_at = base::Time::Now().ToJsTime(); @@ -179,7 +179,7 @@ TEST_F(PublisherInfoDatabaseTest, InsertOrUpdateContributionInfo) { EXPECT_EQ(info_sql.ColumnString(0), info->contribution_id); EXPECT_EQ(info_sql.ColumnDouble(1), info->amount); EXPECT_EQ(info_sql.ColumnInt(2), static_cast(info->type)); - EXPECT_EQ(info_sql.ColumnInt(3), info->step); + EXPECT_EQ(info_sql.ColumnInt(3), static_cast(info->step)); EXPECT_EQ(info_sql.ColumnInt(4), info->retry_count); EXPECT_EQ(info_sql.ColumnInt64(5), static_cast(info->created_at)); } diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index 4ed492150213..48f24e036a65 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -4380,4 +4380,137 @@ void RewardsServiceImpl::OnGetAnonWalletStatus( std::move(callback).Run(static_cast(result)); } +ledger::ContributionInfoList GetNotCompletedContributionsOnFileTaskRunner( + PublisherInfoDatabase* backend) { + DCHECK(backend); + if (!backend) { + return {}; + } + + ledger::ContributionInfoList list; + backend->GetIncompleteContributions(&list); + return list; +} + +void RewardsServiceImpl::GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&GetNotCompletedContributionsOnFileTaskRunner, + publisher_info_backend_.get()), + base::BindOnce(&RewardsServiceImpl::OnGetNotCompletedContributions, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::OnGetNotCompletedContributions( + ledger::GetIncompleteContributionsCallback callback, + ledger::ContributionInfoList list) { + callback(std::move(list)); +} + +ledger::ContributionInfoPtr GetContributionInfoOnFileTaskRunner( + PublisherInfoDatabase* backend, + const std::string& contribution_id) { + DCHECK(backend); + if (!backend) { + return {}; + } + + return backend->GetContributionInfo(contribution_id); +} + +void RewardsServiceImpl::GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&GetContributionInfoOnFileTaskRunner, + publisher_info_backend_.get(), + contribution_id), + base::BindOnce(&RewardsServiceImpl::OnGetContributionInfo, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::OnGetContributionInfo( + ledger::GetContributionInfoCallback callback, + ledger::ContributionInfoPtr info) { + callback(std::move(info)); +} + +ledger::Result UpdateContributionInfoStepAndCountOnFileTaskRunner( + PublisherInfoDatabase* backend, + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count) { + DCHECK(backend); + if (!backend) { + return {}; + } + + const bool success = backend->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count); + return success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR; +} + +void RewardsServiceImpl::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&UpdateContributionInfoStepAndCountOnFileTaskRunner, + publisher_info_backend_.get(), + contribution_id, + step, + retry_count), + base::BindOnce(&RewardsServiceImpl::OnResult, + AsWeakPtr(), + callback)); +} + +ledger::Result UpdateContributionInfoContributedAmountOnFileTaskRunner( + PublisherInfoDatabase* backend, + const std::string& contribution_id, + const std::string& publisher_key) { + DCHECK(backend); + if (!backend) { + return {}; + } + + const bool success = backend->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key); + return success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR; +} + +void RewardsServiceImpl::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&UpdateContributionInfoContributedAmountOnFileTaskRunner, + publisher_info_backend_.get(), + contribution_id, + publisher_key), + base::BindOnce(&RewardsServiceImpl::OnResult, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::ReconcileStampReset() { + for (auto& observer : observers_) { + observer.ReconcileStampReset(); + } +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index 19f23aac6c85..2c09923d6c50 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -737,6 +737,26 @@ class RewardsServiceImpl : public RewardsService, void UnblindedTokensReady() override; + void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) override; + + void GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) override; + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) override; + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) override; + + void ReconcileStampReset() override; + // end ledger::LedgerClient // Mojo Proxy methods @@ -800,6 +820,14 @@ class RewardsServiceImpl : public RewardsService, ledger::GetAllPromotionsCallback callback, ledger::PromotionMap promotions); + void OnGetNotCompletedContributions( + ledger::GetIncompleteContributionsCallback callback, + ledger::ContributionInfoList list); + + void OnGetContributionInfo( + ledger::GetContributionInfoCallback callback, + ledger::ContributionInfoPtr info); + #if defined(OS_ANDROID) ledger::Environment GetServerEnvironmentForAndroid(); void CreateWalletAttestationResult( diff --git a/components/brave_rewards/browser/rewards_service_observer.h b/components/brave_rewards/browser/rewards_service_observer.h index 79da205907fb..6f3cae18cd80 100644 --- a/components/brave_rewards/browser/rewards_service_observer.h +++ b/components/brave_rewards/browser/rewards_service_observer.h @@ -85,6 +85,7 @@ class RewardsServiceObserver : public base::CheckedObserver { const std::string& wallet_type) {} virtual void OnUnblindedTokensReady( brave_rewards::RewardsService* rewards_service) {} + virtual void ReconcileStampReset() {} // DO NOT ADD ANY MORE METHODS HERE UNLESS IT IS A BROADCAST NOTIFICATION // RewardsServiceObserver should not be used to return responses to the // caller. Method calls on RewardsService should use callbacks to return diff --git a/components/brave_rewards/resources/page/actions/rewards_actions.ts b/components/brave_rewards/resources/page/actions/rewards_actions.ts index fc1a9a724930..c0959e008522 100644 --- a/components/brave_rewards/resources/page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/page/actions/rewards_actions.ts @@ -306,3 +306,5 @@ export const onlyAnonWallet = () => action(types.ONLY_ANON_WALLET) export const onOnlyAnonWallet = (only: boolean) => action(types.ON_ONLY_ANON_WALLET, { only }) + +export const onReconcileStampReset = () => action(types.ON_RECONCILE_STAMP_RESET) diff --git a/components/brave_rewards/resources/page/brave_rewards_page.tsx b/components/brave_rewards/resources/page/brave_rewards_page.tsx index e52aee27eb26..135a49741d6e 100644 --- a/components/brave_rewards/resources/page/brave_rewards_page.tsx +++ b/components/brave_rewards/resources/page/brave_rewards_page.tsx @@ -237,6 +237,10 @@ window.cr.define('brave_rewards', function () { getActions().getBalance() } + function reconcileStampReset () { + getActions().onReconcileStampReset() + } + return { initialize, walletCreated, @@ -280,7 +284,8 @@ window.cr.define('brave_rewards', function () { processRewardsPageUrl, disconnectWallet, onlyAnonWallet, - unblindedTokensReady + unblindedTokensReady, + reconcileStampReset } }) diff --git a/components/brave_rewards/resources/page/constants/rewards_types.ts b/components/brave_rewards/resources/page/constants/rewards_types.ts index 104bdf150761..184e332266f0 100644 --- a/components/brave_rewards/resources/page/constants/rewards_types.ts +++ b/components/brave_rewards/resources/page/constants/rewards_types.ts @@ -86,5 +86,6 @@ export const enum types { HIDE_REDIRECT_MODAL = '@@rewards/HIDE_REDIRECT_MODAL', DISCONNECT_WALLET = '@@rewards/DISCONNECT_WALLET', ONLY_ANON_WALLET = '@@rewards/ONLY_ANON_WALLET', - ON_ONLY_ANON_WALLET = '@@rewards/ON_ONLY_ANON_WALLET' + ON_ONLY_ANON_WALLET = '@@rewards/ON_ONLY_ANON_WALLET', + ON_RECONCILE_STAMP_RESET = '@@rewards/ON_RECONCILE_STAMP_RESET' } diff --git a/components/brave_rewards/resources/page/reducers/publishers_reducer.ts b/components/brave_rewards/resources/page/reducers/publishers_reducer.ts index e74b1d583255..09d6fc6cf85b 100644 --- a/components/brave_rewards/resources/page/reducers/publishers_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/publishers_reducer.ts @@ -81,6 +81,9 @@ const publishersReducer: Reducer = (state: Rewards.St case types.GET_EXCLUDED_SITES: chrome.send('brave_rewards.getExcludedSites') break + case types.ON_RECONCILE_STAMP_RESET: + chrome.send('brave_rewards.getContributionList') + break } return state diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc index d4a9225b2c81..f3ac9a4e83d1 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc @@ -1044,4 +1044,70 @@ void BatLedgerClientMojoProxy::UnblindedTokensReady() { bat_ledger_client_->UnblindedTokensReady(); } +void OnGetNotCompletedContributions( + ledger::GetIncompleteContributionsCallback callback, + ledger::ContributionInfoList list) { + callback(std::move(list)); +} + +void BatLedgerClientMojoProxy::GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) { + bat_ledger_client_->GetIncompleteContributions( + base::BindOnce(&OnGetNotCompletedContributions, std::move(callback))); +} + +void OnGetContributionInfo( + ledger::GetContributionInfoCallback callback, + ledger::ContributionInfoPtr info) { + callback(std::move(info)); +} + +void BatLedgerClientMojoProxy::GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) { + bat_ledger_client_->GetContributionInfo( + contribution_id, + base::BindOnce(&OnGetContributionInfo, std::move(callback))); +} + +void OnUpdateContributionInfoStepAndCount( + ledger::ResultCallback callback, + const ledger::Result result) { + callback(result); +} + +void BatLedgerClientMojoProxy::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) { + bat_ledger_client_->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count, + base::BindOnce(&OnUpdateContributionInfoStepAndCount, + std::move(callback))); +} + +void OnUpdateContributionInfoContributedAmount( + ledger::ResultCallback callback, + const ledger::Result result) { + callback(result); +} + +void BatLedgerClientMojoProxy::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) { + bat_ledger_client_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + base::BindOnce(&OnUpdateContributionInfoContributedAmount, + std::move(callback))); +} + +void BatLedgerClientMojoProxy::ReconcileStampReset() { + bat_ledger_client_->ReconcileStampReset(); +} + } // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h index d4896edec714..d9eda508b1b9 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h @@ -236,6 +236,26 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, void UnblindedTokensReady() override; + void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) override; + + void GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) override; + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) override; + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) override; + + void ReconcileStampReset() override; + private: bool Connected() const; diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc index 9125e25c42c6..abdaf51ad7e0 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc @@ -1213,4 +1213,110 @@ void LedgerClientMojoProxy::UnblindedTokensReady() { ledger_client_->UnblindedTokensReady(); } +// static +void LedgerClientMojoProxy::OnGetNotCompletedContributions( + CallbackHolder* holder, + ledger::ContributionInfoList list) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(std::move(list)); + } + delete holder; +} + +void LedgerClientMojoProxy::GetIncompleteContributions( + GetIncompleteContributionsCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->GetIncompleteContributions( + std::bind(LedgerClientMojoProxy::OnGetNotCompletedContributions, + holder, + _1)); +} + +// static +void LedgerClientMojoProxy::OnGetContributionInfo( + CallbackHolder* holder, + ledger::ContributionInfoPtr info) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(std::move(info)); + } + delete holder; +} + +void LedgerClientMojoProxy::GetContributionInfo( + const std::string& contribution_id, + GetContributionInfoCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->GetContributionInfo( + contribution_id, + std::bind(LedgerClientMojoProxy::OnGetContributionInfo, + holder, + _1)); +} + +// static +void LedgerClientMojoProxy::OnUpdateContributionInfoStepAndCount( + CallbackHolder* holder, + const ledger::Result result) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(result); + } + delete holder; +} + +void LedgerClientMojoProxy::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + UpdateContributionInfoStepAndCountCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count, + std::bind(LedgerClientMojoProxy::OnUpdateContributionInfoStepAndCount, + holder, + _1)); +} + +// static +void LedgerClientMojoProxy::OnUpdateContributionInfoContributedAmount( + CallbackHolder* holder, + const ledger::Result result) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(result); + } + delete holder; +} + +void LedgerClientMojoProxy::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + UpdateContributionInfoContributedAmountCallback callback) { + auto* holder = + new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + std::bind( + LedgerClientMojoProxy::OnUpdateContributionInfoContributedAmount, + holder, + _1)); +} + +void LedgerClientMojoProxy::ReconcileStampReset() { + ledger_client_->ReconcileStampReset(); +} + } // namespace bat_ledger diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h index b008bf547c2d..67f5f8f6e500 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h @@ -256,6 +256,26 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, void UnblindedTokensReady() override; + void GetIncompleteContributions( + GetIncompleteContributionsCallback callback) override; + + void GetContributionInfo( + const std::string& contribution_id, + GetContributionInfoCallback callback) override; + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + UpdateContributionInfoStepAndCountCallback callback) override; + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + UpdateContributionInfoContributedAmountCallback callback) override; + + void ReconcileStampReset() override; + private: // workaround to pass base::OnceCallback into std::bind // also serves as a wrapper for passing ledger::LedgerCallbackHandler* @@ -468,6 +488,22 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, CallbackHolder* holder, const ledger::Result result); + static void OnGetNotCompletedContributions( + CallbackHolder* holder, + ledger::ContributionInfoList list); + + static void OnGetContributionInfo( + CallbackHolder* holder, + ledger::ContributionInfoPtr info); + + static void OnUpdateContributionInfoStepAndCount( + CallbackHolder* holder, + const ledger::Result result); + + static void OnUpdateContributionInfoContributedAmount( + CallbackHolder* holder, + const ledger::Result result); + ledger::LedgerClient* ledger_client_; DISALLOW_COPY_AND_ASSIGN(LedgerClientMojoProxy); diff --git a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom index 09202b050ea6..155807c18dd8 100644 --- a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom +++ b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom @@ -297,4 +297,14 @@ interface BatLedgerClient { [Sync] GetClientInfo() => (ledger.mojom.ClientInfo info); UnblindedTokensReady(); + + GetIncompleteContributions() => (array list); + + GetContributionInfo(string contribution_id) => (ledger.mojom.ContributionInfo info); + + UpdateContributionInfoStepAndCount(string contribution_id, ledger.mojom.ContributionStep step, int32 retry_count) => (ledger.mojom.Result result); + + UpdateContributionInfoContributedAmount(string contribution_id, string publisher_key) => (ledger.mojom.Result result); + + ReconcileStampReset(); }; 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 ab9d5a1d3a6f..d16401bee89a 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 @@ -375,6 +375,26 @@ class MockConfirmationsClient : public ConfirmationsClient { MOCK_METHOD0(GetClientInfo, ledger::ClientInfoPtr()); MOCK_METHOD0(UnblindedTokensReady, void()); + + MOCK_METHOD1(GetIncompleteContributions, void( + ledger::GetIncompleteContributionsCallback callback)); + + MOCK_METHOD2(GetContributionInfo, void( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback)); + + MOCK_METHOD4(UpdateContributionInfoStepAndCount, void( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback)); + + MOCK_METHOD3(UpdateContributionInfoContributedAmount, void( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback)); + + MOCK_METHOD0(ReconcileStampReset, void()); }; } // namespace confirmations 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 cfdb90981f21..4444a51eb1d9 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h @@ -76,6 +76,12 @@ using GetPromotionCallback = std::function; using GetAllUnblindedTokensCallback = std::function; using GetAllPromotionsCallback = std::function; +using GetIncompleteContributionsCallback = + std::function; + +using GetContributionInfoCallback = + std::function; + class LEDGER_EXPORT LedgerClient { public: virtual ~LedgerClient() = default; @@ -321,6 +327,26 @@ class LEDGER_EXPORT LedgerClient { virtual ledger::ClientInfoPtr GetClientInfo() = 0; virtual void UnblindedTokensReady() = 0; + + virtual void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) = 0; + + virtual void GetContributionInfo( + const std::string& contribution_id, + GetContributionInfoCallback callback) = 0; + + virtual void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ResultCallback callback) = 0; + + virtual void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ResultCallback callback) = 0; + + virtual void ReconcileStampReset() = 0; }; } // namespace ledger diff --git a/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h b/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h index 37b6ceca79ec..76a1c2d0404e 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h +++ b/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h @@ -36,6 +36,7 @@ using ClientInfoPtr = mojom::ClientInfoPtr; using ContributionInfo = mojom::ContributionInfo; using ContributionInfoPtr = mojom::ContributionInfoPtr; +using ContributionInfoList = std::vector; using ContributionPublisher = mojom::ContributionPublisher; using ContributionPublisherPtr = mojom::ContributionPublisherPtr; @@ -54,6 +55,8 @@ using ContributionQueuePublisherList = using ContributionRetry = mojom::ContributionRetry; +using ContributionStep = mojom::ContributionStep; + using Environment = ledger::mojom::Environment; using ExcludeFilter = mojom::ExcludeFilter; diff --git a/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom b/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom index afd47232f428..ac5a84205ee2 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom +++ b/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom @@ -1,13 +1,24 @@ +// 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/. +// 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/. module ledger.mojom; +enum ContributionStep { + STEP_AC_TABLE_EMPTY = -4, + STEP_NOT_ENOUGH_FUNDS = -3, + STEP_FAILED = -2, + STEP_COMPLETED = -1, + STEP_NO = 0, + STEP_START = 1, + STEP_SUGGESTIONS = 2 +}; + struct ContributionInfo { string contribution_id; double amount; RewardsType type; - int32 step; + ContributionStep step; int32 retry_count; uint64 created_at; @@ -389,4 +400,4 @@ struct RecurringTip { string publisher_key; double amount; uint64 created_at; -}; \ No newline at end of file +}; 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 d572b011ca31..bf1ad1958fef 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 @@ -32,6 +32,26 @@ using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; +namespace { + ledger::ContributionStep ConvertResultIntoContributionStep( + const ledger::Result result) { + switch (result) { + case ledger::Result::LEDGER_OK: { + return ledger::ContributionStep::STEP_COMPLETED; + } + case ledger::Result::AC_TABLE_EMPTY: { + return ledger::ContributionStep::STEP_AC_TABLE_EMPTY; + } + case ledger::Result::NOT_ENOUGH_FUNDS: { + return ledger::ContributionStep::STEP_NOT_ENOUGH_FUNDS; + } + default: { + return ledger::ContributionStep::STEP_FAILED; + } + } + } +} // namespace + namespace braveledger_contribution { Contribution::Contribution(bat_ledger::LedgerImpl* ledger) : @@ -51,6 +71,7 @@ Contribution::~Contribution() { void Contribution::Initialize() { phase_two_->Initialize(); uphold_->Initialize(); + unblinded_->Initialize(); // Resume in progress contributions ledger::CurrentReconciles currentReconciles = ledger_->GetCurrentReconciles(); @@ -352,6 +373,7 @@ void Contribution::OnTimer(uint32_t timer_id) { phase_two_->OnTimer(timer_id); unverified_->OnTimer(timer_id); uphold_->OnTimer(timer_id); + unblinded_->OnTimer(timer_id); if (timer_id == last_reconcile_timer_id_) { last_reconcile_timer_id_ = 0; @@ -363,6 +385,7 @@ void Contribution::OnTimer(uint32_t timer_id) { ProcessContributionQueue(); } + // DEPRECATED for (std::pair const& value : retry_timers_) { if (value.second == timer_id) { std::string viewing_id = value.first; @@ -393,12 +416,13 @@ void Contribution::SetTimer(uint32_t* timer_id, uint64_t start_timer_in) { } BLOG(ledger_, ledger::LogLevel::LOG_INFO) - << "Starts in " + << "Timer will start in " << start_timer_in; ledger_->SetTimer(start_timer_in, timer_id); } +// DEPRECATED void Contribution::ReconcileSuccess( const std::string& viewing_id, const double amount, @@ -428,7 +452,7 @@ void Contribution::ReconcileSuccess( info->contribution_id = viewing_id; info->amount = amount; info->type = reconcile.type; - info->step = -1; + info->step = ledger::ContributionStep::STEP_COMPLETED; info->retry_count = -1; info->created_at = now; info->publishers = std::move(publisher_list); @@ -440,6 +464,27 @@ void Contribution::ReconcileSuccess( } } +void Contribution::ContributionCompleted( + const std::string& contribution_id, + const ledger::RewardsType type, + const double amount, + const ledger::Result result) { + if (result == ledger::Result::LEDGER_OK) { + ledger_->SetBalanceReportItem( + braveledger_time_util::GetCurrentMonth(), + braveledger_time_util::GetCurrentYear(), + GetReportTypeFromRewardsType(type), + amount); + } + + ledger_->UpdateContributionInfoStepAndCount( + contribution_id, + ConvertResultIntoContributionStep(result), + -1, + [](const ledger::Result _){}); +} + +// DEPRECATED void Contribution::AddRetry( ledger::ContributionRetry step, const std::string& viewing_id, @@ -477,6 +522,7 @@ void Contribution::AddRetry( SetTimer(&retry_timers_[viewing_id], start_timer_in); } +// DEPRECATED uint64_t Contribution::GetRetryTimer( ledger::ContributionRetry step, const std::string& viewing_id, @@ -526,6 +572,7 @@ uint64_t Contribution::GetRetryTimer( return 0; } +// DEPRECATED int Contribution::GetRetryPhase(ledger::ContributionRetry step) { int phase = 0; @@ -553,6 +600,7 @@ int Contribution::GetRetryPhase(ledger::ContributionRetry step) { return phase; } +// DEPRECATED void Contribution::DoRetry(const std::string& viewing_id) { auto reconcile = ledger_->GetReconcileById(viewing_id); @@ -751,19 +799,6 @@ bool Contribution::ProcessReconcileUnblindedTokens( return false; } - auto reconcile = ledger::CurrentReconcileProperties(); - reconcile.viewing_id = ledger_->GenerateGUID(); - reconcile.fee = *fee; - reconcile.directions = directions; - reconcile.type = type; - - if (ledger_->ReconcileExists(reconcile.viewing_id)) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) - << "Unable to reconcile with the same viewing id: " - << reconcile.viewing_id; - return false; - } - const double balance = braveledger_wallet::Balance::GetPerWalletBalance( ledger::kWalletUnBlinded, @@ -772,28 +807,53 @@ bool Contribution::ProcessReconcileUnblindedTokens( return false; } - if (balance >= *fee) { - ledger_->AddReconcile(reconcile.viewing_id, reconcile); - unblinded_->Start(reconcile.viewing_id); - return true; - } + const std::string contribution_id = ledger_->GenerateGUID(); - *fee = *fee - balance; - reconcile.fee = balance; + const uint64_t now = static_cast(base::Time::Now().ToDoubleT()); + auto contribution = ledger::ContributionInfo::New(); + contribution->contribution_id = contribution_id; + contribution->amount = *fee; + contribution->type = type; + contribution->step = ledger::ContributionStep::STEP_START; + contribution->retry_count = -1; + contribution->created_at = now; + + ledger::ReconcileDirections new_directions; + bool full_amount = true; + if (balance < *fee) { + contribution->amount = *fee - balance; + full_amount = false; + + if (type == ledger::RewardsType::RECURRING_TIP || + type == ledger::RewardsType::ONE_TIME_TIP) { + AdjustTipsAmounts( + directions, + &new_directions, + leftovers, + balance); + } + } else { + new_directions = directions; + } - if (type == ledger::RewardsType::RECURRING_TIP || - type == ledger::RewardsType::ONE_TIME_TIP) { - ledger::ReconcileDirections new_directions; - AdjustTipsAmounts(directions, - &new_directions, - leftovers, - balance); - reconcile.directions = new_directions; + ledger::ContributionPublisherList publisher_list; + for (auto& item : new_directions) { + auto publisher = ledger::ContributionPublisher::New(); + publisher->contribution_id = contribution_id; + publisher->publisher_key = item.publisher_key; + publisher->total_amount = + (item.amount_percent * contribution->amount) / 100; + publisher->contributed_amount = 0; + publisher_list.push_back(std::move(publisher)); } - ledger_->AddReconcile(reconcile.viewing_id, reconcile); - unblinded_->Start(reconcile.viewing_id); - return false; + contribution->publishers = std::move(publisher_list); + ledger_->SaveContributionInfo( + std::move(contribution), + [](const ledger::Result){}); + unblinded_->Start(contribution_id); + + return full_amount; } bool Contribution::ProcessReconcileAnonize( @@ -938,12 +998,12 @@ void Contribution::AdjustTipsAmounts( } if (item.amount_percent > reduce_fee_for) { - // anon wallet + // primary wallet const auto original_weight = item.amount_percent; item.amount_percent = reduce_fee_for; primary_directions->push_back(item); - // rest to normal wallet + // second wallet item.amount_percent = original_weight - reduce_fee_for; rest_directions->push_back(item); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h index e38cdc358974..10b70be0a588 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h @@ -137,11 +137,20 @@ class Contribution { // Does final stage in contribution // Sets reports and contribution info + // DEPRECATED void ReconcileSuccess( const std::string& viewing_id, const double amount, const bool delete_reconcile); + // Does final stage in contribution + // Sets reports and contribution info + void ContributionCompleted( + const std::string& contribution_id, + const ledger::RewardsType type, + const double amount, + const ledger::Result result); + void HasSufficientBalance( ledger::HasSufficientBalanceToReconcileCallback callback); @@ -154,11 +163,17 @@ class Contribution { void SetTimer(uint32_t* timer_id, uint64_t start_timer_in = 0); + // DEPRECATED void AddRetry( ledger::ContributionRetry step, const std::string& viewing_id, ledger::CurrentReconcileProperties reconcile = {}); + void UpdateContributionStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count); + // Resets reconcile stamps void ResetReconcileStamp(); @@ -204,14 +219,19 @@ class Contribution { const ledger::Result result, ledger::BalancePtr info); + // DEPRECATED uint64_t GetRetryTimer(ledger::ContributionRetry step, const std::string& viewing_id, ledger::CurrentReconcileProperties* reconcile); + // DEPRECATED int GetRetryPhase(ledger::ContributionRetry step); + // DEPRECATED void DoRetry(const std::string& viewing_id); + void CheckStep(const std::string& contribution_id); + void OnHasSufficientBalance( const ledger::PublisherInfoList& publisher_list, const uint32_t record, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc index 7c6d00a10f71..47d088fe4c43 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc @@ -25,12 +25,7 @@ using challenge_bypass_ristretto::UnblindedToken; using challenge_bypass_ristretto::VerificationKey; using challenge_bypass_ristretto::VerificationSignature; -namespace braveledger_contribution { - -Unblinded::Unblinded(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { -} - -Unblinded::~Unblinded() = default; +namespace { std::string ConvertTypeToString(const ledger::RewardsType type) { switch (static_cast(type)) { @@ -52,27 +47,19 @@ std::string ConvertTypeToString(const ledger::RewardsType type) { } void GenerateSuggestionMock( - ledger::UnblindedTokenPtr token, + const ledger::UnblindedToken& token, const std::string& suggestion_encoded, base::Value* result) { - if (!token) { - return; - } - - result->SetStringKey("t", token->token_value); - result->SetStringKey("publicKey", token->public_key); - result->SetStringKey("signature", token->token_value); + result->SetStringKey("t", token.token_value); + result->SetStringKey("publicKey", token.public_key); + result->SetStringKey("signature", token.token_value); } void GenerateSuggestion( - ledger::UnblindedTokenPtr token, + const ledger::UnblindedToken& token, const std::string& suggestion_encoded, base::Value* result) { - if (!token) { - return; - } - - UnblindedToken unblinded = UnblindedToken::decode_base64(token->token_value); + UnblindedToken unblinded = UnblindedToken::decode_base64(token.token_value); VerificationKey verification_key = unblinded.derive_verification_key(); VerificationSignature signature = verification_key.sign(suggestion_encoded); const std::string pre_image = unblinded.preimage().encode_base64(); @@ -84,24 +71,20 @@ void GenerateSuggestion( } result->SetStringKey("t", pre_image); - result->SetStringKey("publicKey", token->public_key); + result->SetStringKey("publicKey", token.public_key); result->SetStringKey("signature", signature.encode_base64()); } -bool HasTokenExpired(ledger::UnblindedTokenPtr token) { - if (!token) { - return true; - } - +bool HasTokenExpired(const ledger::UnblindedToken& token) { const uint64_t now = static_cast(base::Time::Now().ToDoubleT()); - return token->expires_at > 0 && token->expires_at < now; + return token.expires_at > 0 && token.expires_at < now; } std::string GenerateTokenPayload( const std::string& publisher_key, const ledger::RewardsType type, - ledger::UnblindedTokenList list) { + const std::vector& list) { base::Value suggestion(base::Value::Type::DICTIONARY); suggestion.SetStringKey("type", ConvertTypeToString(type)); suggestion.SetStringKey("channel", publisher_key); @@ -115,9 +98,9 @@ std::string GenerateTokenPayload( for (auto & item : list) { base::Value token(base::Value::Type::DICTIONARY); if (ledger::is_testing) { - GenerateSuggestionMock(std::move(item), suggestion_encoded, &token); + GenerateSuggestionMock(item, suggestion_encoded, &token); } else { - GenerateSuggestion(std::move(item), suggestion_encoded, &token); + GenerateSuggestion(item, suggestion_encoded, &token); } credentials.GetList().push_back(std::move(token)); } @@ -131,176 +114,405 @@ std::string GenerateTokenPayload( return json; } -void Unblinded::Start(const std::string& viewing_id) { +bool GetStatisticalVotingWinner( + double dart, + const double amount, + const std::vector& list, + braveledger_contribution::Winners* winners) { + if (!winners) { + return false; + } + + double upper = 0.0; + for (auto& item : list) { + upper += item.total_amount / amount; + if (upper < dart) { + continue; + } + + auto iter = winners->find(item.publisher_key); + + uint32_t current_value = 0; + if (iter != winners->end()) { + current_value = winners->at(item.publisher_key); + winners->at(item.publisher_key) = current_value + 1; + } else { + winners->emplace(item.publisher_key, 1); + } + + return true; + } + + return false; +} + +void GetStatisticalVotingWinners( + uint32_t total_votes, + const double amount, + const ledger::ContributionPublisherList& list, + braveledger_contribution::Winners* winners) { + std::vector converted_list; + + for (auto& item : list) { + ledger::ContributionPublisher new_item; + new_item.total_amount = item->total_amount; + new_item.publisher_key = item->publisher_key; + converted_list.push_back(new_item); + } + + while (total_votes > 0) { + double dart = brave_base::random::Uniform_01(); + if (GetStatisticalVotingWinner(dart, amount, converted_list, winners)) { + --total_votes; + } + } +} + +int32_t GetRetryCount( + const ledger::ContributionStep step, + ledger::ContributionInfoPtr contribution) { + if (!contribution || step != contribution->step) { + return 0; + } + + return contribution->retry_count + 1; +} + +} // namespace + +namespace braveledger_contribution { + +Unblinded::Unblinded(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { +} + +Unblinded::~Unblinded() = default; + +void Unblinded::Initialize() { + auto callback = std::bind(&Unblinded::OnGetNotCompletedContributions, + this, + _1); + ledger_->GetIncompleteContributions(callback); +} + +void Unblinded::OnGetNotCompletedContributions( + ledger::ContributionInfoList list) { + if (list.size() == 0) { + return; + } + + if (!list[0]) { + return; + } + + DoRetry(std::move(list[0])); +} + +void Unblinded::Start(const std::string& contribution_id) { + GetContributionInfoAndUnblindedTokens( + contribution_id, + std::bind(&Unblinded::PrepareTokens, + this, + _1, + _2)); +} + +void Unblinded::GetContributionInfoAndUnblindedTokens( + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback) { ledger_->GetAllUnblindedTokens( - std::bind(&Unblinded::OnUnblindedTokens, - this, - viewing_id, - _1)); + std::bind(&Unblinded::OnUnblindedTokens, + this, + _1, + contribution_id, + callback)); } void Unblinded::OnUnblindedTokens( - const std::string& viewing_id, - ledger::UnblindedTokenList list) { + ledger::UnblindedTokenList list, + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback) { if (list.empty()) { - ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, viewing_id); + ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, nullptr); return; } - const auto reconcile = ledger_->GetReconcileById(viewing_id); + std::vector converted_list; + for (auto& item : list) { + ledger::UnblindedToken new_item; + new_item.id = item->id; + new_item.token_value = item->token_value; + new_item.public_key = item->public_key; + new_item.value = item->value; + new_item.promotion_id = item->promotion_id; + new_item.expires_at = item->expires_at; + + converted_list.push_back(new_item); + } + + ledger_->GetContributionInfo(contribution_id, + std::bind(&Unblinded::OnGetContributionInfo, + this, + _1, + converted_list, + callback)); +} + +void Unblinded::OnGetContributionInfo( + ledger::ContributionInfoPtr contribution, + const std::vector& list, + GetContributionInfoAndUnblindedTokensCallback callback) { + callback(std::move(contribution), list); +} + +void Unblinded::PrepareTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list) { + if (!contribution) { + return; + } + + const int32_t retry_count = GetRetryCount( + ledger::ContributionStep::STEP_START, + contribution->Clone()); + + ledger_->UpdateContributionInfoStepAndCount( + contribution->contribution_id, + ledger::ContributionStep::STEP_START, + retry_count, + [](const ledger::Result){}); + double current_amount = 0.0; - ledger::UnblindedTokenList token_list; + std::vector token_list; std::vector delete_list; for (auto & item : list) { - if (HasTokenExpired(item->Clone())) { - delete_list.push_back(std::to_string(item->id)); + if (HasTokenExpired(item)) { + delete_list.push_back(std::to_string(item.id)); continue; } - if (current_amount >= reconcile.fee) { + if (current_amount >= contribution->amount) { break; } current_amount += 0.25; - token_list.push_back(std::move(item)); + token_list.push_back(item); } if (delete_list.size() > 0) { ledger_->DeleteUnblindedTokens(delete_list, [](const ledger::Result _){}); } - if (current_amount < reconcile.fee) { - ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, viewing_id); + if (current_amount < contribution->amount) { + ContributionCompleted( + ledger::Result::NOT_ENOUGH_FUNDS, + std::move(contribution)); return; } - MakeContribution(viewing_id, std::move(token_list)); + PreparePublishers(token_list, std::move(contribution)); } -void Unblinded::MakeContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list) { - const auto reconcile = ledger_->GetReconcileById(viewing_id); - - if (reconcile.type == ledger::RewardsType::ONE_TIME_TIP || - reconcile.type == ledger::RewardsType::RECURRING_TIP) { - const auto callback = std::bind(&Unblinded::ContributionCompleted, - this, - _1, - viewing_id); - SendTokens( - reconcile.directions.front().publisher_key, - reconcile.type, - std::move(list), - callback); +void Unblinded::PreparePublishers( + const std::vector& list, + ledger::ContributionInfoPtr contribution) { + if (!contribution) { return; } - if (reconcile.type == ledger::RewardsType::AUTO_CONTRIBUTE) { - PrepareAutoContribution(viewing_id, std::move(list)); + if (contribution->type == ledger::RewardsType::AUTO_CONTRIBUTE) { + auto publisher_list = + PrepareAutoContribution(list, contribution->Clone()); + + if (publisher_list.empty()) { + ContributionCompleted( + ledger::Result::AC_TABLE_EMPTY, + std::move(contribution)); + return; + } + + contribution->publishers = std::move(publisher_list); + + ledger_->SaveContributionInfo( + contribution->Clone(), + std::bind(&Unblinded::OnPrepareAutoContribution, + this, + _1, + contribution->contribution_id)); + return; } + + ProcessTokens(contribution->contribution_id); } -bool Unblinded::GetStatisticalVotingWinner( - double dart, - const ledger::ReconcileDirections& directions, - Winners* winners) const { - if (!winners) { - return false; +ledger::ContributionPublisherList Unblinded::PrepareAutoContribution( + const std::vector& list, + ledger::ContributionInfoPtr contribution) { + if (!contribution || list.size() == 0) { + return {}; } - double upper = 0.0; - for (const auto& item : directions) { - upper += item.amount_percent / 100.0; - if (upper < dart) { + const double total_votes = static_cast(list.size()); + Winners winners; + GetStatisticalVotingWinners( + total_votes, + contribution->amount, + std::move(contribution->publishers), + &winners); + + ledger::ContributionPublisherList publisher_list; + for (auto & winner : winners) { + if (winner.second == 0) { continue; } - auto iter = winners->find(item.publisher_key); + const std::string publisher_key = winner.first; + auto publisher = ledger::ContributionPublisher::New(); + publisher->contribution_id = contribution->contribution_id; + publisher->publisher_key = publisher_key; + publisher->total_amount = + (winner.second / total_votes) * contribution->amount; + publisher->contributed_amount = 0; + publisher_list.push_back(std::move(publisher)); + } - uint32_t current_value = 0; - if (iter != winners->end()) { - current_value = winners->at(item.publisher_key); - winners->at(item.publisher_key) = current_value + 1; - } else { - winners->emplace(item.publisher_key, 1); - } + return publisher_list; +} - return true; +void Unblinded::OnPrepareAutoContribution( + const ledger::Result result, + const std::string& contribution_id) { + if (result != ledger::Result::LEDGER_OK) { + SetTimer(contribution_id); + return; } - return false; + ProcessTokens(contribution_id); } -void Unblinded::GetStatisticalVotingWinners( - uint32_t total_votes, - const ledger::ReconcileDirections& directions, - Winners* winners) const { - while (total_votes > 0) { - double dart = brave_base::random::Uniform_01(); - if (GetStatisticalVotingWinner(dart, directions, winners)) { - --total_votes; - } - } +void Unblinded::ProcessTokens(const std::string& contribution_id) { + GetContributionInfoAndUnblindedTokens( + contribution_id, + std::bind(&Unblinded::OnProcessTokens, + this, + _1, + _2)); } -void Unblinded::PrepareAutoContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list) { - if (list.size() == 0) { - ContributionCompleted(ledger::Result::AC_TABLE_EMPTY, viewing_id); +void Unblinded::OnProcessTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list) { + if (!contribution) { return; } - auto reconcile = ledger_->GetReconcileById(viewing_id); - const double total_votes = static_cast(list.size()); - Winners winners; - GetStatisticalVotingWinners(total_votes, reconcile.directions, &winners); + const int32_t retry_count = GetRetryCount( + ledger::ContributionStep::STEP_SUGGESTIONS, + contribution->Clone()); - ledger::ReconcileDirections new_directions; - uint32_t current_position = 0; - for (auto & winner : winners) { - if (winner.second == 0) { + ledger_->UpdateContributionInfoStepAndCount( + contribution->contribution_id, + ledger::ContributionStep::STEP_SUGGESTIONS, + retry_count, + [](const ledger::Result){}); + + for (auto& publisher : contribution->publishers) { + if (publisher->total_amount == publisher->contributed_amount) { continue; } - ledger::ReconcileDirectionProperties direction; - direction.publisher_key = winner.first; - direction.amount_percent = (winner.second / total_votes) * 100; - new_directions.push_back(direction); + std::vector token_list; + double current_amount = 0.0; + for (auto& item : list) { + if (current_amount >= publisher->total_amount) { + break; + } - const uint32_t new_position = current_position + winner.second; - ledger::UnblindedTokenList new_list; - for (size_t i = current_position; i < new_position; i++) { - new_list.push_back(std::move(list[i])); + current_amount += item.value; + token_list.push_back(item); } - current_position = new_position; + + auto callback = std::bind(&Unblinded::TokenProcessed, + this, + _1, + contribution->contribution_id, + publisher->publisher_key); SendTokens( - winner.first, - ledger::RewardsType::AUTO_CONTRIBUTE, - std::move(new_list), - [](const ledger::Result _){}); + publisher->publisher_key, + contribution->type, + token_list, + callback); + return; + } + + ContributionCompleted(ledger::Result::LEDGER_OK, std::move(contribution)); +} + +void Unblinded::TokenProcessed( + const ledger::Result result, + const std::string& contribution_id, + const std::string& publisher_key) { + if (result == ledger::Result::LEDGER_OK) { + auto callback = std::bind(&Unblinded::OnTokenProcessed, + this, + _1, + contribution_id); + + ledger_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + callback); + return; + } + + SetTimer(contribution_id); +} + +void Unblinded::OnTokenProcessed( + const ledger::Result result, + const std::string& contribution_id) { + ledger_->GetContributionInfo( + contribution_id, + std::bind(&Unblinded::CheckIfCompleted, + this, + _1)); +} + +void Unblinded::CheckIfCompleted(ledger::ContributionInfoPtr contribution) { + if (!contribution) { + return; + } + + bool completed = true; + for (auto& publisher : contribution->publishers) { + if (publisher->total_amount == publisher->contributed_amount) { + continue; + } + + completed = false; + break; } - reconcile.directions = new_directions; - ledger_->UpdateReconcile(reconcile); + if (completed) { + ContributionCompleted(ledger::Result::LEDGER_OK, std::move(contribution)); + return; + } - ContributionCompleted(ledger::Result::LEDGER_OK, viewing_id); + SetTimer(contribution->contribution_id); } void Unblinded::SendTokens( const std::string& publisher_key, const ledger::RewardsType type, - ledger::UnblindedTokenList list, - SendTokensCallback callback) { + const std::vector& list, + ledger::ResultCallback callback) { if (publisher_key.empty() || list.empty()) { return callback(ledger::Result::LEDGER_ERROR); } std::vector token_id_list; for (auto & item : list) { - token_id_list.push_back(std::to_string(item->id)); + token_id_list.push_back(std::to_string(item.id)); } auto url_callback = std::bind(&Unblinded::OnSendTokens, @@ -314,7 +526,7 @@ void Unblinded::SendTokens( const std::string payload = GenerateTokenPayload( publisher_key, type, - std::move(list)); + list); const std::string url = braveledger_request_util::GetReedemSuggestionsUrl(); @@ -333,7 +545,7 @@ void Unblinded::OnSendTokens( const std::string& response, const std::map& headers, const std::vector& token_id_list, - SendTokensCallback callback) { + ledger::ResultCallback callback) { ledger_->LogResponse(__func__, response_status_code, response, headers); if (response_status_code != net::HTTP_OK) { callback(ledger::Result::LEDGER_ERROR); @@ -346,13 +558,76 @@ void Unblinded::OnSendTokens( void Unblinded::ContributionCompleted( const ledger::Result result, - const std::string& viewing_id) { - const auto reconcile = ledger_->GetReconcileById(viewing_id); - ledger_->ReconcileComplete( + ledger::ContributionInfoPtr contribution) { + if (!contribution) { + return; + } + + ledger_->ContributionCompleted( result, - reconcile.fee, - viewing_id, - reconcile.type); + contribution->amount, + contribution->contribution_id, + contribution->type); +} + +void Unblinded::SetTimer( + const std::string& contribution_id, + const uint64_t& start_timer_in) { + if (contribution_id.empty()) { + return; + } + + if (!retry_timers_[contribution_id]) { + retry_timers_[contribution_id] = 0u; + } + + uint64_t timer_seconds = start_timer_in; + if (ledger::short_retries) { + timer_seconds = 1; + } else if (start_timer_in == 0) { + timer_seconds = brave_base::random::Geometric(45); + } + + BLOG(ledger_, ledger::LogLevel::LOG_INFO) + << "Timer will start in " + << timer_seconds; + + ledger_->SetTimer(timer_seconds, &retry_timers_[contribution_id]); +} + +void Unblinded::OnTimer(uint32_t timer_id) { + for (std::pair const& value : retry_timers_) { + if (value.second == timer_id) { + std::string contribution_id = value.first; + CheckStep(contribution_id); + retry_timers_[contribution_id] = 0u; + } + } +} + +void Unblinded::CheckStep(const std::string& contribution_id) { + auto callback = std::bind(&Unblinded::DoRetry, + this, + _1); + ledger_->GetContributionInfo(contribution_id, callback); +} + +void Unblinded::DoRetry(ledger::ContributionInfoPtr contribution) { + if (!contribution) { + return; + } + + if (contribution->step == ledger::ContributionStep::STEP_START) { + Start(contribution->contribution_id); + return; + } + + if (contribution->step == ledger::ContributionStep::STEP_SUGGESTIONS) { + ProcessTokens(contribution->contribution_id); + return; + } + + NOTREACHED(); } } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h index 793e25f6f3b0..0b8711ddc158 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h @@ -21,8 +21,9 @@ class LedgerImpl; namespace braveledger_contribution { -using SendTokensCallback = - std::function; +using GetContributionInfoAndUnblindedTokensCallback = std::function& list)>; using Winners = std::map; @@ -31,49 +32,90 @@ class Unblinded { explicit Unblinded(bat_ledger::LedgerImpl* ledger); ~Unblinded(); - void Start(const std::string& viewing_id); + void Initialize(); + + void Start(const std::string& contribution_id); + + void OnTimer(uint32_t timer_id); private: + void OnGetNotCompletedContributions( + ledger::ContributionInfoList list); + + void GetContributionInfoAndUnblindedTokens( + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback); + void OnUnblindedTokens( - const std::string& viewing_id, - ledger::UnblindedTokenList list); + ledger::UnblindedTokenList list, + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback); + + void OnGetContributionInfo( + ledger::ContributionInfoPtr contribution, + const std::vector& list, + GetContributionInfoAndUnblindedTokensCallback callback); + + void PrepareTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list); + + void PreparePublishers( + const std::vector& list, + ledger::ContributionInfoPtr contribution); + + ledger::ContributionPublisherList PrepareAutoContribution( + const std::vector& list, + ledger::ContributionInfoPtr contribution); - void MakeContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list); + void OnPrepareAutoContribution( + const ledger::Result result, + const std::string& contribution_id); + + void ProcessTokens(const std::string& contribution_id); - bool GetStatisticalVotingWinner( - double dart, - const ledger::ReconcileDirections& directions, - Winners* winners) const; + void OnProcessTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list); - void PrepareAutoContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list); + void TokenProcessed( + const ledger::Result result, + const std::string& contribution_id, + const std::string& publisher_key); + + void OnTokenProcessed( + const ledger::Result result, + const std::string& contribution_id); - void GetStatisticalVotingWinners( - uint32_t total_votes, - const ledger::ReconcileDirections& directions, - Winners* winners) const; + void CheckIfCompleted(ledger::ContributionInfoPtr contribution); void SendTokens( const std::string& publisher_key, const ledger::RewardsType type, - ledger::UnblindedTokenList list, - SendTokensCallback callback); + const std::vector& list, + ledger::ResultCallback callback); void OnSendTokens( const int response_status_code, const std::string& response, const std::map& headers, const std::vector& token_id_list, - SendTokensCallback callback); + ledger::ResultCallback callback); void ContributionCompleted( const ledger::Result result, - const std::string& viewing_id); + ledger::ContributionInfoPtr contribution); + + void SetTimer( + const std::string& contribution_id, + const uint64_t& start_timer_in = 0); + + void CheckStep(const std::string& contribution_id); + + void DoRetry(ledger::ContributionInfoPtr contribution); bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::map retry_timers_; }; } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc index b360f0c67af8..c7f1d481958e 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc @@ -16,6 +16,10 @@ using ::testing::_; using ::testing::Invoke; +namespace { + const char contribution_id[] = "60770beb-3cfb-4550-a5db-deccafb5c790"; +} // namespace + namespace braveledger_contribution { class UnblindedTest : public ::testing::Test { @@ -35,44 +39,48 @@ class UnblindedTest : public ::testing::Test { } void SetUp() override { - ON_CALL(*mock_ledger_impl_, GetReconcileById(_)) - .WillByDefault( - Invoke([](const std::string& viewing_id) { - ledger::CurrentReconcileProperties reconcile; - reconcile.fee = 1.0; - return reconcile; - })); + ON_CALL(*mock_ledger_impl_, GetContributionInfo(contribution_id, _)) + .WillByDefault( + Invoke([]( + const std::string& id, + ledger::GetContributionInfoCallback callback) { + auto info = ledger::ContributionInfo::New(); + info->contribution_id = contribution_id; + info->amount = 1.0; + info->type = ledger::RewardsType::ONE_TIME_TIP; + info->step = ledger::ContributionStep::STEP_NO; + info->retry_count = -1; + + callback(std::move(info)); + })); } }; TEST_F(UnblindedTest, NotEnoughFunds) { - const std::string viewing_id = "some_id"; EXPECT_CALL(*mock_ledger_impl_, - ReconcileComplete(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _, _)); + ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _)); ON_CALL(*mock_ledger_impl_, GetAllUnblindedTokens(_)) .WillByDefault( Invoke([](ledger::GetAllUnblindedTokensCallback callback) { ledger::UnblindedTokenList list; - auto info = ledger::UnblindedToken::New(); - info->id = 1; - info->token_value = "asdfasdfasdfsad="; - info->value = 0.25; - info->expires_at = 32574133178; - list.push_back(info->Clone()); + auto info = ledger::UnblindedToken::New(); + info->id = 1; + info->token_value = "asdfasdfasdfsad="; + info->value = 0.25; + info->expires_at = 32574133178; + list.push_back(info->Clone()); callback(std::move(list)); })); - unblinded_->Start(viewing_id); + unblinded_->Start(contribution_id); } TEST_F(UnblindedTest, PromotionExpiredDeleteToken) { - const std::string viewing_id = "some_id"; EXPECT_CALL(*mock_ledger_impl_, - ReconcileComplete(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _, _)) - .Times(0); + ContributionCompleted(ledger::Result::LEDGER_OK, _, _, _)); std::vector delete_list; delete_list.push_back("1"); @@ -109,13 +117,12 @@ TEST_F(UnblindedTest, PromotionExpiredDeleteToken) { callback(std::move(list)); })); - unblinded_->Start(viewing_id); + unblinded_->Start(contribution_id); } TEST_F(UnblindedTest, PromotionExpiredDeleteTokensNotEnoughFunds) { - const std::string viewing_id = "some_id"; EXPECT_CALL(*mock_ledger_impl_, - ReconcileComplete(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _, _)); + ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _)); std::vector delete_list; delete_list.push_back("1"); @@ -140,7 +147,7 @@ TEST_F(UnblindedTest, PromotionExpiredDeleteTokensNotEnoughFunds) { callback(std::move(list)); })); - unblinded_->Start(viewing_id); + unblinded_->Start(contribution_id); } } // namespace braveledger_contribution 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 0a09e25912a1..987ef09c1046 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 @@ -374,6 +374,26 @@ class MockLedgerClient : public LedgerClient { MOCK_METHOD2(DeleteUnblindedTokensForPromotion, void(const std::string& promotion_id, ledger::ResultCallback)); + + MOCK_METHOD1(GetIncompleteContributions, void( + ledger::GetIncompleteContributionsCallback callback)); + + MOCK_METHOD2(GetContributionInfo, void( + const std::string& contribution_id, + GetContributionInfoCallback callback)); + + MOCK_METHOD4(UpdateContributionInfoStepAndCount, void( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ResultCallback callback)); + + MOCK_METHOD3(UpdateContributionInfoContributedAmount, void( + const std::string& contribution_id, + const std::string& publisher_key, + ResultCallback callback)); + + MOCK_METHOD0(ReconcileStampReset, void()); }; } // namespace ledger 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 bbf559fd5fed..a0494c2da41e 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 @@ -632,6 +632,26 @@ void LedgerImpl::ReconcileComplete( type); } +void LedgerImpl::ContributionCompleted( + const ledger::Result result, + const double amount, + const std::string& contribution_id, + const ledger::RewardsType type) { + bat_contribution_->ContributionCompleted( + contribution_id, + type, + amount, + result); + + // TODO(https://github.com/brave/brave-browser/issues/7717) + // rename to ContributionCompleted + ledger_client_->OnReconcileComplete( + result, + contribution_id, + amount, + type); +} + void LedgerImpl::OnWalletProperties( ledger::Result result, const ledger::WalletProperties& properties) { @@ -879,6 +899,7 @@ void LedgerImpl::UpdateAdsRewards() { void LedgerImpl::ResetReconcileStamp() { bat_state_->ResetReconcileStamp(); + ledger_client_->ReconcileStampReset(); } bool LedgerImpl::UpdateReconcile( @@ -1563,4 +1584,37 @@ void LedgerImpl::GetAnonWalletStatus(ledger::ResultCallback callback) { bat_wallet_->GetAnonWalletStatus(callback); } +void LedgerImpl::GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) { + ledger_client_->GetIncompleteContributions(callback); +} + +void LedgerImpl::GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) { + ledger_client_->GetContributionInfo(contribution_id, callback); +} + +void LedgerImpl::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) { + ledger_client_->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count, + callback); +} + +void LedgerImpl::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) { + ledger_client_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + callback); +} + } // namespace bat_ledger 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 6d9921cd54e6..4f21357fc4e6 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 @@ -215,13 +215,20 @@ class LedgerImpl : public ledger::Ledger, const ledger::UrlMethod method, ledger::LoadURLCallback callback); - virtual void ReconcileComplete( + // DEPRECATED + void ReconcileComplete( const ledger::Result result, const double amount, const std::string& viewing_id, const ledger::RewardsType type, const bool delete_reconcile = true); + virtual void ContributionCompleted( + const ledger::Result result, + const double amount, + const std::string& contribution_id, + const ledger::RewardsType type); + std::string URIEncode(const std::string& value) override; void SaveMediaVisit(const std::string& publisher_id, @@ -270,7 +277,7 @@ class LedgerImpl : public ledger::Ledger, ledger::ReportType type, const std::string& probi) override; - virtual ledger::CurrentReconcileProperties GetReconcileById( + ledger::CurrentReconcileProperties GetReconcileById( const std::string& viewingId); void RemoveReconcileById(const std::string& viewingId); @@ -600,6 +607,24 @@ class LedgerImpl : public ledger::Ledger, void GetAnonWalletStatus(ledger::ResultCallback callback) override; + void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback); + + virtual void GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback); + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback); + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback); + private: void OnLoad(ledger::VisitDataPtr visit_data, const uint64_t& current_time) override; 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 cc303181d897..80d4802d2650 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 @@ -194,6 +194,12 @@ class MockLedgerImpl : public LedgerImpl { const ledger::RewardsType, const bool)); + MOCK_METHOD4(ContributionCompleted, void( + const ledger::Result, + const double, + const std::string&, + const ledger::RewardsType)); + MOCK_METHOD1(URIEncode, std::string(const std::string&)); MOCK_METHOD5(SaveMediaVisit, @@ -568,6 +574,10 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD2(DeleteUnblindedTokensForPromotion, void(const std::string& promotion_id, ledger::ResultCallback)); + + MOCK_METHOD2(GetContributionInfo, void( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback)); }; } // namespace bat_ledger diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.mm b/vendor/brave-ios/Ledger/BATBraveLedger.mm index a6f599cfb005..a08a97f1c3c0 100644 --- a/vendor/brave-ios/Ledger/BATBraveLedger.mm +++ b/vendor/brave-ios/Ledger/BATBraveLedger.mm @@ -2002,4 +2002,29 @@ - (void)deleteUnblindedTokensForPromotion:(const std::string&)promotion_id callb // TODO please implement } +- (void)getIncompleteContributions:(ledger::GetIncompleteContributionsCallback)callback +{ + // TODO please implement +} + +- (void)getContributionInfo:(const std::string&)contribution_id callback:(ledger::GetContributionInfoCallback)callback +{ + // TODO please implement +} + +- (void)updateContributionInfoStepAndCount:(const std::string&)contribution_id step:(const ledger::ContributionStep)step retry_count:(const int32_t)retry_count callback:(ledger::ResultCallback)callback +{ + // TODO please implement +} + +- (void)updateContributionInfoContributedAmount:(const std::string&)contribution_id publisher_key:(const std::string&)publisher_key callback:(ledger::ResultCallback)callback +{ + // TODO please implement +} + +- (void)reconcileStampReset +{ + // TODO please implement +} + @end diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h index de809b544e0e..5c6e8dcc39c9 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h @@ -97,4 +97,9 @@ class NativeLedgerClient : public ledger::LedgerClient { void DeleteUnblindedTokensForPromotion(const std::string& promotion_id, ledger::ResultCallback callback) override; ledger::ClientInfoPtr GetClientInfo() override; void UnblindedTokensReady() override; + void GetIncompleteContributions(ledger::GetIncompleteContributionsCallback callback) override; + void GetContributionInfo(const std::string& contribution_id, ledger::GetContributionInfoCallback callback) override; + void UpdateContributionInfoStepAndCount(const std::string& contribution_id, const ledger::ContributionStep step, const int32_t retry_count, ledger::ResultCallback callback) override; + void UpdateContributionInfoContributedAmount(const std::string& contribution_id, const std::string& publisher_key, ledger::ResultCallback callback) override; + void ReconcileStampReset() override; }; diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm index 982349d475f1..3d7d3262f430 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm @@ -258,3 +258,18 @@ void NativeLedgerClient::DeleteUnblindedTokensForPromotion(const std::string& promotion_id, ledger::ResultCallback callback) { [bridge_ deleteUnblindedTokensForPromotion:promotion_id callback:callback]; } +void NativeLedgerClient::GetIncompleteContributions(ledger::GetIncompleteContributionsCallback callback) { + [bridge_ getIncompleteContributions:callback]; +} +void NativeLedgerClient::GetContributionInfo(const std::string& contribution_id, ledger::GetContributionInfoCallback callback) { + [bridge_ getContributionInfo:contribution_id callback:callback]; +} +void NativeLedgerClient::UpdateContributionInfoStepAndCount(const std::string& contribution_id, const ledger::ContributionStep step, const int32_t retry_count, ledger::ResultCallback callback) { + [bridge_ updateContributionInfoStepAndCount:contribution_id step:step retry_count:retry_count callback:callback]; +} +void NativeLedgerClient::UpdateContributionInfoContributedAmount(const std::string& contribution_id, const std::string& publisher_key, ledger::ResultCallback callback) { + [bridge_ updateContributionInfoContributedAmount:contribution_id publisher_key:publisher_key callback:callback]; +} +void NativeLedgerClient::ReconcileStampReset() { + [bridge_ reconcileStampReset]; +} diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h index 7e5a4de2256a..49935a192583 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h @@ -90,5 +90,10 @@ - (void)unblindedTokensReady; - (void)getAllPromotions:(ledger::GetAllPromotionsCallback)callback; - (void)deleteUnblindedTokensForPromotion:(const std::string&)promotion_id callback:(ledger::ResultCallback)callback; +- (void)getIncompleteContributions:(ledger::GetIncompleteContributionsCallback)callback; +- (void)getContributionInfo:(const std::string&)contribution_id callback:(ledger::GetContributionInfoCallback)callback; +- (void)updateContributionInfoStepAndCount:(const std::string&)contribution_id step:(const ledger::ContributionStep)step retry_count:(const int32_t)retry_count callback:(ledger::ResultCallback)callback; +- (void)updateContributionInfoContributedAmount:(const std::string&)contribution_id publisher_key:(const std::string&)publisher_key callback:(ledger::ResultCallback)callback; +- (void)reconcileStampReset; @end From 9f46417cb8432e55989299251d11a7a00c0c64da Mon Sep 17 00:00:00 2001 From: Brian Clifton Date: Tue, 28 Jan 2020 00:54:44 -0700 Subject: [PATCH 2/2] Resolve double/std::string conversion problem --- .../src/bat/ledger/internal/contribution/contribution.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 bf1ad1958fef..2f3415662aa5 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 @@ -470,11 +470,13 @@ void Contribution::ContributionCompleted( const double amount, const ledger::Result result) { if (result == ledger::Result::LEDGER_OK) { + const std::string probi = + braveledger_bat_util::ConvertToProbi(std::to_string(amount)); ledger_->SetBalanceReportItem( braveledger_time_util::GetCurrentMonth(), braveledger_time_util::GetCurrentYear(), GetReportTypeFromRewardsType(type), - amount); + probi); } ledger_->UpdateContributionInfoStepAndCount(