diff --git a/browser/brave_rewards/extension_rewards_service_observer.cc b/browser/brave_rewards/extension_rewards_service_observer.cc index 8619f39ef772..8ad46e4eb045 100644 --- a/browser/brave_rewards/extension_rewards_service_observer.cc +++ b/browser/brave_rewards/extension_rewards_service_observer.cc @@ -354,7 +354,7 @@ void ExtensionRewardsServiceObserver::OnPendingContributionRemoved( void ExtensionRewardsServiceObserver::OnReconcileComplete( RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) { auto* event_router = extensions::EventRouter::Get(profile_); diff --git a/browser/brave_rewards/extension_rewards_service_observer.h b/browser/brave_rewards/extension_rewards_service_observer.h index 4327d6c88559..8331c19dbbf3 100644 --- a/browser/brave_rewards/extension_rewards_service_observer.h +++ b/browser/brave_rewards/extension_rewards_service_observer.h @@ -53,7 +53,7 @@ class ExtensionRewardsServiceObserver : public RewardsServiceObserver, void OnReconcileComplete( RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) override; diff --git a/browser/ui/webui/brave_rewards_page_ui.cc b/browser/ui/webui/brave_rewards_page_ui.cc index 6d4c0c0c793a..a8c09f5515f6 100644 --- a/browser/ui/webui/brave_rewards_page_ui.cc +++ b/browser/ui/webui/brave_rewards_page_ui.cc @@ -222,7 +222,7 @@ class RewardsDOMHandler : public WebUIMessageHandler, void OnReconcileComplete( brave_rewards::RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) override; void OnPendingContributionSaved( @@ -974,7 +974,7 @@ void RewardsDOMHandler::GetContributionAmount(const base::ListValue* args) { void RewardsDOMHandler::OnReconcileComplete( brave_rewards::RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) { if (web_ui()->CanCallJavascript()) { diff --git a/browser/ui/webui/brave_tip_ui.cc b/browser/ui/webui/brave_tip_ui.cc index 8b63a776df30..925a136b8571 100644 --- a/browser/ui/webui/brave_tip_ui.cc +++ b/browser/ui/webui/brave_tip_ui.cc @@ -95,7 +95,7 @@ class RewardsTipDOMHandler : public WebUIMessageHandler, void OnReconcileComplete( brave_rewards::RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) override; @@ -499,7 +499,7 @@ void RewardsTipDOMHandler::OnlyAnonWallet(const base::ListValue* args) { void RewardsTipDOMHandler::OnReconcileComplete( brave_rewards::RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) { if (!web_ui()->CanCallJavascript()) { diff --git a/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc b/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc index 901d1271e9d1..b5795040af5a 100644 --- a/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc +++ b/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc @@ -309,19 +309,30 @@ bool ParseJSON(base::StringPiece json, ], "entries": [ // Brave - { "name": "ledger.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, - { "name": "ledger-staging.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, - { "name": "balance.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, - { "name": "balance-staging.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, { "name": "download.brave.com", "mode": "force-https", "policy": "custom", "pins": "brave"}, { "name": "laptop-updates.brave.com", "mode": "force-https", "policy": "custom", "pins": "brave"}, { "name": "sync.brave.com", "mode": "force-https", "policy": "custom", "pins": "brave"}, { "name": "sync-staging.brave.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, - { "name": "publishers-distro.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, - { "name": "publishers-staging-distro.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, { "name": "p3a.brave.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, { "name": "p3a.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, - { "name": "p3a-dev.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"} + { "name": "p3a-dev.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + + // Rewards + { "name": "ledger.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "ledger-staging.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "ledger.rewards.brave.software", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "balance.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "balance-staging.mercury.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "balance.rewards.brave.software", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "publishers-distro.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "publishers-staging-distro.basicattentiontoken.org", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "creators-distro.brave.software", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "grant.rewards.brave.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "grant.rewards.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "grant.rewards.brave.software", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "payment.rewards.brave.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "payment.rewards.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "payment.rewards.brave.software", "policy": "custom", "mode": "force-https", "pins": "brave"} ]})brave_json"; return ParseJSON_ChromiumImpl(brave_json, entries, pinsets); diff --git a/components/brave_rewards/browser/rewards_notification_service_impl.cc b/components/brave_rewards/browser/rewards_notification_service_impl.cc index 1dfa5dcf1bf6..7d0869293389 100644 --- a/components/brave_rewards/browser/rewards_notification_service_impl.cc +++ b/components/brave_rewards/browser/rewards_notification_service_impl.cc @@ -365,7 +365,7 @@ void RewardsNotificationServiceImpl::OnPromotionFinished( void RewardsNotificationServiceImpl::OnReconcileComplete( RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) { auto converted_result = static_cast(result); @@ -384,7 +384,7 @@ void RewardsNotificationServiceImpl::OnReconcileComplete( converted_result == ledger::Result::LEDGER_ERROR || converted_result == ledger::Result::TIP_ERROR) { RewardsNotificationService::RewardsNotificationArgs args; - args.push_back(viewing_id); + args.push_back(contribution_id); args.push_back(std::to_string(result)); args.push_back(std::to_string(type)); args.push_back(std::to_string(amount)); @@ -392,7 +392,7 @@ void RewardsNotificationServiceImpl::OnReconcileComplete( AddNotification( RewardsNotificationService::REWARDS_NOTIFICATION_AUTO_CONTRIBUTE, args, - "contribution_" + viewing_id); + "contribution_" + contribution_id); } } diff --git a/components/brave_rewards/browser/rewards_notification_service_impl.h b/components/brave_rewards/browser/rewards_notification_service_impl.h index f88ed5c89815..05e3bc41fcf5 100644 --- a/components/brave_rewards/browser/rewards_notification_service_impl.h +++ b/components/brave_rewards/browser/rewards_notification_service_impl.h @@ -64,7 +64,7 @@ class RewardsNotificationServiceImpl void OnReconcileComplete( RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) override; diff --git a/components/brave_rewards/browser/rewards_service_browsertest.cc b/components/brave_rewards/browser/rewards_service_browsertest.cc index e6122184f8b1..9f361ea52e92 100644 --- a/components/brave_rewards/browser/rewards_service_browsertest.cc +++ b/components/brave_rewards/browser/rewards_service_browsertest.cc @@ -17,6 +17,7 @@ #include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/uphold/uphold_util.h" #include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/request/request_sku.h" #include "bat/ledger/internal/static_values.h" #include "bat/ledger/ledger.h" #include "brave/browser/extensions/api/brave_action_api.h" @@ -136,21 +137,14 @@ namespace brave_test_resp { std::string verification_; std::string promotions_; std::string promotion_claim_; - std::string promotion_tokens_; + std::string creds_tokens_; + std::string creds_tokens_prod_; std::string captcha_; std::string wallet_properties_; std::string wallet_properties_defaults_; std::string uphold_auth_resp_; std::string uphold_transactions_resp_; std::string uphold_commit_resp_; - - std::string contribution_; - std::string reconcile_; - std::string current_reconcile_; - std::string register_; - std::string register_credential_; - std::string surveyor_voting_; - std::string surveyor_voting_credential_; } // namespace brave_test_resp class BraveRewardsBrowserTest @@ -271,6 +265,45 @@ class BraveRewardsBrowserTest status.c_str()); } + std::string GetOrderCreateResponse() { + DCHECK(sku_order_); + std::string items; + for (const auto& item : sku_order_->items) { + items.append(base::StringPrintf( + R"({ + "id": "%s", + "orderId": "%s", + "sku": "", + "createdAt": "2020-04-08T08:22:26.288974Z", + "updatedAt": "2020-04-08T08:22:26.288974Z", + "currency": "BAT", + "quantity": %d, + "price": "%g", + "description": "%s" + })", + item->order_item_id.c_str(), + sku_order_->order_id.c_str(), + item->quantity, + item->price, + item->description.c_str())); + } + + return base::StringPrintf( + R"({ + "id": "%s", + "createdAt": "2020-04-08T08:22:26.288974Z", + "currency": "BAT", + "updatedAt": "2020-04-08T08:22:26.288974Z", + "totalPrice": "%g", + "location": "brave.com", + "status": "pending", + "items": [%s] + })", + sku_order_->order_id.c_str(), + sku_order_->total_amount, + items.c_str()); + } + std::vector GetSiteBannerTipOptions( content::WebContents* site_banner) { rewards_service_browsertest_utils::WaitForElementToAppear( @@ -351,7 +384,7 @@ class BraveRewardsBrowserTest } else if (URLMatches(url, "/promotions/", PREFIX_V1, ServerTypes::kPromotion)) { if (url.find("claims") != std::string::npos) { - *response = brave_test_resp::promotion_tokens_; + *response = brave_test_resp::creds_tokens_; } else { *response = brave_test_resp::promotion_claim_; } @@ -409,30 +442,27 @@ class BraveRewardsBrowserTest braveledger_uphold::GetAPIUrl("/v0/me"), base::CompareCase::INSENSITIVE_ASCII)) { *response = GetUpholdUser(); - } else if (URLMatches(url, WALLET_PROPERTIES, PREFIX_V2, - ServerTypes::LEDGER)) { - GURL gurl(url); - if (gurl.has_query()) { - *response = brave_test_resp::reconcile_; - } else { - *response = brave_test_resp::current_reconcile_; + } else if (URLMatches( + url, + "/order", + PREFIX_V1, + ServerTypes::kPayments)) { + if (url.find("credentials") != std::string::npos) { + if (method == 0) { + #if defined(OFFICIAL_BUILD) + *response = brave_test_resp::creds_tokens_prod_; + #else + *response = brave_test_resp::creds_tokens_; + #endif + + return; + } + return; + } else if (url.find("transaction") == std::string::npos) { + *response = GetOrderCreateResponse(); } - } else if (URLMatches(url, RECONCILE_CONTRIBUTION, PREFIX_V2, - ServerTypes::LEDGER)) { - *response = brave_test_resp::contribution_; - } else if (URLMatches(url, REGISTER_VIEWING, PREFIX_V2, - ServerTypes::LEDGER)) { - if (url.find(REGISTER_VIEWING "/") != std::string::npos) - *response = brave_test_resp::register_credential_; - else - *response = brave_test_resp::register_; - } else if (URLMatches(url, SURVEYOR_BATCH_VOTING, PREFIX_V2, - ServerTypes::LEDGER)) { - if (url.find(SURVEYOR_BATCH_VOTING "/") != std::string::npos) - *response = brave_test_resp::surveyor_voting_credential_; - else - *response = brave_test_resp::surveyor_voting_; + *response_status_code = net::HTTP_CREATED; } } @@ -650,8 +680,11 @@ class BraveRewardsBrowserTest base::ReadFileToString(path.AppendASCII("promotion_claim_resp.json"), &brave_test_resp::promotion_claim_)); ASSERT_TRUE( - base::ReadFileToString(path.AppendASCII("promotion_tokens_resp.json"), - &brave_test_resp::promotion_tokens_)); + base::ReadFileToString(path.AppendASCII("creds_tokens_resp.json"), + &brave_test_resp::creds_tokens_)); + ASSERT_TRUE( + base::ReadFileToString(path.AppendASCII("creds_tokens_prod_resp.json"), + &brave_test_resp::creds_tokens_prod_)); ASSERT_TRUE( base::ReadFileToString(path.AppendASCII("wallet_properties_resp.json"), &brave_test_resp::wallet_properties_)); @@ -667,26 +700,6 @@ class BraveRewardsBrowserTest ASSERT_TRUE(base::ReadFileToString( path.AppendASCII("uphold_commit_resp.json"), &brave_test_resp::uphold_commit_resp_)); - - ASSERT_TRUE( - base::ReadFileToString(path.AppendASCII("contribution_resp.json"), - &brave_test_resp::contribution_)); - ASSERT_TRUE(base::ReadFileToString(path.AppendASCII("reconcile_resp.json"), - &brave_test_resp::reconcile_)); - ASSERT_TRUE( - base::ReadFileToString(path.AppendASCII("current_reconcile_resp.json"), - &brave_test_resp::current_reconcile_)); - ASSERT_TRUE(base::ReadFileToString(path.AppendASCII("register_resp.json"), - &brave_test_resp::register_)); - ASSERT_TRUE(base::ReadFileToString( - path.AppendASCII("register_credential_resp.json"), - &brave_test_resp::register_credential_)); - ASSERT_TRUE( - base::ReadFileToString(path.AppendASCII("surveyor_voting_resp.json"), - &brave_test_resp::surveyor_voting_)); - ASSERT_TRUE(base::ReadFileToString( - path.AppendASCII("surveyor_voting_credential_resp.json"), - &brave_test_resp::surveyor_voting_credential_)); } void UpdateContributionBalance(double amount, bool verified = false) { @@ -1174,7 +1187,7 @@ class BraveRewardsBrowserTest void OnReconcileComplete( brave_rewards::RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) { const auto converted_result = static_cast(result); @@ -1408,6 +1421,8 @@ class BraveRewardsBrowserTest std::unique_ptr wait_for_attestation_loop_; + ledger::SKUOrderPtr sku_order_ = nullptr; + bool last_publisher_added_ = false; bool alter_publisher_list_ = false; bool show_defaults_in_properties_ = false; @@ -2716,6 +2731,24 @@ IN_PROC_BROWSER_TEST_F( // 30 form unblinded and 20 from uphold rewards_service()->SetContributionAmount(50.0); + ledger::SKUOrderItemList items; + auto item = ledger::SKUOrderItem::New(); + item->order_item_id = "ed193339-e58c-483c-8d61-7decd3c24827"; + item->order_id = "a38b211b-bf78-42c8-9479-b11e92e3a76c"; + item->quantity = 80; + item->price = 0.25; + item->description = "description"; + item->type = ledger::SKUOrderItemType::SINGLE_USE; + items.push_back(std::move(item)); + + auto order = ledger::SKUOrder::New(); + order->order_id = "a38b211b-bf78-42c8-9479-b11e92e3a76c"; + order->total_amount = 20; + order->merchant_id = ""; + order->location = "brave.com"; + order->items = std::move(items); + sku_order_ = std::move(order); + // Trigger contribution process rewards_service()->StartMonthlyContributionForTest(); diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index 86f64c50a2bb..98a5912802ef 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -851,15 +851,8 @@ void RewardsServiceImpl::OnGetRewardsInternalsInfo( rewards_internals_info->user_id = info->user_id; rewards_internals_info->boot_stamp = info->boot_stamp; - for (const auto& item : info->current_reconciles) { - ReconcileInfo reconcile_info; - reconcile_info.viewing_id_ = item.second->viewing_id; - reconcile_info.amount_ = item.second->amount; - reconcile_info.retry_step_ = - static_cast(item.second->retry_step); - reconcile_info.retry_level_ = item.second->retry_level; - rewards_internals_info->current_reconciles[item.first] = reconcile_info; - } + // TODO(https://github.com/brave/brave-browser/issues/8633) + // add active contributions std::move(callback).Run(std::move(rewards_internals_info)); } @@ -886,7 +879,7 @@ void RewardsServiceImpl::OnRecoverWallet( void RewardsServiceImpl::OnReconcileComplete( const ledger::Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type) { if (result == ledger::Result::LEDGER_OK && @@ -897,7 +890,7 @@ void RewardsServiceImpl::OnReconcileComplete( for (auto& observer : observers_) observer.OnReconcileComplete(this, static_cast(result), - viewing_id, + contribution_id, amount, static_cast(type)); } @@ -2871,6 +2864,8 @@ void RewardsServiceImpl::GetExternalWallets( for (const auto& it : dict->DictItems()) { ledger::ExternalWalletPtr wallet = ledger::ExternalWallet::New(); + wallet->type = it.first; + auto* token = it.second.FindKey("token"); if (token && token->is_string()) { wallet->token = token->GetString(); diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index 4855f2150d6f..35bcb9c92242 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -463,7 +463,7 @@ class RewardsServiceImpl : public RewardsService, double balance); void OnReconcileComplete( const ledger::Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type) override; void OnAttestPromotion( diff --git a/components/brave_rewards/browser/rewards_service_observer.h b/components/brave_rewards/browser/rewards_service_observer.h index 6f3cae18cd80..c790e63bb0c0 100644 --- a/components/brave_rewards/browser/rewards_service_observer.h +++ b/components/brave_rewards/browser/rewards_service_observer.h @@ -53,7 +53,7 @@ class RewardsServiceObserver : public base::CheckedObserver { virtual void OnReconcileComplete( RewardsService* rewards_service, unsigned int result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const int32_t type) {} virtual void OnAdsEnabled( 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 c0f0fe27710b..b0b62792dc2b 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc @@ -116,7 +116,7 @@ void BatLedgerClientMojoProxy::OnWalletProperties( void BatLedgerClientMojoProxy::OnReconcileComplete( ledger::Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type) { if (!Connected()) @@ -124,7 +124,7 @@ void BatLedgerClientMojoProxy::OnReconcileComplete( bat_ledger_client_->OnReconcileComplete( result, - viewing_id, + contribution_id, amount, type); } 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 d27e3275787f..91233a864531 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h @@ -31,7 +31,7 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, ledger::Result result, ledger::WalletPropertiesPtr properties) override; void OnReconcileComplete(ledger::Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type) override; void LoadLedgerState(ledger::OnLoadCallback callback) override; 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 0e6768df7195..bd828d81cea8 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 @@ -119,12 +119,12 @@ void LedgerClientMojoProxy::SavePublisherState( void LedgerClientMojoProxy::OnReconcileComplete( const ledger::Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type) { ledger_client_->OnReconcileComplete( result, - viewing_id, + contribution_id, amount, type); } 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 eb81dab006fd..ecfec3668c1e 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 @@ -31,7 +31,7 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, ledger::WalletPropertiesPtr properties) override; void OnReconcileComplete( const ledger::Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type) override; diff --git a/test/BUILD.gn b/test/BUILD.gn index df55b522daf3..b34e2656af64 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -328,10 +328,8 @@ test("brave_unit_tests") { if (brave_rewards_enabled) { sources += [ "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_activity_info_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/media/helper_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/media/reddit_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/media/github_unittest.cc", @@ -345,19 +343,9 @@ test("brave_unit_tests") { "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/bat_util_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc", - "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state_unittest.cc", diff --git a/test/data/rewards-data/contribution_resp.json b/test/data/rewards-data/contribution_resp.json deleted file mode 100644 index bb90592f0817..000000000000 --- a/test/data/rewards-data/contribution_resp.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "signature":"28a00fb8a4b663b9a6e38e8e712a3df, iay57CDbWSG9Y2z39QVgx0nSSexW4OAWwjQdBuq+EN 4BaXMtejRWXjKZ17aAfWLkj08t8ClSQCXFUo0QPkQvL 1 CdbDycAPfzVRsfT3p3jH8pdyFjuW1cySuu68jcovI0n 3p+RP29bqtPgACqJn98xWhUepfoV1ZQ2o4LfTOyHY9H\n", - "payload":{ - "adFree":{ - "fee":{ - "USD":5 - }, - "votes":100, - "altcurrency":"BAT", - "probi":"25000000000000000000" - } - }, - "surveyorId":"FuznYc8NaAXt+At2S+DdaM/rsEyHWd3vFpLpbCLm/z7", - "surveyVK":"==========ANONLOGIN_VK_BEG==========\n6SWJBmkQXkPm1/0Sge4ezHWVXRCtdbGFwcb5XZnjEH2 O4cvn69IzJiH5znUsFK45e4KNoccd4vHmtaozGQgEj 1\n2MHE1Qepdw64bc69nN58JDslzeI36AHr5VfRQfmB/VC 6xtkMq6YI56oVETjouerencG2CJ4pP1Y0PPEPWAyi84 1\n6belVbSubm7yHJFFD5JIz8BwCUBGzHawZH/ILqiSZGh 6r6Rpi8hGcQWa+regtXCtzx5uJI+BG3dzln6/DuKVGe 1\n9XqLkmga7sBZRBeESqNIs2HlUr71C7VQ13mG1Ias2W mg+JzzbVuJKLYABVE975tWtKT0o7dxJOBk16zUdNhc 1\n8yNeactDzb+RTNHNIrQSsvT00wEDP0cRdMkrD0vQW5A 4tga6SJf+aU3ewRmEa2+azykll3d77VTsfvTCVFbNWb y3h8BC+KIIU54hv02sISKzRpSMN3kam1sFfY6Dp2Xq 31AENnYtE0dGLqMhr0t+pDKx/dPJ1rO4hncDfqfaj2Z 1 0\n===========ANONLOGIN_VK_END==========", - "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==========" -} \ No newline at end of file diff --git a/test/data/rewards-data/promotion_tokens_resp.json b/test/data/rewards-data/creds_tokens_prod_resp.json similarity index 99% rename from test/data/rewards-data/promotion_tokens_resp.json rename to test/data/rewards-data/creds_tokens_prod_resp.json index 29aa4719be0f..5d74246b6cd3 100644 --- a/test/data/rewards-data/promotion_tokens_resp.json +++ b/test/data/rewards-data/creds_tokens_prod_resp.json @@ -122,5 +122,5 @@ "etDK97tchgvLzSFmzcGhGT34KaVa6DVUU2iNB9Urxgk=" ], "batchProof": "Z6+3SJ3DtDskOZ6pXdzmIiHB28qdTXsdyYorvv3fdwJc0JAmdvQ24HOqHp1JQ0+VUhT99zc0KgX2oaR52OJiDA==", - "publicKey": "JkaJRxlQqccX6ss53Uc/liHoTH14KWn4CNsPShJRERM=" + "publicKey": "yr4w9Y0XZQISBOToATNEl5ADspDUgm7cBSOhfYgPWx4=" } \ No newline at end of file diff --git a/test/data/rewards-data/creds_tokens_resp.json b/test/data/rewards-data/creds_tokens_resp.json new file mode 100644 index 000000000000..ea8a90548ac3 --- /dev/null +++ b/test/data/rewards-data/creds_tokens_resp.json @@ -0,0 +1,126 @@ +{ + "signedCreds": [ + "Fo0lNiiLJZvehAe0Nucrrhr9/qgBaJt0QQTN0GZx9FQ=", + "ip8ds6Pg6wlG8dVk6eSb1uFBV7nh13vUyFbQPiht0C4=", + "NkeBxhN1lZk7n/5wh9/DN5E7jeLB9gfn7nWUxJ9rLQE=", + "sE0SZYd4qNzgGPTGnJrw1ZxrTY+GPrYtiO+76ceyAS0=", + "kq9dk8p0niCfuka7O1C3Rq0JtZuBoX0aI4V808g7kBA=", + "SrEAjDWUAMo8Y4H/hfc8PDyAZYbSAgzetciKxGvlNzs=", + "oD8PlMXI4PKDOUY9BnEOirKAqR9ctaNRPPZMYl7jemU=", + "7DaTre9eKjurqVF2FYLz/R1xBDB8fItlYGB8kjweSRs=", + "pDqBpYvA93d3hYyTq8MkUglSo4bwnuG1o/2ArYJ7hhU=", + "Yp0fiwu5tOY8TkCLbARuV+1ihx2UNsLZzWuahLAguVY=", + "wrNNe2mjv4Zs09qoyBusIrqGoPKWzAnvLo8dtMHDuBE=", + "7JvEhi8L4QZuFufk6EvOM1HWnDXVxxYYlaq9mmqTZCg=", + "VL/zyImLugLeF1eAImWmPF+ljsyzXT61c+o9QbEPxjE=", + "shn3lvJAmKwu2cZxOTkw4L9gQGbWH7hOc7ZZ7iimJQw=", + "0EEaSFtPGsdlY+HDjy/SHo6Kf/Bp+V9wnpt1sAMyRUE=", + "UsSOBPiKJIKzz0tMoaR3kFW8wSubgcp+hkSuLcPP31A=", + "+JO5gMIYpP0OfB1IBByEZeM6XXRCRXXriJVOZZRsXk0=", + "upE0n2vEXZtnozYD6/2YZlfy/RQBES+3Oa8T9s79vXo=", + "/h1e5mBYrAXj63rb8nhPCZRLOyedNozlBKYPjcsZUHg=", + "/miQ7ewkoIArdMtUqXO+MEwJnPhf1bYjTwTWyDUHFAU=", + "4tcBnAHQrKzR0tvg6E+IfFekfFZOKKDv+e43S2m+k1w=", + "qsRP0Z7mxkZXXjgTNEtwA76myraE/8ErfR6sd8S8/AI=", + "dL9QSFWoiw27y84mEURNe/54O4Lcp/lKkbidAkO+xUU=", + "GjsgRbFhVNaCrgAHrpUsh+NGRQbJsvA89krWPtbraw0=", + "TmsSl1/zn+tKf39WY5KEatWWxnhZ0S7cGRgGBRxtqxw=", + "RPOHgRxUdf1X+lkAxCkFp0aXr70GUPWaNkc6ojk11y0=", + "DvdwEkodKpsFOk1qLMQVkhyrG7TDvIwH+mYTt1LyB1s=", + "BB3WSaFe30xPSMLt2bRGvIk3qD24N3eDbMUfJk7TxzY=", + "mGa4X18fXYEClTd0+SZAyhza8qZ6H8aHzmLi3pDhNkI=", + "vGKSvhnEWOBh9o5ZcxXAPHXIq9RERowI48uUOie4oW4=", + "NNX6FaWipF7/QWJuwfa89Z2mxTz0HGXwMIW1fJjMW2Y=", + "xN4REvse67v+3/z2comPXJvR5NTU/yTltDcah1hgIEI=", + "aJrkjU8GDASMyitbZn0X8f995AIy/AZPwN+heg12kF8=", + "/KQpDjyOfi4unbzmevZ/zmsr8XLkGJMjAm1w1lJ5HQ0=", + "6JniWAa2EhZHl824vkhMMiNFLIR97yZcBp374mpJRD0=", + "jow6OBDiYult6v7xNRtZIalwsFrkGdxB9Tr+7dmc+S4=", + "SP1BW8CKGZnUdDWsfbOY/aLJPdjEyAfsqWNxyguifRg=", + "YiwIJ8sCxxnC+4KxcZWnDp8uZr/1MbYX6KxQ2j1OljE=", + "EgAoqpPstDgJcYTaiJzeGB03Psd5ptZ4SyaWl8uc1E8=", + "3ko9Zr3CThxLbkbP1BroaSE+ffxs7VCFm40qq4M7L3I=", + "DOm6dkf7vATf+7IAJkUEaK8ZfmFFwZ3V4yRWvFGvrBQ=", + "loS9EkzqwwJ1++nUkcSZhetuz7TKzQvtz/g1pdx7HX8=", + "9gD/iWPFJ8p4Dho9lVFXgPqd1EYulgK5VjXvz+RBqi0=", + "8FdnB+qklQZx+715mhMK2aEr7y5QzKvlRHwmWv7Wrw0=", + "GjV+srUWdi19ru34/oMrIWNdpYK1Bz6zqFKBhKCiMwY=", + "1rxWJjfzJttV4GoEuTJBMGVK5fkQM0r/Gh5uPmagMR0=", + "WMGoS7vftRF65KPhByPeXaeWE3c7V3BQajl0DlD63Wc=", + "sIqey9z6yP2Zysp8jPzuABYo9cXEYB05m4WkwppzZkc=", + "usjICudNQU9OUDM47IcEmgW753Kyaa7yEo9z30FsaFM=", + "etDK97tchgvLzSFmzcGhGT34KaVa6DVUU2iNB9Urxgk=", + "WHEkYm2TWZNMw9JJBqhjZA4XEoyfMC0+PwbIIEkVDWA=", + "apudufgT9BH4FBscLbBlCis7ZxJatVnYx7FBaIFZkgI=", + "qPCAKh+/UBfQIrPpjzd5JY9pY8WHHdaiuW8UAHDCnRY=", + "gHpyNe4wMiHjGXtO3iweM4LJE6VZXORxqJXLkL8dVn0=", + "+FiSWS2ziu/jQ9RBA2jjsUQsAbyC3Z0tMwv5pFb+GWk=", + "QBkt7L/PJ+FU0d7cRuJDYErrYdga2L1acuflsmBFu2c=", + "NE7WsQD3xLIIa6Gajg8jASTXQmwMCaHjkwV0uY+6l1M=", + "ElFQOPytNPhqjCK2Nj3MmrkDBZk/f49psDzFIeK12Fc=", + "rCWgydzNURQiOuLTYWHJ07XXcvbyMjopULT3N/MAeXo=", + "1NzGCBGcYcG7A7+9eXkOL+QxSjVCSEgJ+t6RXw35fkM=", + "1jv/61WgljwI6GGjuHR7hl9mxIyUL/ioPF/Tswm9Rx8=", + "tqzuISO+YnrMQ5JdwSJZsLmCrX1snpNVPx0RFDfHWgw=", + "rGktvfaEUFZQpEAOpzCihblkNTh4SiyNN9atHKriN3Q=", + "2LPZ5hVuyric9uFHTiU8D+3ejHeIoSbHdBdhBqF96Rg=", + "vtgi6GgGD+czcRcyMDdPeZLRdkDstIq+ElfpK5mvNQk=", + "4JNlmdJQ+ezLlNp0t6bpv4mqD9wttXjOjvjak80WYnE=", + "AktTILzogHjYVOCa2GW+6fjOJQPQxCnsP9qIfiy+dmk=", + "GsK55frSU7TQT0pKJFxyCSu0EaMi47q2zn+LFQC8vk0=", + "9jjAy07Hhm9lOzi+uuCitmH3WsXdAgdGbPlPPFibbEQ=", + "EPccEqmtJS0BD2Z5aOehAXsvG5XhmU2lU1H++QZe5AE=", + "Fo0lNiiLJZvehAe0Nucrrhr9/qgBaJt0QQTN0GZx9FQ=", + "ip8ds6Pg6wlG8dVk6eSb1uFBV7nh13vUyFbQPiht0C4=", + "NkeBxhN1lZk7n/5wh9/DN5E7jeLB9gfn7nWUxJ9rLQE=", + "sE0SZYd4qNzgGPTGnJrw1ZxrTY+GPrYtiO+76ceyAS0=", + "kq9dk8p0niCfuka7O1C3Rq0JtZuBoX0aI4V808g7kBA=", + "SrEAjDWUAMo8Y4H/hfc8PDyAZYbSAgzetciKxGvlNzs=", + "oD8PlMXI4PKDOUY9BnEOirKAqR9ctaNRPPZMYl7jemU=", + "7DaTre9eKjurqVF2FYLz/R1xBDB8fItlYGB8kjweSRs=", + "pDqBpYvA93d3hYyTq8MkUglSo4bwnuG1o/2ArYJ7hhU=", + "Yp0fiwu5tOY8TkCLbARuV+1ihx2UNsLZzWuahLAguVY=", + "wrNNe2mjv4Zs09qoyBusIrqGoPKWzAnvLo8dtMHDuBE=", + "7JvEhi8L4QZuFufk6EvOM1HWnDXVxxYYlaq9mmqTZCg=", + "VL/zyImLugLeF1eAImWmPF+ljsyzXT61c+o9QbEPxjE=", + "shn3lvJAmKwu2cZxOTkw4L9gQGbWH7hOc7ZZ7iimJQw=", + "0EEaSFtPGsdlY+HDjy/SHo6Kf/Bp+V9wnpt1sAMyRUE=", + "UsSOBPiKJIKzz0tMoaR3kFW8wSubgcp+hkSuLcPP31A=", + "+JO5gMIYpP0OfB1IBByEZeM6XXRCRXXriJVOZZRsXk0=", + "upE0n2vEXZtnozYD6/2YZlfy/RQBES+3Oa8T9s79vXo=", + "/h1e5mBYrAXj63rb8nhPCZRLOyedNozlBKYPjcsZUHg=", + "/miQ7ewkoIArdMtUqXO+MEwJnPhf1bYjTwTWyDUHFAU=", + "4tcBnAHQrKzR0tvg6E+IfFekfFZOKKDv+e43S2m+k1w=", + "qsRP0Z7mxkZXXjgTNEtwA76myraE/8ErfR6sd8S8/AI=", + "dL9QSFWoiw27y84mEURNe/54O4Lcp/lKkbidAkO+xUU=", + "GjsgRbFhVNaCrgAHrpUsh+NGRQbJsvA89krWPtbraw0=", + "TmsSl1/zn+tKf39WY5KEatWWxnhZ0S7cGRgGBRxtqxw=", + "RPOHgRxUdf1X+lkAxCkFp0aXr70GUPWaNkc6ojk11y0=", + "DvdwEkodKpsFOk1qLMQVkhyrG7TDvIwH+mYTt1LyB1s=", + "BB3WSaFe30xPSMLt2bRGvIk3qD24N3eDbMUfJk7TxzY=", + "mGa4X18fXYEClTd0+SZAyhza8qZ6H8aHzmLi3pDhNkI=", + "vGKSvhnEWOBh9o5ZcxXAPHXIq9RERowI48uUOie4oW4=", + "NNX6FaWipF7/QWJuwfa89Z2mxTz0HGXwMIW1fJjMW2Y=", + "xN4REvse67v+3/z2comPXJvR5NTU/yTltDcah1hgIEI=", + "aJrkjU8GDASMyitbZn0X8f995AIy/AZPwN+heg12kF8=", + "/KQpDjyOfi4unbzmevZ/zmsr8XLkGJMjAm1w1lJ5HQ0=", + "6JniWAa2EhZHl824vkhMMiNFLIR97yZcBp374mpJRD0=", + "jow6OBDiYult6v7xNRtZIalwsFrkGdxB9Tr+7dmc+S4=", + "SP1BW8CKGZnUdDWsfbOY/aLJPdjEyAfsqWNxyguifRg=", + "YiwIJ8sCxxnC+4KxcZWnDp8uZr/1MbYX6KxQ2j1OljE=", + "EgAoqpPstDgJcYTaiJzeGB03Psd5ptZ4SyaWl8uc1E8=", + "3ko9Zr3CThxLbkbP1BroaSE+ffxs7VCFm40qq4M7L3I=", + "DOm6dkf7vATf+7IAJkUEaK8ZfmFFwZ3V4yRWvFGvrBQ=", + "loS9EkzqwwJ1++nUkcSZhetuz7TKzQvtz/g1pdx7HX8=", + "9gD/iWPFJ8p4Dho9lVFXgPqd1EYulgK5VjXvz+RBqi0=", + "8FdnB+qklQZx+715mhMK2aEr7y5QzKvlRHwmWv7Wrw0=", + "GjV+srUWdi19ru34/oMrIWNdpYK1Bz6zqFKBhKCiMwY=", + "1rxWJjfzJttV4GoEuTJBMGVK5fkQM0r/Gh5uPmagMR0=", + "WMGoS7vftRF65KPhByPeXaeWE3c7V3BQajl0DlD63Wc=", + "sIqey9z6yP2Zysp8jPzuABYo9cXEYB05m4WkwppzZkc=", + "usjICudNQU9OUDM47IcEmgW753Kyaa7yEo9z30FsaFM=", + "etDK97tchgvLzSFmzcGhGT34KaVa6DVUU2iNB9Urxgk=" + ], + "batchProof": "Z6+3SJ3DtDskOZ6pXdzmIiHB28qdTXsdyYorvv3fdwJc0JAmdvQ24HOqHp1JQ0+VUhT99zc0KgX2oaR52OJiDA==", + "publicKey": "mMMWZrWPlO5b9IB8vF5kUJW4f7ULH1wuEop3NOYqNW0=" +} \ No newline at end of file diff --git a/test/data/rewards-data/current_reconcile_resp.json b/test/data/rewards-data/current_reconcile_resp.json deleted file mode 100644 index 9488ff023e7f..000000000000 --- a/test/data/rewards-data/current_reconcile_resp.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "paymentStamp":1551325017004, - "probi":"1000000000000000000", - "altcurrency":"BAT" -} \ No newline at end of file diff --git a/test/data/rewards-data/migration/publisher_info_db_v18 b/test/data/rewards-data/migration/publisher_info_db_v18 new file mode 100644 index 000000000000..788af43c3218 Binary files /dev/null and b/test/data/rewards-data/migration/publisher_info_db_v18 differ diff --git a/test/data/rewards-data/migration/publisher_info_schema_current.txt b/test/data/rewards-data/migration/publisher_info_schema_current.txt index 0c0e4cd804b9..c8f293acb257 100644 --- a/test/data/rewards-data/migration/publisher_info_schema_current.txt +++ b/test/data/rewards-data/migration/publisher_info_schema_current.txt @@ -14,6 +14,9 @@ index|server_publisher_amounts_publisher_key_index|server_publisher_amounts|CREA index|server_publisher_banner_publisher_key_index|server_publisher_banner|CREATE INDEX server_publisher_banner_publisher_key_index ON server_publisher_banner (publisher_key) index|server_publisher_info_publisher_key_index|server_publisher_info|CREATE INDEX server_publisher_info_publisher_key_index ON server_publisher_info (publisher_key) index|server_publisher_links_publisher_key_index|server_publisher_links|CREATE INDEX server_publisher_links_publisher_key_index ON server_publisher_links (publisher_key) +index|sku_order_items_order_id_index|sku_order_items|CREATE INDEX sku_order_items_order_id_index ON sku_order_items (order_id) +index|sku_order_items_order_item_id_index|sku_order_items|CREATE INDEX sku_order_items_order_item_id_index ON sku_order_items (order_item_id) +index|sku_transaction_order_id_index|sku_transaction|CREATE INDEX sku_transaction_order_id_index ON sku_transaction (order_id) index|sqlite_autoindex_activity_info_1|activity_info| index|sqlite_autoindex_contribution_info_1|contribution_info| index|sqlite_autoindex_creds_batch_1|creds_batch| @@ -27,6 +30,9 @@ index|sqlite_autoindex_server_publisher_amounts_1|server_publisher_amounts| index|sqlite_autoindex_server_publisher_banner_1|server_publisher_banner| index|sqlite_autoindex_server_publisher_info_1|server_publisher_info| index|sqlite_autoindex_server_publisher_links_1|server_publisher_links| +index|sqlite_autoindex_sku_order_1|sku_order| +index|sqlite_autoindex_sku_order_items_1|sku_order_items| +index|sqlite_autoindex_sku_transaction_1|sku_transaction| index|unblinded_tokens_creds_id_index|unblinded_tokens|CREATE INDEX unblinded_tokens_creds_id_index ON unblinded_tokens (creds_id) table|activity_info|activity_info|CREATE TABLE activity_info (publisher_id LONGVARCHAR NOT NULL,duration INTEGER DEFAULT 0 NOT NULL,visits INTEGER DEFAULT 0 NOT NULL,score DOUBLE DEFAULT 0 NOT NULL,percent INTEGER DEFAULT 0 NOT NULL,weight DOUBLE DEFAULT 0 NOT NULL,reconcile_stamp INTEGER DEFAULT 0 NOT NULL,CONSTRAINT activity_unique UNIQUE (publisher_id, reconcile_stamp)) table|contribution_info|contribution_info|CREATE TABLE contribution_info (contribution_id TEXT NOT NULL,amount DOUBLE NOT NULL,type INTEGER NOT NULL,step INTEGER NOT NULL DEFAULT -1,retry_count INTEGER NOT NULL DEFAULT -1,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, processor INTEGER NOT NULL DEFAULT 1,PRIMARY KEY (contribution_id)) @@ -44,5 +50,8 @@ table|server_publisher_amounts|server_publisher_amounts|CREATE TABLE server_publ table|server_publisher_banner|server_publisher_banner|CREATE TABLE server_publisher_banner (publisher_key LONGVARCHAR PRIMARY KEY NOT NULL UNIQUE,title TEXT,description TEXT,background TEXT,logo TEXT) table|server_publisher_info|server_publisher_info|CREATE TABLE server_publisher_info (publisher_key LONGVARCHAR PRIMARY KEY NOT NULL UNIQUE,status INTEGER DEFAULT 0 NOT NULL,excluded INTEGER DEFAULT 0 NOT NULL,address TEXT NOT NULL) table|server_publisher_links|server_publisher_links|CREATE TABLE server_publisher_links (publisher_key LONGVARCHAR NOT NULL,provider TEXT,link TEXT,CONSTRAINT server_publisher_links_unique UNIQUE (publisher_key, provider)) +table|sku_order|sku_order|CREATE TABLE sku_order (order_id TEXT NOT NULL,total_amount DOUBLE,merchant_id TEXT,location TEXT,status INTEGER NOT NULL DEFAULT 0,contribution_id TEXT,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY (order_id)) +table|sku_order_items|sku_order_items|CREATE TABLE sku_order_items (order_item_id TEXT NOT NULL,order_id TEXT NOT NULL,sku TEXT,quantity INTEGER,price DOUBLE,name TEXT,description TEXT,type INTEGER,expires_at TIMESTAMP,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,CONSTRAINT sku_order_items_unique UNIQUE (order_item_id, order_id)) +table|sku_transaction|sku_transaction|CREATE TABLE sku_transaction (transaction_id TEXT NOT NULL,order_id TEXT NOT NULL,external_transaction_id TEXT NOT NULL,type INTEGER NOT NULL,amount DOUBLE NOT NULL,status INTEGER NOT NULL,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY (transaction_id)) table|sqlite_sequence|sqlite_sequence|CREATE TABLE sqlite_sequence(name,seq) table|unblinded_tokens|unblinded_tokens|CREATE TABLE unblinded_tokens (token_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,token_value TEXT,public_key TEXT,value DOUBLE NOT NULL DEFAULT 0,creds_id TEXT,expires_at TIMESTAMP NOT NULL DEFAULT 0,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP) diff --git a/test/data/rewards-data/promotions_resp.json b/test/data/rewards-data/promotions_resp.json index ab9b9f964dce..67d65d675653 100644 --- a/test/data/rewards-data/promotions_resp.json +++ b/test/data/rewards-data/promotions_resp.json @@ -11,7 +11,7 @@ "available": true, "platform": "", "publicKeys": [ - "JkaJRxlQqccX6ss53Uc/liHoTH14KWn4CNsPShJRERM=" + "mMMWZrWPlO5b9IB8vF5kUJW4f7ULH1wuEop3NOYqNW0=" ] } ] diff --git a/test/data/rewards-data/reconcile_resp.json b/test/data/rewards-data/reconcile_resp.json deleted file mode 100644 index 3e4032985602..000000000000 --- a/test/data/rewards-data/reconcile_resp.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "altcurrency":"BAT", - "paymentStamp":0, - "httpSigningPubKey":"ecb1132244475e1a5c5f08648ce594fcad0fda4a1a715af2dab8b853256caef4", - "rates":{ - "BTC":0.000042699069007737, - "ETH":0.001201763025187042, - "XRP":0.5246050162355701, - "BCH":0.001243508186632462, - "LTC":0.003590124034065517, - "DASH":0.002026628168709195, - "BTG":0.012951215171998555, - "USD":0.16313341782581928, - "EUR":0.1433725775243243 - }, - "addresses":{ - "BAT":"0xD72237CC12D3a8209EdaF99713eae677eA26E358", - "BTC":"n2ri2eAqccRaS3BpRnVfJjdoM7Sq152nyM", - "CARD_ID":"cdd39592-0964-4048-9c50-4ff76e55d71d", - "ETH":"0xD72237CC12D3a8209EdaF99713eae677eA26E358", - "LTC":"mxhHDYMxbMFkZfgU6Jv1LHbg2XrruiQd5g" - }, - "parameters":{ - "adFree":{ - "currency":"BAT", - "fee":{ - "BAT":20 - }, - "choices":{ - "BAT":[ - 10, - 15, - 20, - 30, - 50, - 100 - ] - }, - "range":{ - "BAT":[ - 10, - 100 - ] - }, - "days":30, - "nanos":1 - } - }, - "grants":[ - { - "altcurrency":"BAT", - "expiryTime":1640995200, - "probi":"30000000000000000000" - } - ], - "probi":"30000000000000000000", - "balance":"30.0000", - "unconfirmed":"0.0000", - "requestType":"httpSignature", - "unsignedTx":{ - "denomination":{ - "amount":"1", - "currency":"BAT" - }, - "destination":"6654ecb0-6079-4f6c-ba58-791cc890a561" - } -} \ No newline at end of file diff --git a/test/data/rewards-data/register_credential_resp.json b/test/data/rewards-data/register_credential_resp.json deleted file mode 100644 index 1f544791d16c..000000000000 --- a/test/data/rewards-data/register_credential_resp.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "surveyorIds":[ - "DL4LvvYYQL0UM99cK5Fzhj1hvno9tUXlVRDFTguKGlZ", - "6hK+xhExVChfP8y17iX4ZHDLDhQpAtFaexk6k0sPwj8", - "Dp8pzNQTa4eYI0IQiHN7+2bpx5rIkbGaNNV5LdffDz8", - "2xQG08DS+sBXlv7376WC+fkz/yZCr8K1QA4RghQKL9A" - ], - "verification":"5/alnMBLuQskB4nmX7Lj/6yZFqQCSrjGWMjwQXgpqPo B6vimIH1P4x95u2Md9WIEflpMa/HRJ41neCZ7wRkJzn 1 BdGcoaum1AMSMgUePvwVvsbP90XSZeGuqqJqcOKxKnm\n" -} \ No newline at end of file diff --git a/test/data/rewards-data/register_resp.json b/test/data/rewards-data/register_resp.json deleted file mode 100644 index 9aa960971d7e..000000000000 --- a/test/data/rewards-data/register_resp.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "payload":{}, - "registrarVK":"==========ANONLOGIN_VK_BEG==========\n8MMyJJmqhl/C8PVenwLrAucbcDAAEVPHYa/WMvCFmTu 1sO+XpYPdGS/nqkJoy7Ni6L4vfkX3+6+/8mH+YsoIFb 1\nAPz5/M6QPS0ovaIptqGkTWvwe0wAUpCS1nkn3o578Ow 4QV/FW74yTEzJ2YbYoSwoYJGLeKJ3JWphpHhddmszL2 1\n4Jw9l7H/0I+xLBKl7//SPhWAFhVBbp3XWcewn69WYEx 3bUNzMKNsnpWRKgivBfShbCsfhcR0MGD4CfOFeAYhPE 1\nA5KTrxKgqycFYnvo9BgmYafUJ46Gti/5T+4LmDYOEHL B33Ne5c9wPj1LZF4Nd2O3xeRrF5z2WHtTcnW0dRWJqP 1\n6Aza57xUODgaN5vBgHnr3S7aZQezQl9M6t/IUcLDFxy 6TG8AP2XmsXiDYNfULlMlKmkcIE8wypl41airjsUDOo 7AlIDZY0AA96/pbbBwhaMMaPlsU8zKFrh3nln9R+lta 4O7rb+E7S1RiHB6MZ9f9tX0F6J6TIxX2a5miuRXptf 1 0\n===========ANONLOGIN_VK_END==========" -} diff --git a/test/data/rewards-data/surveyor_voting_credential_resp.json b/test/data/rewards-data/surveyor_voting_credential_resp.json deleted file mode 100644 index ce1f661fb5b6..000000000000 --- a/test/data/rewards-data/surveyor_voting_credential_resp.json +++ /dev/null @@ -1,38 +0,0 @@ -[ - { - "signature":"e33991d4902bd9982d0fb80e15345a8, 6xUZRtd9M1S6fMQdoB/XGMWIc7M5O6c14K/MH4fec8k 3ge5Wxa0+ZQixl8vq65S0zEXzOteKehzQLIOqQ5HTtZ 1 FqgCWY32c0dJdy1Uk1vVdSVMKzdtQkK90zN8u+IAXmG 84/PiJiFAg5pRZfmxVKCnse9PZVuQtKZw+cadbg+yp2\n", - "payload":{ - "cohort":"grant" - }, - "surveyorId":"Dp8pzNQTa4eYI0IQiHN7+2bpx5rIkbGaNNV5LdffDz8", - "surveyVK":"==========ANONLOGIN_VK_BEG==========\nfHkhv0xgGRxhKjKvL/oUxFG8sLW97r7w+8T9q8V3+J 6ItDG6BFN7whKf/ozxrcu1om1GseOL7DzFq//KFNngC 1\n9x53aLXEYLwK92474w22NNAnqX9wg47QVZsbEyUQu3e 8zQySgRqFaHwr3zXQirxFXyvH0LSOoe1B/p1emXnN9b 1\n28TUqLrPcbIvDwoB2/0x/xetyYFUeYpoYLEnuL/IpJu 67GL6ZD1MXQJE+omJC8WKfWHfgefWyiuEwj8A+Ot5iF 1\n4YHzUOgQOIC4ELDVxDw1B17PyBfbAC3Cl2D8FUW687p 2TYXeNIqgNpNTSPE/7FkMM2f8xwsQ7Y65cUoXhrE5Zm 1\n7kkcQewu9qDkVTPL8YbJ1FT1/w0DHzRqufvo2mdeQQm 8iXLonMliV5WaWx4D1rEQUziVQxJMtMEOOdOSyEL1Zp 4v3hwfYFAtwOqDAZtbUFSBorwdaV5HudJGRcoKNbBDM 7TYlKvktCudGxluiM412UiwlEz6liG6rsmIjzaMxFxc 1 0\n===========ANONLOGIN_VK_END==========", - "registrarVK":"==========ANONLOGIN_VK_BEG==========\n8MMyJJmqhl/C8PVenwLrAucbcDAAEVPHYa/WMvCFmTu 1sO+XpYPdGS/nqkJoy7Ni6L4vfkX3+6+/8mH+YsoIFb 1\nAPz5/M6QPS0ovaIptqGkTWvwe0wAUpCS1nkn3o578Ow 4QV/FW74yTEzJ2YbYoSwoYJGLeKJ3JWphpHhddmszL2 1\n4Jw9l7H/0I+xLBKl7//SPhWAFhVBbp3XWcewn69WYEx 3bUNzMKNsnpWRKgivBfShbCsfhcR0MGD4CfOFeAYhPE 1\nA5KTrxKgqycFYnvo9BgmYafUJ46Gti/5T+4LmDYOEHL B33Ne5c9wPj1LZF4Nd2O3xeRrF5z2WHtTcnW0dRWJqP 1\n6Aza57xUODgaN5vBgHnr3S7aZQezQl9M6t/IUcLDFxy 6TG8AP2XmsXiDYNfULlMlKmkcIE8wypl41airjsUDOo 7AlIDZY0AA96/pbbBwhaMMaPlsU8zKFrh3nln9R+lta 4O7rb+E7S1RiHB6MZ9f9tX0F6J6TIxX2a5miuRXptf 1 0\n===========ANONLOGIN_VK_END==========" - }, - { - "signature":"e33991d4902bd9982d0fb80e15345a8, np1dFZKGnztf1sEQVpr5duBBT/v/tJJNKMzzqJG3qi 8DzsvRSG3DTJGfIL5cCTUJKNazPR+4JBDzTAMvfaORU 1 Ajm4Mflc+Cc3dJKfYT89K+cANXb5SWtYkHCyZTrKuFk 9+cwZgXzbPSL/0zNrriAsp5SDZcea70Vh9TcWUPtyhO\n", - "payload":{ - "cohort":"grant" - }, - "surveyorId":"DL4LvvYYQL0UM99cK5Fzhj1hvno9tUXlVRDFTguKGlZ", - "surveyVK":"==========ANONLOGIN_VK_BEG==========\n1zO1RppknZP6XugXsxlLH02rZcBJKg5Z67Kh+UCz/yG 6pVbM4d/GSLm5wh3jgZPML1lI3JTHzXgicITHOeeRd7 1\n39jyd/GNXUUhFyqhXneFQOWYe0bAlIrM4XFmoqh23VD 5CHNBUdI1U+kf9E1iIo2llO0ykIAcXQ3DHe3Wc8wF76 1\n2irIX55Dc3q3W8d0BvD0BCCbqGQEOJOolVKzfoJkTAQ 8lrMS3aipYyZrT/oBelV380bzSsE1Dnb99+678cmyqr 1\nB6IXJBZZDz7pWURlUeAruYF+3nu51/uY4F8XDwz/V8r 6F3u6xAEUAjpg9B+cnSPG0PJhpfnicR0vU3W75OHtew 1\n2FaPYcspv1g2Wzorwn9k/rMO8kw6ug2U4mp6ae9JqO/ 3fizfUe7sZP0ePrLkz60Oi+CJrCgc/M34aLSA014seP 6iZXw0iBlrWJf99VdhmqsLT3SB8PU3khNHVq/2HmgGI 2v/Y9X5nsUp2GCr5msiD1i6pAZuUFZ8LOj0QQUKPP56 1 0\n===========ANONLOGIN_VK_END==========", - "registrarVK":"==========ANONLOGIN_VK_BEG==========\n8MMyJJmqhl/C8PVenwLrAucbcDAAEVPHYa/WMvCFmTu 1sO+XpYPdGS/nqkJoy7Ni6L4vfkX3+6+/8mH+YsoIFb 1\nAPz5/M6QPS0ovaIptqGkTWvwe0wAUpCS1nkn3o578Ow 4QV/FW74yTEzJ2YbYoSwoYJGLeKJ3JWphpHhddmszL2 1\n4Jw9l7H/0I+xLBKl7//SPhWAFhVBbp3XWcewn69WYEx 3bUNzMKNsnpWRKgivBfShbCsfhcR0MGD4CfOFeAYhPE 1\nA5KTrxKgqycFYnvo9BgmYafUJ46Gti/5T+4LmDYOEHL B33Ne5c9wPj1LZF4Nd2O3xeRrF5z2WHtTcnW0dRWJqP 1\n6Aza57xUODgaN5vBgHnr3S7aZQezQl9M6t/IUcLDFxy 6TG8AP2XmsXiDYNfULlMlKmkcIE8wypl41airjsUDOo 7AlIDZY0AA96/pbbBwhaMMaPlsU8zKFrh3nln9R+lta 4O7rb+E7S1RiHB6MZ9f9tX0F6J6TIxX2a5miuRXptf 1 0\n===========ANONLOGIN_VK_END==========" - }, - { - "signature":"e33991d4902bd9982d0fb80e15345a8, wK0n1p7AzXMIe8nl0JnO/1J4zoZeOa2MgKszzzaHNq 2OrGCAwY2uMRrfkKvZeLkPhBXnnSuupS0MdQh5No8AF 1 9lLKQbGk/XBuAK+Ao9JBlS5JOTCY/ijhsNds60zEe9T 8RoGT2L+VUvfwkJN0WcsNtVHI1jTJG39nC4xFU0YvTk\n", - "payload":{ - "cohort":"grant" - }, - "surveyorId":"2xQG08DS+sBXlv7376WC+fkz/yZCr8K1QA4RghQKL9A", - "surveyVK":"==========ANONLOGIN_VK_BEG==========\n1+CkQ4F4RTpmPZDV4mV+PiolH20KROLwgNpqTp3HmV6 7/jGNEji/DuCasyaFGlLD4LHHe3kC3Pl+nQmwBmqzpp 1\n5FjtzmmKhfyid2WUhEe8WhVK3eozWZicTH7EKJwNvfP 9zV4SEpqH37/Ev/aJ9SlOoskRqjut6WzTgO0sI9r4bs 1\n8tV/QjIhcCut3CdjZIwU5ZAiDQiSF4z8jEnnTZZkG9v 9Bbc3klPeqLL1YtbUf5mAG4ibdNGSgXRF42bsvdUdnQ 1\n3sI+k3QmZp1OkBki3ErKQNoPuI4xuPv4bwLQBK2xkgi 1gooebLRhce4Qx1bI55wFzK8hb1lI7wshSYyHKG8hND 1\n6G0Otrpmkk6qfgDl4W4UwfV35Yklm4qXTQDuxrKKUAl BKlkaOYuTZJPC+AfzXm65s7nQNHj1RRJpBW6MJ+RRRc 4lJ0U5tLnc6htwXLRB1+TY4FeEf//Z7NlCJgBxanFHa 3WtnfCi9zc9+I1uPgEHr1Xb12kkYFGmL3fncBEcqzva 1 0\n===========ANONLOGIN_VK_END==========", - "registrarVK":"==========ANONLOGIN_VK_BEG==========\n8MMyJJmqhl/C8PVenwLrAucbcDAAEVPHYa/WMvCFmTu 1sO+XpYPdGS/nqkJoy7Ni6L4vfkX3+6+/8mH+YsoIFb 1\nAPz5/M6QPS0ovaIptqGkTWvwe0wAUpCS1nkn3o578Ow 4QV/FW74yTEzJ2YbYoSwoYJGLeKJ3JWphpHhddmszL2 1\n4Jw9l7H/0I+xLBKl7//SPhWAFhVBbp3XWcewn69WYEx 3bUNzMKNsnpWRKgivBfShbCsfhcR0MGD4CfOFeAYhPE 1\nA5KTrxKgqycFYnvo9BgmYafUJ46Gti/5T+4LmDYOEHL B33Ne5c9wPj1LZF4Nd2O3xeRrF5z2WHtTcnW0dRWJqP 1\n6Aza57xUODgaN5vBgHnr3S7aZQezQl9M6t/IUcLDFxy 6TG8AP2XmsXiDYNfULlMlKmkcIE8wypl41airjsUDOo 7AlIDZY0AA96/pbbBwhaMMaPlsU8zKFrh3nln9R+lta 4O7rb+E7S1RiHB6MZ9f9tX0F6J6TIxX2a5miuRXptf 1 0\n===========ANONLOGIN_VK_END==========" - }, - { - "signature":"e33991d4902bd9982d0fb80e15345a8, 7/RJ0Czhi/xqWHW9SleZpeMqfH1XaB9hAkBFXCEv4+v 8x8fAReJ+lC8bcvYixunBcdPnuKHnvmIQu05BHYV8eu 1 B9ISQ2BL/zrFXcpA3ZubI39Emp4OXMR59RxK0smWtba EN3+Ojq47AFEavHSsQJX5ZDP9FDhXc46HjzvyvkePS2\n", - "payload":{ - "cohort":"grant" - }, - "surveyorId":"6hK+xhExVChfP8y17iX4ZHDLDhQpAtFaexk6k0sPwj8", - "surveyVK":"==========ANONLOGIN_VK_BEG==========\n1zarqtmQbOnM8VaQWuVoXNy7FDgzDonn2yi88BKuYf 4SVoTBWpHO8t+bdgE5PPkEvJA/UV+i4/qeKPOEjkecq 1\n708Z/W3x0/bjS3HGSy72Mjcrda7SBADPZTOuvvNVCPO Aw90YltPtsD1NPItsAtSJyiebjmQ4hVqPbsphcfH6Gk 1\n9FV6ZP54l6onPqVgtjwq9gVsDOvFYQA1TOTPXFTdzXK 5Ekk3w0ssHs4d5mb/HCHgllBMDoQzW5NvZuyOzl3gGj 1\n30DJMVqu/059b57biHn0cvfYWVxmru81QZahAhv1Cbs 17F/L4IW9uY4r7sZPRSSlucFbDLgsA4YZDzbIS7yKJD 1\n1YQ03u23TXviyBwX3V+62AHHd27BrLArdYJF6szH0z2 T62hLNlMyDNIi6ZWIITeeBCZ6G5ya9tfTPjmepj48S Af65DgA+aX9mBk7g/Db0g4DG86i6Xj+kbNN2NFJqSaw 2Se5DacPgmJnky8WGMSgCY/S1LKWLnJL0Am4TSt1C88 1 0\n===========ANONLOGIN_VK_END==========", - "registrarVK":"==========ANONLOGIN_VK_BEG==========\n8MMyJJmqhl/C8PVenwLrAucbcDAAEVPHYa/WMvCFmTu 1sO+XpYPdGS/nqkJoy7Ni6L4vfkX3+6+/8mH+YsoIFb 1\nAPz5/M6QPS0ovaIptqGkTWvwe0wAUpCS1nkn3o578Ow 4QV/FW74yTEzJ2YbYoSwoYJGLeKJ3JWphpHhddmszL2 1\n4Jw9l7H/0I+xLBKl7//SPhWAFhVBbp3XWcewn69WYEx 3bUNzMKNsnpWRKgivBfShbCsfhcR0MGD4CfOFeAYhPE 1\nA5KTrxKgqycFYnvo9BgmYafUJ46Gti/5T+4LmDYOEHL B33Ne5c9wPj1LZF4Nd2O3xeRrF5z2WHtTcnW0dRWJqP 1\n6Aza57xUODgaN5vBgHnr3S7aZQezQl9M6t/IUcLDFxy 6TG8AP2XmsXiDYNfULlMlKmkcIE8wypl41airjsUDOo 7AlIDZY0AA96/pbbBwhaMMaPlsU8zKFrh3nln9R+lta 4O7rb+E7S1RiHB6MZ9f9tX0F6J6TIxX2a5miuRXptf 1 0\n===========ANONLOGIN_VK_END==========" - } -] \ No newline at end of file diff --git a/test/data/rewards-data/surveyor_voting_resp.json b/test/data/rewards-data/surveyor_voting_resp.json deleted file mode 100644 index 4e393f4a2e51..000000000000 --- a/test/data/rewards-data/surveyor_voting_resp.json +++ /dev/null @@ -1,26 +0,0 @@ -[ - { - "surveyorId":"2xQG08DS+sBXlv7376WC+fkz/yZCr8K1QA4RghQKL9A", - "response":{ - "submissionId":"9AbjitgUneZgh4iAPt/H+hXGoNotLiYAtMi7iSmF2j4 6BnZyrGE2HzQqrT35aJ2NOemY8vqcPhAznKLA6P75X7 1" - } - }, - { - "surveyorId":"Dp8pzNQTa4eYI0IQiHN7+2bpx5rIkbGaNNV5LdffDz8", - "response":{ - "submissionId":"8ujn5fBuye7jOGcSo6u7kObRfsUPDTx8B75dddsTZVD 7jNhWSYOu6q02edoOJ35olbqcskQfref9zFpl8kolFF 1" - } - }, - { - "surveyorId":"6hK+xhExVChfP8y17iX4ZHDLDhQpAtFaexk6k0sPwj8", - "response":{ - "submissionId":"3r6tC/femy/jO8Uh64Je3myVyp8JP+zkCVDL1J68z6Z 5eO//I2fzeSE8MeBvndxQW5X/Nnr4/r4UClxkDf7HBn 1" - } - }, - { - "surveyorId":"DL4LvvYYQL0UM99cK5Fzhj1hvno9tUXlVRDFTguKGlZ", - "response":{ - "submissionId":"1NgQ3Sd8OeeTPMYmEOHe9WROm+aS3eEG77LCwr6PJcx 1KjOZkq8qo9t0THIepkHffKrg/jPNS/bBeaeB3RTuV0 1" - } - } -] \ No newline at end of file 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 3f0665179899..b28208d979ea 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 @@ -64,7 +64,7 @@ class ConfirmationsClientMock : public ConfirmationsClient { MOCK_METHOD4(OnReconcileComplete, void( Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type)); diff --git a/vendor/bat-native-ledger/BUILD.gn b/vendor/bat-native-ledger/BUILD.gn index f31ab01f40d7..d2428e470319 100644 --- a/vendor/bat-native-ledger/BUILD.gn +++ b/vendor/bat-native-ledger/BUILD.gn @@ -116,14 +116,24 @@ source_set("ledger") { "src/bat/ledger/internal/common/time_util.h", "src/bat/ledger/internal/contribution/contribution.cc", "src/bat/ledger/internal/contribution/contribution.h", + "src/bat/ledger/internal/contribution/contribution_ac.cc", + "src/bat/ledger/internal/contribution/contribution_ac.h", + "src/bat/ledger/internal/contribution/contribution_anon_card.cc", + "src/bat/ledger/internal/contribution/contribution_anon_card.h", + "src/bat/ledger/internal/contribution/contribution_external_wallet.cc", + "src/bat/ledger/internal/contribution/contribution_external_wallet.h", + "src/bat/ledger/internal/contribution/contribution_monthly.cc", + "src/bat/ledger/internal/contribution/contribution_monthly.h", + "src/bat/ledger/internal/contribution/contribution_monthly_util.cc", + "src/bat/ledger/internal/contribution/contribution_monthly_util.h", + "src/bat/ledger/internal/contribution/contribution_sku.cc", + "src/bat/ledger/internal/contribution/contribution_sku.h", + "src/bat/ledger/internal/contribution/contribution_tip.cc", + "src/bat/ledger/internal/contribution/contribution_tip.h", "src/bat/ledger/internal/contribution/contribution_unblinded.cc", "src/bat/ledger/internal/contribution/contribution_unblinded.h", "src/bat/ledger/internal/contribution/contribution_util.cc", "src/bat/ledger/internal/contribution/contribution_util.h", - "src/bat/ledger/internal/contribution/phase_one.cc", - "src/bat/ledger/internal/contribution/phase_one.h", - "src/bat/ledger/internal/contribution/phase_two.cc", - "src/bat/ledger/internal/contribution/phase_two.h", "src/bat/ledger/internal/contribution/unverified.cc", "src/bat/ledger/internal/contribution/unverified.h", "src/bat/ledger/internal/credentials/credentials.h", @@ -133,6 +143,12 @@ source_set("ledger") { "src/bat/ledger/internal/credentials/credentials_factory.h", "src/bat/ledger/internal/credentials/credentials_promotion.cc", "src/bat/ledger/internal/credentials/credentials_promotion.h", + "src/bat/ledger/internal/credentials/credentials_redeem.cc", + "src/bat/ledger/internal/credentials/credentials_redeem.h", + "src/bat/ledger/internal/credentials/credentials_sku.cc", + "src/bat/ledger/internal/credentials/credentials_sku.h", + "src/bat/ledger/internal/credentials/credentials_trigger.cc", + "src/bat/ledger/internal/credentials/credentials_trigger.h", "src/bat/ledger/internal/credentials/credentials_util.cc", "src/bat/ledger/internal/credentials/credentials_util.h", "src/bat/ledger/internal/database/database.cc", @@ -175,6 +191,12 @@ source_set("ledger") { "src/bat/ledger/internal/database/database_server_publisher_info.h", "src/bat/ledger/internal/database/database_server_publisher_links.cc", "src/bat/ledger/internal/database/database_server_publisher_links.h", + "src/bat/ledger/internal/database/database_sku_order.cc", + "src/bat/ledger/internal/database/database_sku_order.h", + "src/bat/ledger/internal/database/database_sku_order_items.cc", + "src/bat/ledger/internal/database/database_sku_order_items.h", + "src/bat/ledger/internal/database/database_sku_transaction.cc", + "src/bat/ledger/internal/database/database_sku_transaction.h", "src/bat/ledger/internal/database/database_table.cc", "src/bat/ledger/internal/database/database_table.h", "src/bat/ledger/internal/database/database_unblinded_token.cc", @@ -203,40 +225,16 @@ source_set("ledger") { "src/bat/ledger/internal/promotion/promotion_transfer.h", "src/bat/ledger/internal/promotion/promotion_util.cc", "src/bat/ledger/internal/promotion/promotion_util.h", - "src/bat/ledger/internal/properties/ballot_properties.cc", - "src/bat/ledger/internal/properties/ballot_properties.h", - "src/bat/ledger/internal/properties/batch_proof_properties.cc", - "src/bat/ledger/internal/properties/batch_proof_properties.h", "src/bat/ledger/internal/properties/client_properties.cc", "src/bat/ledger/internal/properties/client_properties.h", - "src/bat/ledger/internal/properties/current_reconcile_properties.cc", - "src/bat/ledger/internal/properties/current_reconcile_properties.h", - "src/bat/ledger/internal/properties/publisher_properties.cc", - "src/bat/ledger/internal/properties/publisher_properties.h", "src/bat/ledger/internal/properties/publisher_settings_properties.cc", "src/bat/ledger/internal/properties/publisher_settings_properties.h", - "src/bat/ledger/internal/properties/publisher_vote_properties.cc", - "src/bat/ledger/internal/properties/publisher_vote_properties.h", - "src/bat/ledger/internal/properties/publisher_votes_properties.cc", - "src/bat/ledger/internal/properties/publisher_votes_properties.h", - "src/bat/ledger/internal/properties/reconcile_direction_properties.cc", - "src/bat/ledger/internal/properties/reconcile_direction_properties.h", - "src/bat/ledger/internal/properties/reconcile_request_properties.cc", - "src/bat/ledger/internal/properties/reconcile_request_properties.h", "src/bat/ledger/internal/properties/report_balance_properties.cc", "src/bat/ledger/internal/properties/report_balance_properties.h", - "src/bat/ledger/internal/properties/surveyor_properties.cc", - "src/bat/ledger/internal/properties/surveyor_properties.h", - "src/bat/ledger/internal/properties/transaction_ballot_properties.cc", - "src/bat/ledger/internal/properties/transaction_ballot_properties.h", - "src/bat/ledger/internal/properties/transaction_properties.cc", - "src/bat/ledger/internal/properties/transaction_properties.h", "src/bat/ledger/internal/properties/unsigned_tx_properties.cc", "src/bat/ledger/internal/properties/unsigned_tx_properties.h", "src/bat/ledger/internal/properties/wallet_info_properties.cc", "src/bat/ledger/internal/properties/wallet_info_properties.h", - "src/bat/ledger/internal/properties/winner_properties.cc", - "src/bat/ledger/internal/properties/winner_properties.h", "src/bat/ledger/internal/publisher/publisher.cc", "src/bat/ledger/internal/publisher/publisher.h", "src/bat/ledger/internal/publisher/publisher_server_list.cc", @@ -247,37 +245,34 @@ source_set("ledger") { "src/bat/ledger/internal/request/request_attestation.h", "src/bat/ledger/internal/request/request_promotion.cc", "src/bat/ledger/internal/request/request_promotion.h", + "src/bat/ledger/internal/request/request_sku.cc", + "src/bat/ledger/internal/request/request_sku.h", "src/bat/ledger/internal/request/request_util.cc", "src/bat/ledger/internal/request/request_util.h", + "src/bat/ledger/internal/sku/sku.h", + "src/bat/ledger/internal/sku/sku_brave.cc", + "src/bat/ledger/internal/sku/sku_brave.h", + "src/bat/ledger/internal/sku/sku_common.cc", + "src/bat/ledger/internal/sku/sku_common.h", + "src/bat/ledger/internal/sku/sku_factory.cc", + "src/bat/ledger/internal/sku/sku_factory.h", + "src/bat/ledger/internal/sku/sku_merchant.cc", + "src/bat/ledger/internal/sku/sku_merchant.h", + "src/bat/ledger/internal/sku/sku_order.cc", + "src/bat/ledger/internal/sku/sku_order.h", + "src/bat/ledger/internal/sku/sku_transaction.cc", + "src/bat/ledger/internal/sku/sku_transaction.h", + "src/bat/ledger/internal/sku/sku_util.cc", + "src/bat/ledger/internal/sku/sku_util.h", "src/bat/ledger/internal/state_keys.h", - "src/bat/ledger/internal/state/ballot_state.cc", - "src/bat/ledger/internal/state/ballot_state.h", "src/bat/ledger/internal/state/client_state.cc", "src/bat/ledger/internal/state/client_state.h", - "src/bat/ledger/internal/state/current_reconcile_state.cc", - "src/bat/ledger/internal/state/current_reconcile_state.h", "src/bat/ledger/internal/state/publisher_settings_state.cc", "src/bat/ledger/internal/state/publisher_settings_state.h", - "src/bat/ledger/internal/state/publisher_state.cc", - "src/bat/ledger/internal/state/publisher_state.h", - "src/bat/ledger/internal/state/publisher_vote_state.cc", - "src/bat/ledger/internal/state/publisher_vote_state.h", - "src/bat/ledger/internal/state/publisher_votes_state.cc", - "src/bat/ledger/internal/state/publisher_votes_state.h", - "src/bat/ledger/internal/state/reconcile_direction_state.cc", - "src/bat/ledger/internal/state/reconcile_direction_state.h", - "src/bat/ledger/internal/state/reconcile_request_state.cc", - "src/bat/ledger/internal/state/reconcile_request_state.h", "src/bat/ledger/internal/state/report_balance_state.cc", "src/bat/ledger/internal/state/report_balance_state.h", "src/bat/ledger/internal/state/state_reader.h", "src/bat/ledger/internal/state/state_writer.h", - "src/bat/ledger/internal/state/surveyor_state.cc", - "src/bat/ledger/internal/state/surveyor_state.h", - "src/bat/ledger/internal/state/transaction_ballot_state.cc", - "src/bat/ledger/internal/state/transaction_ballot_state.h", - "src/bat/ledger/internal/state/transaction_state.cc", - "src/bat/ledger/internal/state/transaction_state.h", "src/bat/ledger/internal/state/unsigned_tx_state.cc", "src/bat/ledger/internal/state/unsigned_tx_state.h", "src/bat/ledger/internal/state/wallet_info_state.cc", diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger.h b/vendor/bat-native-ledger/include/bat/ledger/ledger.h index 8275d0f810f6..294f0b9f3038 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger.h @@ -352,6 +352,11 @@ class LEDGER_EXPORT Ledger { virtual void GetAllMonthlyReportIds( ledger::GetAllMonthlyReportIdsCallback callback) = 0; + + virtual void ProcessSKU( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) = 0; }; } // namespace ledger 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 463fa0d326e8..df1a7e90e2e9 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h @@ -81,6 +81,15 @@ using GetCredsBatchCallback = std::function; using GetAllCredsBatchCallback = std::function; using GetPromotionListCallback = std::function; +using SKUOrderCallback = + std::function; + +using TransactionCallback = + std::function; + +using GetSKUOrderCallback = std::function; +using GetSKUTransactionCallback = std::function; + class LEDGER_EXPORT LedgerClient { public: virtual ~LedgerClient() = default; @@ -91,7 +100,7 @@ class LEDGER_EXPORT LedgerClient { virtual void OnReconcileComplete( const Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type) = 0; 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 65f5b7b13a59..955961971378 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h +++ b/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h @@ -139,6 +139,24 @@ using ServerPublisherInfoPtr = mojom::ServerPublisherInfoPtr; using ServerPublisherPartial = mojom::ServerPublisherPartial; using ServerPublisherPartialPtr = mojom::ServerPublisherPartialPtr; +using SKUOrder = mojom::SKUOrder; +using SKUOrderPtr = mojom::SKUOrderPtr; + +using SKUOrderStatus = mojom::SKUOrderStatus; + +using SKUOrderItem = mojom::SKUOrderItem; +using SKUOrderItemPtr = mojom::SKUOrderItemPtr; +using SKUOrderItemList = std::vector; + +using SKUOrderItemType = mojom::SKUOrderItemType; + +using SKUTransaction = mojom::SKUTransaction; +using SKUTransactionPtr = mojom::SKUTransactionPtr; + +using SKUTransactionStatus = mojom::SKUTransactionStatus; + +using SKUTransactionType = mojom::SKUTransactionType; + using TransferFee = mojom::TransferFee; using TransferFeePtr = mojom::TransferFeePtr; using TransferFeeList = std::map; 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 b07969ee06f5..299c221996ba 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 @@ -11,13 +11,17 @@ enum ContributionStep { STEP_COMPLETED = -1, STEP_NO = 0, STEP_START = 1, - STEP_SUGGESTIONS = 2 + STEP_PREPARE = 2, + STEP_RESERVE = 3, + STEP_EXTERNAL_TRANSACTION = 4, + STEP_CREDS = 5 }; enum ContributionProcessor { NONE = 0, BRAVE_TOKENS = 1, - UPHOLD = 2 + UPHOLD = 2, + BRAVE_USER_FUNDS = 3 }; struct ContributionInfo { @@ -133,6 +137,7 @@ struct MediaEventInfo { }; struct ExternalWallet { + string type; string token; string address; WalletStatus status; @@ -241,7 +246,9 @@ enum Result { ALREADY_EXISTS = 26, SAFETYNET_ATTESTATION_FAILED = 27, DATABASE_INIT_FAILED = 28, - RETRY = 29 + RETRY = 29, + RETRY_SHORT = 30, + RETRY_LONG = 30 }; enum PublisherStatus { @@ -278,6 +285,8 @@ enum RewardsType { AUTO_CONTRIBUTE = 2, ONE_TIME_TIP = 8, RECURRING_TIP = 16, + TRANSFER = 17, + PAYMENT = 18 }; enum ReportType { @@ -432,7 +441,8 @@ struct MonthlyReportInfo { enum CredsBatchType { NONE = 0, - PROMOTION = 1 + PROMOTION = 1, + SKU = 2 }; enum CredsBatchStatus { @@ -456,3 +466,63 @@ struct CredsBatch { CredsBatchStatus status; }; +enum SKUOrderStatus { + NONE = 0, + PENDING = 1, + PAID = 2, + FULFILLED = 3, + CANCELED = 4 +}; + +struct SKUOrder { + string order_id; + double total_amount; + string merchant_id; + string location; + SKUOrderStatus status; + string contribution_id; + uint64 created_at; + array items; +}; + +enum SKUOrderItemType { + NONE = 0, + SINGLE_USE = 1 +}; + +struct SKUOrderItem { + string order_item_id; + string order_id; + string sku; + int32 quantity; + double price; + string name; + string description; + SKUOrderItemType type; + uint64 expires_at; + uint64 created_at; +}; + +enum SKUTransactionType { + NONE = 0, + UPHOLD = 1, + ANONYMOUS_CARD = 2, + TOKENS = 3 +}; + +enum SKUTransactionStatus { + NONE = 0, + CREATED = 1, + COMPLETED = 2 +}; + +struct SKUTransaction { + string transaction_id; + string order_id; + string external_transaction_id; + SKUTransactionType type; + double amount; + SKUTransactionStatus status; + uint64 created_at; +}; + 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 84e6acb58de0..9f5686c50d35 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 @@ -171,9 +171,7 @@ bool getJSONRates(const std::string& json, bool getJSONWalletInfo(const std::string& json, ledger::WalletInfoProperties* walletInfo, - std::string* fee_currency, - double* fee_amount, - unsigned int* days) { + double* fee_amount) { rapidjson::Document d; d.Parse(json.c_str()); @@ -193,20 +191,16 @@ bool getJSONWalletInfo(const std::string& json, walletInfo->address_card_id = d["wallet"]["addresses"]["CARD_ID"].GetString(); - *days = d["payload"]["adFree"]["days"].GetUint(); const auto & fee = d["payload"]["adFree"]["fee"].GetObject(); auto itr = fee.MemberBegin(); if (itr != fee.MemberEnd()) { - *fee_currency = itr->name.GetString(); *fee_amount = itr->value.GetDouble(); } } else if (d.HasMember("parameters") && d["parameters"].IsObject()) { walletInfo->address_card_id = d["addresses"]["CARD_ID"].GetString(); - *days = d["parameters"]["adFree"]["days"].GetUint(); const auto & fee = d["parameters"]["adFree"]["fee"].GetObject(); auto itr = fee.MemberBegin(); if (itr != fee.MemberEnd()) { - *fee_currency = itr->name.GetString(); *fee_amount = itr->value.GetDouble(); } } 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 41b07a477f10..51c8fde9820c 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 @@ -31,9 +31,7 @@ bool getJSONList(const std::string& fieldName, bool getJSONWalletInfo(const std::string& json, ledger::WalletInfoProperties* walletInfo, - std::string* fee_currency, - double* fee_amount, - unsigned int* days); + double* fee_amount); bool getJSONRates(const std::string& json, std::map* rates); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc index 8e0c8beab19a..b380c4804cbd 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc @@ -75,47 +75,6 @@ void BatState::OnSaveState(const ledger::Result result) { } } -void BatState::AddReconcile(const std::string& viewing_id, - const ledger::CurrentReconcileProperties& reconcile) { - state_->current_reconciles.insert(std::make_pair(viewing_id, reconcile)); - SaveState(); -} - -bool BatState::UpdateReconcile( - const ledger::CurrentReconcileProperties& reconcile) { - if (state_->current_reconciles.count(reconcile.viewing_id) == 0) { - return false; - } - - state_->current_reconciles[reconcile.viewing_id] = reconcile; - SaveState(); - return true; -} - -ledger::CurrentReconcileProperties BatState::GetReconcileById( - const std::string& viewingId) const { - if (state_->current_reconciles.count(viewingId) == 0) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << - "Could not find any reconcile tasks with the id " << viewingId; - return ledger::CurrentReconcileProperties(); - } - - return state_->current_reconciles[viewingId]; -} - -bool BatState::ReconcileExists(const std::string& viewingId) const { - return state_->current_reconciles.count(viewingId) > 0; -} - -void BatState::RemoveReconcileById(const std::string& viewingId) { - ledger::CurrentReconciles::iterator it = - state_->current_reconciles.find(viewingId); - if (it != state_->current_reconciles.end()) { - state_->current_reconciles.erase(it); - SaveState(); - } -} - void BatState::SetRewardsMainEnabled(bool enabled) { state_->rewards_enabled = enabled; SaveState(); @@ -271,53 +230,6 @@ void BatState::SetWalletProperties( SaveState(); } -unsigned int BatState::GetDays() const { - return state_->days; -} - -void BatState::SetDays(unsigned int days) { - state_->days = days; - SaveState(); -} - -const ledger::Transactions& BatState::GetTransactions() const { - return state_->transactions; -} - -void BatState::SetTransactions( - const ledger::Transactions& transactions) { - state_->transactions = transactions; - SaveState(); -} - -const ledger::Ballots& BatState::GetBallots() const { - return state_->ballots; -} - -void BatState::SetBallots(const ledger::Ballots& ballots) { - state_->ballots = ballots; - SaveState(); -} - -const ledger::PublisherVotes& BatState::GetPublisherVotes() const { - return state_->publisher_votes; -} - -void BatState::SetPublisherVotes( - const ledger::PublisherVotes& publisher_votes) { - state_->publisher_votes = publisher_votes; - SaveState(); -} - -const std::string& BatState::GetCurrency() const { - return state_->fee_currency; -} - -void BatState::SetCurrency(const std::string ¤cy) { - state_->fee_currency = currency; - SaveState(); -} - uint64_t BatState::GetBootStamp() const { return state_->boot_timestamp; } @@ -327,39 +239,6 @@ void BatState::SetBootStamp(uint64_t stamp) { SaveState(); } -const std::string& BatState::GetMasterUserToken() const { - return state_->master_user_token; -} - -void BatState::SetMasterUserToken(const std::string &token) { - state_->master_user_token = token; - SaveState(); -} - -bool BatState::AddReconcileStep(const std::string& viewing_id, - ledger::ContributionRetry step, - int level) { - ledger::CurrentReconcileProperties reconcile = GetReconcileById(viewing_id); - - if (reconcile.viewing_id.empty()) { - return false; - } - - // don't save step when you are already in the same step - if (reconcile.retry_step == step && level == -1) { - return true; - } - - reconcile.retry_step = step; - reconcile.retry_level = level; - - return UpdateReconcile(reconcile); -} - -const ledger::CurrentReconciles& BatState::GetCurrentReconciles() const { - return state_->current_reconciles; -} - double BatState::GetDefaultContributionAmount() { return state_->wallet.fee_amount; } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h index ef4c1537f637..a5600ce1553a 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h @@ -11,11 +11,7 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/properties/ballot_properties.h" -#include "bat/ledger/internal/properties/publisher_votes_properties.h" #include "bat/ledger/internal/properties/client_properties.h" -#include "bat/ledger/internal/properties/current_reconcile_properties.h" -#include "bat/ledger/internal/properties/transaction_properties.h" #include "bat/ledger/internal/properties/wallet_info_properties.h" namespace bat_ledger { @@ -31,20 +27,6 @@ class BatState { bool LoadState(const std::string& data); - void AddReconcile( - const std::string& viewing_id, - const ledger::CurrentReconcileProperties& reconcile); - - bool UpdateReconcile( - const ledger::CurrentReconcileProperties& reconcile); - - ledger::CurrentReconcileProperties GetReconcileById( - const std::string& viewingId) const; - - void RemoveReconcileById(const std::string& viewingId); - - bool ReconcileExists(const std::string& viewingId) const; - void SetRewardsMainEnabled(bool enabled); bool GetRewardsMainEnabled() const; @@ -96,42 +78,10 @@ class BatState { void SetWalletProperties( ledger::WalletProperties* properties); - unsigned int GetDays() const; - - void SetDays(unsigned int days); - - const ledger::Transactions& GetTransactions() const; - - void SetTransactions( - const ledger::Transactions& transactions); - - const ledger::Ballots& GetBallots() const; - - void SetBallots(const ledger::Ballots& ballots); - - const ledger::PublisherVotes& GetPublisherVotes() const; - - void SetPublisherVotes( - const ledger::PublisherVotes& publisher_votes); - - const std::string& GetCurrency() const; - - void SetCurrency(const std::string& currency); - uint64_t GetBootStamp() const; void SetBootStamp(uint64_t stamp); - const std::string& GetMasterUserToken() const; - - void SetMasterUserToken(const std::string& token); - - bool AddReconcileStep(const std::string& viewing_id, - ledger::ContributionRetry step, - int level); - - const ledger::CurrentReconciles& GetCurrentReconciles() const; - double GetDefaultContributionAmount(); void SetInlineTipSetting(const std::string& key, bool enabled); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.cc index 9efa460872f9..3c414c1db0a0 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.cc @@ -8,6 +8,7 @@ #include "base/json/json_reader.h" #include "base/json/json_writer.h" +#include "base/strings/string_number_conversions.h" #include "bat/ledger/internal/common/bind_util.h" namespace braveledger_bind_util { @@ -543,4 +544,144 @@ ledger::MonthlyReportInfoPtr FromStringToMonthlyReport( return info; } +std::string FromSKUOrderToString(ledger::SKUOrderPtr info) { + if (!info) { + return "{}"; + } + + base::Value items(base::Value::Type::LIST); + for (const auto& item : info->items) { + base::Value order_item(base::Value::Type::DICTIONARY); + order_item.SetStringKey("order_item_id", item->order_item_id); + order_item.SetStringKey("order_id", item->order_id); + order_item.SetStringKey("sku", item->sku); + order_item.SetIntKey("quantity", item->quantity); + order_item.SetDoubleKey("price", item->price); + order_item.SetStringKey("name", item->name); + order_item.SetStringKey("description", item->description); + order_item.SetIntKey("type", static_cast(item->type)); + order_item.SetStringKey("expires_at", std::to_string(item->expires_at)); + items.Append(std::move(order_item)); + } + + base::Value order(base::Value::Type::DICTIONARY); + order.SetStringKey("order_id", info->order_id); + order.SetDoubleKey("total_amount", info->total_amount); + order.SetStringKey("merchant_id", info->merchant_id); + order.SetStringKey("location", info->location); + order.SetIntKey("status", static_cast(info->status)); + order.SetStringKey("contribution_id", info->contribution_id); + order.SetKey("items", std::move(items)); + + std::string json; + base::JSONWriter::Write(order, &json); + + return json; +} + +ledger::SKUOrderPtr FromStringToSKUOrder(const std::string& data) { + base::Optional value = base::JSONReader::Read(data); + + if (!value || !value->is_dict()) { + return nullptr; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + return nullptr; + } + + auto order = ledger::SKUOrder::New(); + + std::string id; + const auto* order_id = dictionary->FindStringKey("order_id"); + if (order_id) { + order->order_id = *order_id; + id = order->order_id; + } + + if (id.empty()) { + return nullptr; + } + + const auto total_amount = dictionary->FindDoubleKey("total_amount"); + if (total_amount) { + order->total_amount = *total_amount; + } + + const auto* merchant_id = dictionary->FindStringKey("merchant_id"); + if (merchant_id) { + order->merchant_id = *merchant_id; + } + + const auto* location = dictionary->FindStringKey("location"); + if (location) { + order->location = *location; + } + + const auto status = dictionary->FindIntKey("status"); + if (status) { + order->status = static_cast(*status); + } + + const auto* contribution_id = dictionary->FindStringKey("contribution_id"); + if (contribution_id) { + order->contribution_id = *contribution_id; + } + + auto* items = dictionary->FindListKey("items"); + if (items) { + ledger::SKUOrderItemPtr order_item = nullptr; + for (const auto& item : items->GetList()) { + order_item = ledger::SKUOrderItem::New(); + + const auto* order_item_id = item.FindStringKey("order_item_id"); + if (order_item_id) { + order_item->order_item_id = *order_item_id; + } + + order_item->order_id = id; + + const auto* sku = item.FindStringKey("sku"); + if (sku) { + order_item->sku = *sku; + } + + const auto quantity = item.FindIntKey("quantity"); + if (quantity) { + order_item->quantity = *quantity; + } + + const auto price = item.FindDoubleKey("price"); + if (price) { + order_item->price = *price; + } + + const auto* name = item.FindStringKey("name"); + if (name) { + order_item->name = *name; + } + + const auto* description = item.FindStringKey("description"); + if (description) { + order_item->description = *description; + } + + const auto type = item.FindDoubleKey("type"); + if (type) { + order_item->type = static_cast(*type); + } + + const auto* expires_at = item.FindStringKey("expires_at"); + if (expires_at) { + base::StringToUint64(*expires_at, &order_item->expires_at); + } + + order->items.push_back(std::move(order_item)); + } + } + + return order; +} + } // namespace braveledger_bind_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.h index b6cd49560e29..b6f8ae279e2f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/common/bind_util.h @@ -43,6 +43,10 @@ std::string FromMonthlyReportToString(ledger::MonthlyReportInfoPtr info); ledger::MonthlyReportInfoPtr FromStringToMonthlyReport(const std::string& data); +std::string FromSKUOrderToString(ledger::SKUOrderPtr info); + +ledger::SKUOrderPtr FromStringToSKUOrder(const std::string& data); + } // namespace braveledger_bind_util #endif // BRAVELEDGER_COMMON_BIND_UTIL_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 02145eb6ebc9..fa83a6497c66 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 @@ -12,19 +12,21 @@ #include #include "base/guid.h" -#include "base/time/time.h" #include "bat/ledger/global_constants.h" #include "bat/ledger/internal/bat_util.h" #include "bat/ledger/internal/common/bind_util.h" #include "bat/ledger/internal/common/time_util.h" #include "bat/ledger/internal/contribution/contribution.h" +#include "bat/ledger/internal/contribution/contribution_ac.h" +#include "bat/ledger/internal/contribution/contribution_anon_card.h" +#include "bat/ledger/internal/contribution/contribution_external_wallet.h" +#include "bat/ledger/internal/contribution/contribution_monthly.h" +#include "bat/ledger/internal/contribution/contribution_tip.h" +#include "bat/ledger/internal/contribution/contribution_sku.h" #include "bat/ledger/internal/contribution/contribution_unblinded.h" #include "bat/ledger/internal/contribution/contribution_util.h" -#include "bat/ledger/internal/contribution/phase_one.h" -#include "bat/ledger/internal/contribution/phase_two.h" #include "bat/ledger/internal/contribution/unverified.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/ledger_impl.h" #include "brave_base/random.h" @@ -34,62 +36,54 @@ 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; - } +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) : ledger_(ledger), - phase_one_(std::make_unique(ledger, this)), - phase_two_(std::make_unique(ledger, this)), unverified_(std::make_unique(ledger, this)), unblinded_(std::make_unique(ledger)), + sku_(std::make_unique(ledger, this)), uphold_(std::make_unique(ledger)), + monthly_(std::make_unique(ledger, this)), + ac_(std::make_unique(ledger, this)), + tip_(std::make_unique(ledger, this)), + anon_card_(std::make_unique(ledger, this)), last_reconcile_timer_id_(0u), queue_timer_id_(0u) { + DCHECK(ledger_ && uphold_); + external_wallet_ = std::make_unique( + ledger, + this, + uphold_.get()); } -Contribution::~Contribution() { -} +Contribution::~Contribution() = default; void Contribution::Initialize() { - phase_two_->Initialize(); uphold_->Initialize(); - unblinded_->Initialize(); - // Resume in progress contributions - ledger::CurrentReconciles currentReconciles = ledger_->GetCurrentReconciles(); - - for (const auto& value : currentReconciles) { - ledger::CurrentReconcileProperties reconcile = value.second; - - if (reconcile.retry_step == ledger::ContributionRetry::STEP_FINAL || - reconcile.retry_step == ledger::ContributionRetry::STEP_NO) { - ledger_->RemoveReconcileById(reconcile.viewing_id); - } else { - DoRetry(reconcile.viewing_id); - } - } - - // Process contribution queue CheckContributionQueue(); + CheckNotCompletedContributions(); } void Contribution::CheckContributionQueue() { @@ -119,136 +113,35 @@ void Contribution::OnProcessContributionQueue( } queue_in_progress_ = true; - - InitReconcile(std::move(info)); -} - -void Contribution::HasSufficientBalance( - ledger::HasSufficientBalanceToReconcileCallback callback) { - ledger_->FetchBalance( - std::bind(&Contribution::OnSufficientBalanceWallet, - this, - _1, - _2, - callback)); + Start(std::move(info)); } -void Contribution::OnSufficientBalanceWallet( - const ledger::Result result, - ledger::BalancePtr properties, - ledger::HasSufficientBalanceToReconcileCallback callback) { - if (result != ledger::Result::LEDGER_OK || !properties) { - return; - } - - auto tips_callback = - std::bind(&Contribution::OnHasSufficientBalance, - this, - _1, - properties->total, - callback); +void Contribution::CheckNotCompletedContributions() { + auto get_callback = std::bind(&Contribution::NotCompletedContributions, + this, + _1); - ledger_->GetRecurringTips(tips_callback); + ledger_->GetNotCompletedContributions(get_callback); } -void Contribution::OnHasSufficientBalance( - const ledger::PublisherInfoList& publisher_list, - const double balance, - ledger::HasSufficientBalanceToReconcileCallback callback) { - if (publisher_list.empty()) { - callback(true); +void Contribution::NotCompletedContributions( + ledger::ContributionInfoList list) { + if (list.empty()) { return; } - const auto total = GetTotalFromRecurringVerified(publisher_list); - callback(balance >= total); -} - -// static -double Contribution::GetTotalFromRecurringVerified( - const ledger::PublisherInfoList& publisher_list) { - double total_recurring_amount = 0.0; - for (const auto& publisher : publisher_list) { - if (publisher->id.empty()) { + for (auto& item : list) { + if (!item) { continue; } - if (publisher->status == ledger::PublisherStatus::VERIFIED) { - total_recurring_amount += publisher->weight; - } + SetRetryCounter(std::move(item)); } - return total_recurring_amount; } -ledger::PublisherInfoList Contribution::GetVerifiedListRecurring( - const ledger::PublisherInfoList& list) { - ledger::PublisherInfoList verified; - ledger::PendingContributionList non_verified; - - for (const auto& publisher : list) { - if (publisher->id.empty() || publisher->weight == 0.0) { - continue; - } - - if (publisher->status != ledger::PublisherStatus::NOT_VERIFIED) { - verified.push_back(publisher->Clone()); - } else { - auto contribution = ledger::PendingContribution::New(); - contribution->amount = publisher->weight; - contribution->publisher_key = publisher->id; - contribution->viewing_id = ""; - contribution->type = ledger::RewardsType::RECURRING_TIP; - - non_verified.push_back(std::move(contribution)); - } - } - - if (non_verified.size() > 0) { - auto save_callback = std::bind(&Contribution::OnSavePendingContribution, - this, - _1); - ledger_->SavePendingContribution(std::move(non_verified), save_callback); - } - - return verified; -} - -void Contribution::OnSavePendingContribution(const ledger::Result result) { - ledger_->PendingContributionSaved(result); -} - -void Contribution::StartRecurringTips(ledger::ResultCallback callback) { - ledger_->GetRecurringTips( - std::bind(&Contribution::PrepareRecurringList, - this, - _1, - callback)); -} - -void Contribution::PrepareRecurringList( - ledger::PublisherInfoList list, - ledger::ResultCallback callback) { - auto verified_list = GetVerifiedListRecurring(list); - - for (const auto &item : verified_list) { - ledger::ContributionQueuePublisherList queue_list; - auto publisher = ledger::ContributionQueuePublisher::New(); - publisher->publisher_key = item->id; - publisher->amount_percent = 100.0; - queue_list.push_back(std::move(publisher)); - - auto queue = ledger::ContributionQueue::New(); - queue->type = ledger::RewardsType::RECURRING_TIP; - queue->amount = item->weight; - queue->partial = false; - queue->publishers = std::move(queue_list); - - ledger_->SaveContributionQueue( - std::move(queue), - [](const ledger::Result _){}); - } - CheckContributionQueue(); - callback(ledger::Result::LEDGER_OK); +void Contribution::HasSufficientBalance( + ledger::HasSufficientBalanceToReconcileCallback callback) { + monthly_->HasSufficientBalance(callback); } void Contribution::ResetReconcileStamp() { @@ -263,106 +156,43 @@ void Contribution::StartMonthlyContribution() { } BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "Staring monthly contribution"; - auto callback = std::bind(&Contribution::OnStartRecurringTips, + auto callback = std::bind(&Contribution::StartAutoContribute, this, _1); - StartRecurringTips(callback); -} - -void Contribution::OnStartRecurringTips(const ledger::Result result) { - StartAutoContribute(ledger_->GetReconcileStamp()); - ResetReconcileStamp(); -} - -bool Contribution::ShouldStartAutoContribute() { - if (!ledger_->GetRewardsMainEnabled()) { - return false; - } - - return ledger_->GetAutoContribute(); + monthly_->Process(callback); } -void Contribution::StartAutoContribute(uint64_t reconcile_stamp) { - if (!ShouldStartAutoContribute()) { - return; - } - - BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "Staring auto contribution"; - auto filter = ledger_->CreateActivityFilter( - "", - ledger::ExcludeFilter::FILTER_ALL_EXCEPT_EXCLUDED, - true, - reconcile_stamp, - false, - ledger_->GetPublisherMinVisits()); - - ledger_->GetActivityInfoList( - 0, - 0, - std::move(filter), - std::bind(&Contribution::PrepareACList, - this, - _1)); -} - -void Contribution::PrepareACList(ledger::PublisherInfoList list) { - ledger::PublisherInfoList normalized_list; - - ledger_->NormalizeContributeWinners(&normalized_list, &list, 0); - - if (normalized_list.empty()) { - return; - } - - ledger::ContributionQueuePublisherList queue_list; - for (const auto &item : normalized_list) { - if (item->percent == 0) { - continue; - } - - auto publisher = ledger::ContributionQueuePublisher::New(); - publisher->publisher_key = item->id; - publisher->amount_percent = item->weight; - queue_list.push_back(std::move(publisher)); +void Contribution::StartAutoContribute(const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Monthly contribution failed"; } - auto queue = ledger::ContributionQueue::New(); - queue->type = ledger::RewardsType::AUTO_CONTRIBUTE; - queue->amount = ledger_->GetContributionAmount(); - queue->partial = true; - queue->publishers = std::move(queue_list); - ledger_->SaveContributionQueue( - std::move(queue), - [](const ledger::Result _){}); - CheckContributionQueue(); + ac_->Process(); } -void Contribution::OnBalanceForReconcile( +void Contribution::OnBalance( const std::string& contribution_queue, const ledger::Result result, ledger::BalancePtr info) { - auto const contribution = + auto const queue = braveledger_bind_util::FromStringToContributionQueue(contribution_queue); if (result != ledger::Result::LEDGER_OK || !info) { queue_in_progress_ = false; BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "We couldn't get balance from the server."; - phase_one_->Complete(ledger::Result::LEDGER_ERROR, - "", - contribution->type); return; } - ProcessReconcile(contribution->Clone(), std::move(info)); + Process(queue->Clone(), std::move(info)); } -void Contribution::InitReconcile(ledger::ContributionQueuePtr info) { +void Contribution::Start(ledger::ContributionQueuePtr info) { const auto info_converted = braveledger_bind_util::FromContributionQueueToString(std::move(info)); ledger_->FetchBalance( - std::bind(&Contribution::OnBalanceForReconcile, + std::bind(&Contribution::OnBalance, this, info_converted, _1, @@ -370,10 +200,23 @@ void Contribution::InitReconcile(ledger::ContributionQueuePtr info) { } void Contribution::OnTimer(uint32_t timer_id) { - phase_two_->OnTimer(timer_id); unverified_->OnTimer(timer_id); uphold_->OnTimer(timer_id); - unblinded_->OnTimer(timer_id); + + for (std::pair const& value : retry_timers_) { + if (value.second != timer_id) { + continue; + } + + std::string contribution_id = value.first; + retry_timers_[contribution_id] = 0u; + + auto callback = std::bind(&Contribution::SetRetryCounter, + this, + _1); + ledger_->GetContributionInfo(contribution_id, callback); + return; + } if (timer_id == last_reconcile_timer_id_) { last_reconcile_timer_id_ = 0; @@ -384,15 +227,6 @@ void Contribution::OnTimer(uint32_t timer_id) { if (timer_id == queue_timer_id_) { ProcessContributionQueue(); } - - // DEPRECATED - for (std::pair const& value : retry_timers_) { - if (value.second == timer_id) { - std::string viewing_id = value.first; - DoRetry(viewing_id); - retry_timers_[viewing_id] = 0u; - } - } } void Contribution::SetReconcileTimer() { @@ -422,46 +256,6 @@ void Contribution::SetTimer(uint32_t* timer_id, uint64_t start_timer_in) { ledger_->SetTimer(start_timer_in, timer_id); } -// DEPRECATED -void Contribution::ReconcileSuccess( - const std::string& viewing_id, - const double amount, - const bool delete_reconcile) { - const auto reconcile = ledger_->GetReconcileById(viewing_id); - - ledger_->SetBalanceReportItem( - braveledger_time_util::GetCurrentMonth(), - braveledger_time_util::GetCurrentYear(), - GetReportTypeFromRewardsType(reconcile.type), - amount); - - ledger::ContributionPublisherList publisher_list; - for (auto& item : reconcile.directions) { - auto publisher = ledger::ContributionPublisher::New(); - publisher->contribution_id = viewing_id; - publisher->publisher_key = item.publisher_key; - publisher->total_amount = (item.amount_percent * amount) / 100; - publisher->contributed_amount = publisher->total_amount; - publisher_list.push_back(std::move(publisher)); - } - - const uint64_t now = static_cast(base::Time::Now().ToDoubleT()); - auto info = ledger::ContributionInfo::New(); - info->contribution_id = viewing_id; - info->amount = amount; - info->type = reconcile.type; - info->step = ledger::ContributionStep::STEP_COMPLETED; - info->retry_count = -1; - info->created_at = now; - info->publishers = std::move(publisher_list); - - ledger_->SaveContributionInfo(std::move(info), [](ledger::Result _){}); - - if (!viewing_id.empty() && delete_reconcile) { - ledger_->RemoveReconcileById(viewing_id); - } -} - void Contribution::ContributionCompleted( const std::string& contribution_id, const ledger::RewardsType type, @@ -475,302 +269,38 @@ void Contribution::ContributionCompleted( amount); } + if (contribution_id.empty()) { + return; + } + + auto save_callback = std::bind(&Contribution::ContributionCompletedSaved, + this, + _1); + ledger_->UpdateContributionInfoStepAndCount( contribution_id, ConvertResultIntoContributionStep(result), -1, - [](const ledger::Result _){}); + save_callback); } -// DEPRECATED -void Contribution::AddRetry( - ledger::ContributionRetry step, - const std::string& viewing_id, - ledger::CurrentReconcileProperties reconcile) { - BLOG(ledger_, ledger::LogLevel::LOG_WARNING) - << "Re-trying contribution for step " - << std::to_string(static_cast(step)) - << " for " << viewing_id; - - if (reconcile.viewing_id.empty()) { - reconcile = ledger_->GetReconcileById(viewing_id); - } - - // Don't retry one-time tip if in phase 1 - if (GetRetryPhase(step) == 1 && - reconcile.type == ledger::RewardsType::ONE_TIME_TIP) { - phase_one_->Complete(ledger::Result::TIP_ERROR, - viewing_id, - reconcile.type); - return; - } - - uint64_t start_timer_in = GetRetryTimer(step, viewing_id, &reconcile); - bool success = ledger_->AddReconcileStep(viewing_id, - reconcile.retry_step, - reconcile.retry_level); - if (!success || start_timer_in == 0) { - phase_one_->Complete(ledger::Result::LEDGER_ERROR, - viewing_id, - reconcile.type); +void Contribution::ContributionCompletedSaved(const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Contribution step and count failed"; return; } - - retry_timers_[viewing_id] = 0u; - SetTimer(&retry_timers_[viewing_id], start_timer_in); -} - -// DEPRECATED -uint64_t Contribution::GetRetryTimer( - ledger::ContributionRetry step, - const std::string& viewing_id, - ledger::CurrentReconcileProperties* reconcile) { - ledger::ContributionRetry old_step = reconcile->retry_step; - - int phase = GetRetryPhase(step); - if (phase > GetRetryPhase(old_step)) { - reconcile->retry_level = 0; - } else { - reconcile->retry_level++; - } - - reconcile->retry_step = step; - - if (phase == 1) { - // TODO(nejczdovc) get size from the list - if (reconcile->retry_level < 5) { - if (ledger::short_retries) { - return phase_one_debug_timers[reconcile->retry_level]; - } else { - return phase_one_timers[reconcile->retry_level]; - } - - } else { - return 0; - } - } - - if (phase == 2) { - // TODO(nejczdovc) get size from the list - if (reconcile->retry_level > 2) { - if (ledger::short_retries) { - return phase_two_debug_timers[2]; - } else { - return phase_two_timers[2]; - } - } else { - if (ledger::short_retries) { - return phase_two_debug_timers[reconcile->retry_level]; - } else { - return phase_two_timers[reconcile->retry_level]; - } - } - } - - return 0; -} - -// DEPRECATED -int Contribution::GetRetryPhase(ledger::ContributionRetry step) { - int phase = 0; - - switch (step) { - case ledger::ContributionRetry::STEP_RECONCILE: - case ledger::ContributionRetry::STEP_CURRENT: - case ledger::ContributionRetry::STEP_PAYLOAD: - case ledger::ContributionRetry::STEP_REGISTER: - case ledger::ContributionRetry::STEP_VIEWING: { - phase = 1; - break; - } - case ledger::ContributionRetry::STEP_PREPARE: - case ledger::ContributionRetry::STEP_VOTE: - case ledger::ContributionRetry::STEP_PROOF: - case ledger::ContributionRetry::STEP_WINNERS: - case ledger::ContributionRetry::STEP_FINAL: { - phase = 2; - break; - } - case ledger::ContributionRetry::STEP_NO: - break; - } - - return phase; -} - -// DEPRECATED -void Contribution::DoRetry(const std::string& viewing_id) { - auto reconcile = ledger_->GetReconcileById(viewing_id); - - switch (reconcile.retry_step) { - case ledger::ContributionRetry::STEP_RECONCILE: { - phase_one_->Start(viewing_id); - break; - } - case ledger::ContributionRetry::STEP_CURRENT: { - phase_one_->CurrentReconcile(viewing_id); - break; - } - case ledger::ContributionRetry::STEP_PAYLOAD: { - phase_one_->ReconcilePayload(viewing_id); - break; - } - case ledger::ContributionRetry::STEP_REGISTER: { - phase_one_->RegisterViewing(viewing_id); - break; - } - case ledger::ContributionRetry::STEP_VIEWING: { - phase_one_->ViewingCredentials(viewing_id); - break; - } - case ledger::ContributionRetry::STEP_PREPARE: { - phase_two_->PrepareBallots(); - break; - } - case ledger::ContributionRetry::STEP_PROOF: { - phase_two_->Proof(); - break; - } - case ledger::ContributionRetry::STEP_VOTE: { - phase_two_->VoteBatch(); - break; - } - case ledger::ContributionRetry::STEP_WINNERS: { - phase_two_->Start(viewing_id); - break; - } - case ledger::ContributionRetry::STEP_FINAL: - case ledger::ContributionRetry::STEP_NO: - break; - } } void Contribution::ContributeUnverifiedPublishers() { unverified_->Contribute(); } -void Contribution::StartPhaseTwo(const std::string& viewing_id) { - phase_two_->Start(viewing_id); -} - void Contribution::OneTimeTip( const std::string& publisher_key, const double amount, ledger::ResultCallback callback) { - if (publisher_key.empty()) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << - "Failed to do tip due to missing publisher key"; - callback(ledger::Result::NOT_FOUND); - return; - } - - const auto server_callback = - std::bind(&Contribution::OneTimeTipServerPublisher, - this, - _1, - publisher_key, - amount, - callback); - - ledger_->GetServerPublisherInfo(publisher_key, server_callback); -} - -void Contribution::SavePendingContribution( - const std::string& publisher_key, - double amount, - const ledger::RewardsType type, - ledger::ResultCallback callback) { - auto contribution = ledger::PendingContribution::New(); - contribution->publisher_key = publisher_key; - contribution->amount = amount; - contribution->type = type; - - ledger::PendingContributionList list; - list.push_back(std::move(contribution)); - - ledger_->SavePendingContribution(std::move(list), callback); -} - -void Contribution::OneTimeTipServerPublisher( - ledger::ServerPublisherInfoPtr server_info, - const std::string& publisher_key, - double amount, - ledger::ResultCallback callback) { - auto status = ledger::PublisherStatus::NOT_VERIFIED; - if (server_info) { - status = server_info->status; - } - - // Save to the pending list if not verified - if (status == ledger::PublisherStatus::NOT_VERIFIED) { - auto save_callback = std::bind(&Contribution::OnSavePendingOneTimeTip, - this, - _1, - callback); - SavePendingContribution( - publisher_key, - amount, - ledger::RewardsType::ONE_TIME_TIP, - save_callback); - return; - } - - ledger::ContributionQueuePublisherList queue_list; - auto publisher = ledger::ContributionQueuePublisher::New(); - publisher->publisher_key = publisher_key; - publisher->amount_percent = 100.0; - queue_list.push_back(std::move(publisher)); - - auto queue = ledger::ContributionQueue::New(); - queue->type = ledger::RewardsType::ONE_TIME_TIP; - queue->amount = amount; - queue->partial = false; - queue->publishers = std::move(queue_list); - - InitReconcile(std::move(queue)); - callback(ledger::Result::LEDGER_OK); -} - -void Contribution::OnSavePendingOneTimeTip( - const ledger::Result result, - ledger::ResultCallback callback) { - ledger_->PendingContributionSaved(result); - callback(result); -} - -bool Contribution::HaveReconcileEnoughFunds( - ledger::ContributionQueuePtr contribution, - double* fee, - const double balance) { - if (contribution->type == ledger::RewardsType::AUTO_CONTRIBUTE) { - if (balance == 0) { - BLOG(ledger_, ledger::LogLevel::LOG_WARNING) << - "You do not have enough funds for auto contribution"; - phase_one_->Complete(ledger::Result::NOT_ENOUGH_FUNDS, - "", - contribution->type); - return false; - } - - if (contribution->amount > balance) { - contribution->amount = balance; - } - - *fee = contribution->amount; - return true; - } - - if (contribution->amount > balance) { - BLOG(ledger_, ledger::LogLevel::LOG_WARNING) << - "You do not have enough funds to do a contribution"; - phase_one_->Complete(ledger::Result::NOT_ENOUGH_FUNDS, - "", - contribution->type); - return false; - } - - *fee = contribution->amount; - return true; + tip_->Process(publisher_key, amount, callback); } void Contribution::OnDeleteContributionQueue(const ledger::Result result) { @@ -790,454 +320,456 @@ void Contribution::DeleteContributionQueue(const uint64_t id) { ledger_->DeleteContributionQueue(id, callback); } -bool Contribution::ProcessReconcileUnblindedTokens( - ledger::BalancePtr info, - ledger::RewardsType type, - double* fee, - ledger::ReconcileDirections directions, - ledger::ReconcileDirections* leftovers) { - if (!fee) { - return false; +void Contribution::CreateNewEntry( + const std::string& wallet_type, + ledger::BalancePtr balance, + ledger::ContributionQueuePtr queue) { + if (!queue) { + BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "Queue is null"; + return; + } + + if (queue->publishers.empty() || !balance || wallet_type.empty()) { + DeleteContributionQueue(queue->id); + return; } - const double balance = + const double wallet_balance = braveledger_wallet::Balance::GetPerWalletBalance( - ledger::kWalletUnBlinded, - info->wallets); - if (balance == 0) { - return false; + wallet_type, + balance->wallets); + if (wallet_balance == 0) { + CreateNewEntry( + GetNextProcessor(wallet_type), + std::move(balance), + std::move(queue)); + return; } const std::string contribution_id = base::GenerateGUID(); - const uint64_t now = static_cast(base::Time::Now().ToDoubleT()); auto contribution = ledger::ContributionInfo::New(); + const uint64_t now = braveledger_time_util::GetCurrentTimeStamp(); contribution->contribution_id = contribution_id; - contribution->amount = *fee; - contribution->type = type; + contribution->amount = queue->amount; + contribution->type = queue->type; contribution->step = ledger::ContributionStep::STEP_START; - contribution->retry_count = -1; + contribution->retry_count = 0; contribution->created_at = now; - contribution->processor = ledger::ContributionProcessor::BRAVE_TOKENS; - - ledger::ReconcileDirections new_directions; - bool full_amount = true; - if (balance < *fee) { - *fee = *fee - balance; - contribution->amount = balance; - full_amount = false; - - if (type == ledger::RewardsType::RECURRING_TIP || - type == ledger::RewardsType::ONE_TIME_TIP) { - AdjustTipsAmounts( - directions, - &new_directions, - leftovers, - balance); + contribution->processor = GetProcessor(wallet_type); + + ledger::ContributionQueuePublisherList queue_publishers; + for (auto& item : queue->publishers) { + queue_publishers.push_back(item->Clone()); + } + + ledger::ContributionQueuePublisherList publishers_new; + ledger::ContributionQueuePublisherList publishers_left; + if (wallet_balance < queue->amount) { + contribution->amount = wallet_balance; + queue->amount = queue->amount - wallet_balance; + + if (queue->type == ledger::RewardsType::RECURRING_TIP || + queue->type == ledger::RewardsType::ONE_TIME_TIP) { + AdjustPublisherListAmounts( + std::move(queue_publishers), + &publishers_new, + &publishers_left, + wallet_balance); + queue->publishers = std::move(publishers_left); } else { - new_directions = directions; + publishers_new = std::move(queue_publishers); } } else { - new_directions = directions; + publishers_new = std::move(queue_publishers); + queue->amount = 0; } ledger::ContributionPublisherList publisher_list; - for (auto& item : new_directions) { + for (const auto& item : publishers_new) { auto publisher = ledger::ContributionPublisher::New(); publisher->contribution_id = contribution_id; - publisher->publisher_key = item.publisher_key; + publisher->publisher_key = item->publisher_key; publisher->total_amount = - (item.amount_percent * contribution->amount) / 100; + (item->amount_percent * contribution->amount) / 100; publisher->contributed_amount = 0; publisher_list.push_back(std::move(publisher)); } contribution->publishers = std::move(publisher_list); - ledger_->SaveContributionInfo( - std::move(contribution), - [](const ledger::Result){}); - unblinded_->Start(contribution_id); - return full_amount; + auto save_callback = std::bind(&Contribution::OnEntrySaved, + this, + _1, + contribution->contribution_id, + wallet_type, + *balance, + braveledger_bind_util::FromContributionQueueToString(queue->Clone())); + + ledger_->SaveContributionInfo( + contribution->Clone(), + save_callback); } -bool Contribution::ProcessReconcileAnonize( - ledger::BalancePtr info, - ledger::RewardsType type, - double* fee, - ledger::ReconcileDirections directions, - ledger::ReconcileDirections* leftovers) { - if (!fee) { - return false; +void Contribution::OnEntrySaved( + const ledger::Result result, + const std::string& contribution_id, + const std::string& wallet_type, + const ledger::Balance& balance, + const std::string& queue_string) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Contribution was not saved correctly"; + return; } - auto reconcile = ledger::CurrentReconcileProperties(); - reconcile.viewing_id = base::GenerateGUID(); - reconcile.fee = *fee; - reconcile.directions = directions; - reconcile.type = type; + auto queue = braveledger_bind_util::FromStringToContributionQueue( + queue_string); - if (ledger_->ReconcileExists(reconcile.viewing_id)) { + if (!queue) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) - << "Unable to reconcile with the same viewing id: " - << reconcile.viewing_id; - return false; + << "Queue was not converted successfully"; + return; } - const double balance = braveledger_wallet::Balance::GetPerWalletBalance( - ledger::kWalletAnonymous, - info->wallets); - if (balance == 0) { - return false; - } + if (wallet_type == ledger::kWalletUnBlinded) { + auto result_callback = std::bind(&Contribution::Result, + this, + _1, + contribution_id); - if (balance >= *fee) { - ledger_->AddReconcile(reconcile.viewing_id, reconcile); - phase_one_->Start(reconcile.viewing_id); - return true; - } + StartUnblinded( + {ledger::CredsBatchType::PROMOTION}, + contribution_id, + result_callback); + } else if (wallet_type == ledger::kWalletAnonymous) { + auto wallet = ledger::ExternalWallet::New(); + wallet->type = wallet_type; - *fee = *fee - balance; - reconcile.fee = balance; - - if (type == ledger::RewardsType::RECURRING_TIP || - type == ledger::RewardsType::ONE_TIME_TIP) { - ledger::ReconcileDirections new_direction; - AdjustTipsAmounts(directions, - &new_direction, - leftovers, - balance); - reconcile.directions = new_direction; - } + auto result_callback = std::bind(&Contribution::Result, + this, + _1, + contribution_id); - ledger_->AddReconcile(reconcile.viewing_id, reconcile); - phase_one_->Start(reconcile.viewing_id); - return false; -} + sku_->AnonUserFunds(contribution_id, std::move(wallet), result_callback); + } else if (wallet_type == ledger::kWalletUphold) { + auto result_callback = std::bind(&Contribution::Result, + this, + _1, + contribution_id); -bool Contribution::ProcessExternalWallet( - ledger::BalancePtr info, - ledger::RewardsType type, - const double fee, - const ledger::ReconcileDirections& directions) { - const double balance = - braveledger_wallet::Balance::GetPerWalletBalance( - ledger::kWalletUphold, - info->wallets); - if (balance == 0) { - return false; + external_wallet_->Process(contribution_id, result_callback); } - const std::string contribution_id = base::GenerateGUID(); + if (queue->amount > 0) { + auto save_callback = std::bind(&Contribution::OnQueueSaved, + this, + _1, + wallet_type, + balance, + braveledger_bind_util::FromContributionQueueToString(queue->Clone())); - 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; - // We should change this to NONE and update it in next phase - // when we add more external processors - contribution->processor = ledger::ContributionProcessor::UPHOLD; + ledger_->SaveContributionQueue(queue->Clone(), save_callback); + } else { + DeleteContributionQueue(queue->id); + } +} - ledger::ContributionPublisherList publisher_list; - for (auto& item : 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)); +void Contribution::OnQueueSaved( + const ledger::Result result, + const std::string& wallet_type, + const ledger::Balance& balance, + const std::string& queue_string) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Queue was not saved successfully"; + return; } - contribution->publishers = std::move(publisher_list); + auto queue = braveledger_bind_util::FromStringToContributionQueue( + queue_string); - if (type == ledger::RewardsType::AUTO_CONTRIBUTE) { - auto reconcile = ledger::CurrentReconcileProperties(); - reconcile.viewing_id = contribution_id; - reconcile.fee = fee; - reconcile.directions = directions; - reconcile.type = contribution->type; - ledger_->AddReconcile(reconcile.viewing_id, reconcile); + if (!queue) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Queue was not converted successfully"; + return; } - auto save_callback = std::bind(&Contribution::OnProcessExternalWalletSaved, - this, - _1, - contribution_id, - info->wallets); - - ledger_->SaveContributionInfo(std::move(contribution), save_callback); - return true; + CreateNewEntry( + GetNextProcessor(wallet_type), + ledger::Balance::New(balance), + std::move(queue)); } -void Contribution::OnProcessExternalWalletSaved( - const ledger::Result result, - const std::string& contribution_id, - base::flat_map wallet_balances) { - auto wallets_callback = std::bind(&Contribution::OnExternalWallets, - this, - contribution_id, - wallet_balances, - _1); +void Contribution::Process( + ledger::ContributionQueuePtr queue, + ledger::BalancePtr balance) { + if (!queue || !balance) { + return; + } - // Check if we have token - ledger_->GetExternalWallets(wallets_callback); -} + if (queue->amount == 0 || queue->publishers.empty()) { + DeleteContributionQueue(queue->id); + return; + } -void Contribution::ProcessReconcile( - ledger::ContributionQueuePtr contribution, - ledger::BalancePtr info) { - double fee = .0; - const auto have_enough_balance = HaveReconcileEnoughFunds( - contribution->Clone(), - &fee, - info->total); + const auto have_enough_balance = HaveEnoughFundsToContribute( + &queue->amount, + queue->partial, + balance->total); if (!have_enough_balance) { - DeleteContributionQueue(contribution->id); + DeleteContributionQueue(queue->id); return; } - if (contribution->amount == 0 || contribution->publishers.empty()) { - DeleteContributionQueue(contribution->id); + if (queue->amount == 0 || queue->publishers.empty()) { + DeleteContributionQueue(queue->id); return; } - const auto directions = FromContributionQueuePublishersToReconcileDirections( - std::move(contribution->publishers)); - - ledger::ReconcileDirections anon_directions = directions; - bool result = ProcessReconcileUnblindedTokens( - info->Clone(), - contribution->type, - &fee, - directions, - &anon_directions); - if (result) { - // contribution was processed in full - DeleteContributionQueue(contribution->id); + CreateNewEntry( + GetNextProcessor(""), + balance->Clone(), + queue->Clone()); +} + +void Contribution::TransferFunds( + const ledger::SKUTransaction& transaction, + const std::string& destination, + ledger::ExternalWalletPtr wallet, + ledger::TransactionCallback callback) { + if (!wallet) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Wallet is null"; + callback(ledger::Result::LEDGER_ERROR, ""); return; } - ledger::ReconcileDirections wallet_directions = anon_directions; - result = ProcessReconcileAnonize( - info->Clone(), - contribution->type, - &fee, - anon_directions, - &wallet_directions); - if (result) { - // contribution was processed in full - DeleteContributionQueue(contribution->id); + if (wallet->type == ledger::kWalletUphold) { + uphold_->TransferFunds( + transaction.amount, + destination, + std::move(wallet), + callback); return; } - result = ProcessExternalWallet( - info->Clone(), - contribution->type, - fee, - wallet_directions); - - if (result) { - // contribution was processed in full - DeleteContributionQueue(contribution->id); + if (wallet->type == ledger::kWalletAnonymous) { + anon_card_->SendTransaction( + transaction.amount, + transaction.order_id, + destination, + callback); + return; } -} -void Contribution::AdjustTipsAmounts( - ledger::ReconcileDirections original_directions, - ledger::ReconcileDirections* primary_directions, - ledger::ReconcileDirections* rest_directions, - double reduce_fee_for) { - if (!primary_directions || !rest_directions) { + if (wallet->type == ledger::kWalletUnBlinded) { + sku_->Merchant(transaction, callback); return; } - for (auto item : original_directions) { - if (reduce_fee_for == 0) { - rest_directions->push_back(item); - continue; - } - - if (item.amount_percent <= reduce_fee_for) { - primary_directions->push_back(item); - reduce_fee_for -= item.amount_percent; - continue; - } - - if (item.amount_percent > reduce_fee_for) { - // primary wallet - const auto original_weight = item.amount_percent; - item.amount_percent = reduce_fee_for; - primary_directions->push_back(item); + NOTREACHED(); + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Wallet type not supported: " << wallet->type; +} - // second wallet - item.amount_percent = original_weight - reduce_fee_for; - rest_directions->push_back(item); +void Contribution::SKUAutoContribution( + const std::string& contribution_id, + ledger::ExternalWalletPtr wallet, + ledger::ResultCallback callback) { + sku_->AutoContribution(contribution_id, std::move(wallet), callback); +} - reduce_fee_for = 0; - } - } +void Contribution::StartUnblinded( + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback) { + unblinded_->Start(types, contribution_id, callback); } -void Contribution::OnExternalWallets( +void Contribution::RetryUnblinded( + const std::vector& types, const std::string& contribution_id, - base::flat_map wallet_balances, - std::map wallets) { - if (wallets.size() == 0) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "No external wallets"; - ledger_->UpdateContributionInfoStepAndCount( - contribution_id, - ledger::ContributionStep::STEP_FAILED, - -1, - [](const ledger::Result _){}); - return; - } + ledger::ResultCallback callback) { - ledger::ExternalWalletPtr wallet = - braveledger_uphold::GetWallet(std::move(wallets)); + auto get_callback = std::bind(&Contribution::RetryUnblindedContribution, + this, + _1, + types, + callback); - ledger_->GetContributionInfo(contribution_id, - std::bind(&Contribution::ExternalWalletContributionInfo, - this, - _1, - wallet_balances, - *wallet)); + ledger_->GetContributionInfo(contribution_id, get_callback); } -void Contribution::ExternalWalletContributionInfo( +void Contribution::RetryUnblindedContribution( ledger::ContributionInfoPtr contribution, - base::flat_map wallet_balances, - const ledger::ExternalWallet& wallet) { - // In this phase we only support one wallet - // so we will just always pick uphold. - // In the future we will allow user to pick which wallet to use via UI - // and then we will extend this function - const double uphold_balance = - braveledger_wallet::Balance::GetPerWalletBalance( - ledger::kWalletUphold, - wallet_balances); - - auto result = ledger::Result::LEDGER_OK; - if (uphold_balance < contribution->amount) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) - << "Not enough funds in uphold wallet"; - result = ledger::Result::NOT_ENOUGH_FUNDS; - } + const std::vector& types, + ledger::ResultCallback callback) { + unblinded_->Retry(types, std::move(contribution), callback); +} - if (wallet.token.empty() || - wallet.status != ledger::WalletStatus::VERIFIED) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) - << "Wallet token is empty/wallet is not verified " << wallet.status; - result = ledger::Result::LEDGER_ERROR; +void Contribution::Result( + const ledger::Result result, + const std::string& contribution_id) { + if (result == ledger::Result::RETRY_SHORT) { + SetRetryTimer(contribution_id, 5); + return; } - if (result != ledger::Result::LEDGER_OK) { - ledger_->ContributionCompleted( - result, - contribution->amount, - contribution->contribution_id, - contribution->type); + if (result == ledger::Result::RETRY) { + SetRetryTimer(contribution_id); return; } - if (contribution->type == ledger::RewardsType::AUTO_CONTRIBUTE) { - auto callback = std::bind(&Contribution::OnUpholdAC, - this, - _1, - _2, - contribution->contribution_id); - uphold_->TransferFunds( - contribution->amount, - ledger_->GetCardIdAddress(), - ledger::ExternalWallet::New(wallet), - callback); + auto get_callback = std::bind(&Contribution::OnResult, + this, + _1, + result); + + ledger_->GetContributionInfo(contribution_id, get_callback); +} + +void Contribution::OnResult( + ledger::ContributionInfoPtr contribution, + const ledger::Result result) { + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution is null"; return; } - for (const auto& publisher : contribution->publishers) { - auto callback = - std::bind(&Contribution::OnExternalWalletServerPublisherInfo, - this, - _1, + if (result == ledger::Result::RETRY_LONG) { + if (contribution->processor == + ledger::ContributionProcessor::BRAVE_TOKENS) { + SetRetryTimer(contribution->contribution_id); + } else { + SetRetryTimer( contribution->contribution_id, - publisher->total_amount, - wallet, - contribution->type); + brave_base::random::Geometric(450)); + } - ledger_->GetServerPublisherInfo(publisher->publisher_key, callback); + return; } + + ledger_->ContributionCompleted( + result, + contribution->amount, + contribution->contribution_id, + contribution->type); } -void Contribution::OnExternalWalletServerPublisherInfo( - ledger::ServerPublisherInfoPtr info, +void Contribution::SetRetryTimer( const std::string& contribution_id, - double amount, - const ledger::ExternalWallet& wallet, - const ledger::RewardsType type) { - if (!info) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Publisher not found"; - ledger_->ContributionCompleted( - ledger::Result::LEDGER_ERROR, - amount, - contribution_id, - type); + const uint64_t start_timer_in) { + if (contribution_id.empty()) { return; } - if (info->status != ledger::PublisherStatus::VERIFIED) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Publisher not verified"; + 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); + } - auto save_callback = std::bind(&Contribution::OnSavePendingContribution, - this, - _1); + BLOG(ledger_, ledger::LogLevel::LOG_INFO) + << "Timer for contribution retry (" + << contribution_id + << ") will start in " + << timer_seconds; + + ledger_->SetTimer(timer_seconds, &retry_timers_[contribution_id]); +} - SavePendingContribution(info->publisher_key, amount, type, save_callback); +void Contribution::SetRetryCounter(ledger::ContributionInfoPtr contribution) { + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution is null"; + return; + } + if (contribution->retry_count == 3) { ledger_->ContributionCompleted( ledger::Result::LEDGER_ERROR, - amount, - contribution_id, - type); + contribution->amount, + contribution->contribution_id, + contribution->type); return; } - auto completed_callback = std::bind(&Contribution::ExternalWalletCompleted, + auto save_callback = std::bind(&Contribution::Retry, this, _1, - amount, - contribution_id, - type); + braveledger_bind_util::FromContributionToString(contribution->Clone())); - uphold_->StartContribution( - contribution_id, - std::move(info), - amount, - ledger::ExternalWallet::New(wallet), - completed_callback); + ledger_->UpdateContributionInfoStepAndCount( + contribution->contribution_id, + contribution->step, + contribution->retry_count + 1, + save_callback); } -void Contribution::ExternalWalletCompleted( +void Contribution::Retry( const ledger::Result result, - const double amount, - const std::string& contribution_id, - const ledger::RewardsType type) { - ledger_->ContributionCompleted(result, amount, contribution_id, type); -} - -void Contribution::OnUpholdAC(ledger::Result result, - bool created, - const std::string& viewing_id) { + const std::string& contribution_string) { if (result != ledger::Result::LEDGER_OK) { - // TODO(nejczdovc): add retries + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Retry count update failed"; + return; + } + + auto contribution = braveledger_bind_util::FromStringToContribution( + contribution_string); + + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution is null"; return; } - phase_one_->Start(viewing_id); + // negative steps are final steps, nothing to retry + if (static_cast(contribution->step) < 0) { + return; + } + + BLOG(ledger_, ledger::LogLevel::LOG_INFO) + << "Retrying contribution (" + << contribution->contribution_id + << ") on step " + << contribution->step; + + auto result_callback = std::bind(&Contribution::Result, + this, + _1, + contribution->contribution_id); + + switch (contribution->processor) { + case ledger::ContributionProcessor::BRAVE_TOKENS: { + RetryUnblindedContribution( + contribution->Clone(), + {ledger::CredsBatchType::PROMOTION}, + result_callback); + return; + } + case ledger::ContributionProcessor::UPHOLD: { + if (contribution->type == ledger::RewardsType::AUTO_CONTRIBUTE) { + sku_->Retry(contribution->Clone(), result_callback); + return; + } + + external_wallet_->Retry(contribution->Clone(), result_callback); + return; + } + case ledger::ContributionProcessor::BRAVE_USER_FUNDS: { + sku_->Retry(contribution->Clone(), result_callback); + return; + } + case ledger::ContributionProcessor::NONE: { + Result(ledger::Result::LEDGER_ERROR, contribution->contribution_id); + return; + } + } } } // namespace braveledger_contribution 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 d0b7c01b53ae..483e294bfeb5 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 @@ -11,72 +11,10 @@ #include #include #include +#include #include "base/gtest_prod_util.h" #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/properties/current_reconcile_properties.h" - -// Contribution has two big phases. PHASE 1 is starting the contribution, -// getting surveyors and transferring BAT from the wallet. -// PHASE 2 uses surveyors from the phase 1 and client generates votes/ballots -// and send them to the server so that server knows to -// which publisher sends the money. - -// For every phase we are doing retries, so that we try our best to process -// contribution successfully. In Phase 1 we notify users about the failure after -// we do the whole interval of retries. In Phase 2 we have shorter interval -// but we will try indefinitely, because we just need to send data to the server -// and we don't need anything from the server. - -// Re-try interval for Phase 1: -// 1 hour -// 6 hours -// 12 hours -// 24 hours -// 48 hours -// stop contribution and report error to the user - -// Re-try interval for Phase 2: -// 1 hour -// 6 hours -// 24 hours -// repeat 24 hours interval - - -// Contribution process - -// PHASE 0 -// 1. InitReconcile -// 2. ProcessReconcile - -// PHASE 1 (reconcile) -// 1. Start (Reconcile) -// 3. ReconcileCallback -// 4. CurrentReconcile -// 5. CurrentReconcileCallback -// 6. ReconcilePayload -// 7. ReconcilePayloadCallback -// 8. RegisterViewing -// 9. RegisterViewingCallback -// 10. ViewingCredentials -// 11. ViewingCredentialsCallback -// 12. Complete - -// PHASE 2 (voting) -// 1. Start (GetReconcileWinners) -// 2. VotePublishers -// 3. VotePublisher -// 4. PrepareBallots -// 5. PrepareBatch -// 6. PrepareBatchCallback -// 7. ProofBatch -// 8. ProofBatchCallback -// 9. SetTimer -// 10. PrepareVoteBatch -// 12. SetTimer -// 12. VoteBatch -// 13. VoteBatchCallback -// 14. SetTimer - we set timer until the whole batch is processed namespace bat_ledger { class LedgerImpl; @@ -88,35 +26,15 @@ class Uphold; namespace braveledger_contribution { -class PhaseOne; -class PhaseTwo; +class ContributionAC; +class ContributionAnonCard; +class ContributionExternalWallet; +class ContributionMonthly; +class ContributionSKU; +class ContributionTip; class Unverified; class Unblinded; -static const uint64_t phase_one_timers[] = { - 1 * 60 * 60, // 1h - 2 * 60 * 60, // 2h - 12 * 60 * 60, // 12h - 24 * 60 * 60, // 24h - 48 * 60 * 60}; // 48h - -static const uint64_t phase_two_timers[] = { - 1 * 60 * 60, // 1h - 6 * 60 * 60, // 6h - 24 * 60 * 60}; // 24h - -static const uint64_t phase_one_debug_timers[] = { - 0.5 * 60, // 30sec - 1 * 60, // 1min - 2 * 60, // 2min - 3 * 60, // 3min - 4 * 60}; // 4min - -static const uint64_t phase_two_debug_timers[] = { - 1 * 60, // 1min - 2 * 60, // 2min - 3 * 60}; // 3min - class Contribution { public: explicit Contribution(bat_ledger::LedgerImpl* ledger); @@ -125,9 +43,9 @@ class Contribution { void Initialize(); - // Initial point for contribution + // Start point for contribution // In this step we get balance from the server - void InitReconcile(ledger::ContributionQueuePtr info); + void Start(ledger::ContributionQueuePtr info); // Called when timer is triggered void OnTimer(uint32_t timer_id); @@ -135,14 +53,6 @@ class Contribution { // Sets new reconcile timer for monthly contribution in 30 days void SetReconcileTimer(); - // 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( @@ -159,193 +69,122 @@ class Contribution { // Can be also called manually void StartMonthlyContribution(); - bool ShouldStartAutoContribute(); - 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(); - // Triggers contribution process for auto contribute table - void StartAutoContribute(uint64_t reconcile_stamp); - void ContributeUnverifiedPublishers(); - void StartPhaseTwo(const std::string& viewing_id); - void OneTimeTip( const std::string& publisher_key, const double amount, ledger::ResultCallback callback); - private: void CheckContributionQueue(); - void ProcessContributionQueue(); - - void OnProcessContributionQueue(ledger::ContributionQueuePtr info); - - // RECURRING TIPS: from the list gets only verified publishers and - // save unverified to the db - ledger::PublisherInfoList GetVerifiedListRecurring( - const ledger::PublisherInfoList& all); - - void OnSavePendingContribution(const ledger::Result result); - - void PrepareACList(ledger::PublisherInfoList list); + void TransferFunds( + const ledger::SKUTransaction& transaction, + const std::string& destination, + ledger::ExternalWalletPtr wallet, + ledger::TransactionCallback callback); - void StartRecurringTips(ledger::ResultCallback callback); - - void PrepareRecurringList( - ledger::PublisherInfoList list, + void SKUAutoContribution( + const std::string& contribution_id, + ledger::ExternalWalletPtr wallet, ledger::ResultCallback callback); - void OnStartRecurringTips(const ledger::Result result); - - void OnBalanceForReconcile( - const std::string& contribution_queue, - const ledger::Result result, - ledger::BalancePtr info); + void StartUnblinded( + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback); - // DEPRECATED - uint64_t GetRetryTimer(ledger::ContributionRetry step, - const std::string& viewing_id, - ledger::CurrentReconcileProperties* reconcile); + void RetryUnblinded( + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback); - // DEPRECATED - int GetRetryPhase(ledger::ContributionRetry step); + private: + void StartAutoContribute(const ledger::Result result); - // DEPRECATED - void DoRetry(const std::string& viewing_id); + void ContributionCompletedSaved(const ledger::Result result); - void CheckStep(const std::string& contribution_id); + void ProcessContributionQueue(); - void OnHasSufficientBalance( - const ledger::PublisherInfoList& publisher_list, - const double balance, - ledger::HasSufficientBalanceToReconcileCallback callback); + void OnProcessContributionQueue(ledger::ContributionQueuePtr info); - static double GetTotalFromRecurringVerified( - const ledger::PublisherInfoList& publisher_list); + void CheckNotCompletedContributions(); - void OnSufficientBalanceWallet( - ledger::Result result, - ledger::BalancePtr properties, - ledger::HasSufficientBalanceToReconcileCallback callback); + void NotCompletedContributions(ledger::ContributionInfoList list); - void SavePendingContribution( - const std::string& publisher_key, - double amount, - const ledger::RewardsType type, - ledger::ResultCallback callback); + void OnBalance( + const std::string& contribution_queue, + const ledger::Result result, + ledger::BalancePtr info); - void OneTimeTipServerPublisher( - ledger::ServerPublisherInfoPtr server_info, - const std::string& publisher_key, - double amount, - ledger::ResultCallback callback); + void CreateNewEntry( + const std::string& wallet_type, + ledger::BalancePtr balance, + ledger::ContributionQueuePtr queue); - void OnSavePendingOneTimeTip( + void OnEntrySaved( const ledger::Result result, - ledger::ResultCallback callback); + const std::string& contribution_id, + const std::string& wallet_type, + const ledger::Balance& balance, + const std::string& queue_string); - bool HaveReconcileEnoughFunds( - ledger::ContributionQueuePtr contribution, - double* fee, - const double balance); - - bool ProcessReconcileUnblindedTokens( - ledger::BalancePtr info, - ledger::RewardsType type, - double* fee, - ledger::ReconcileDirections directions, - ledger::ReconcileDirections* leftovers); - - bool ProcessReconcileAnonize( - ledger::BalancePtr info, - ledger::RewardsType type, - double* fee, - ledger::ReconcileDirections directions, - ledger::ReconcileDirections* leftovers); - - bool ProcessExternalWallet( - ledger::BalancePtr info, - ledger::RewardsType type, - const double fee, - const ledger::ReconcileDirections& directions); - - void OnProcessExternalWalletSaved( + void OnQueueSaved( const ledger::Result result, - const std::string& contribution_id, - base::flat_map wallet_balances); + const std::string& wallet_type, + const ledger::Balance& balance, + const std::string& queue_string); - void ProcessReconcile( - ledger::ContributionQueuePtr contribution, - ledger::BalancePtr info); + void Process( + ledger::ContributionQueuePtr queue, + ledger::BalancePtr balance); void DeleteContributionQueue(const uint64_t id); - void AdjustTipsAmounts( - ledger::ReconcileDirections original_directions, - ledger::ReconcileDirections* primary_directions, - ledger::ReconcileDirections* rest_directions, - double reduce_fee_for); + void OnDeleteContributionQueue(const ledger::Result result); - void OnExternalWallets( - const std::string& contribution_id, - base::flat_map wallet_balances, - std::map wallets); + void RetryUnblindedContribution( + ledger::ContributionInfoPtr contribution, + const std::vector& types, + ledger::ResultCallback callback); + + void Result( + const ledger::Result result, + const std::string& contribution_id); - void ExternalWalletContributionInfo( + void OnResult( ledger::ContributionInfoPtr contribution, - base::flat_map wallet_balances, - const ledger::ExternalWallet& wallet); + const ledger::Result result); - void OnExternalWalletServerPublisherInfo( - ledger::ServerPublisherInfoPtr info, + void SetRetryTimer( const std::string& contribution_id, - double amount, - const ledger::ExternalWallet& wallet, - const ledger::RewardsType type); - - void OnUpholdAC(ledger::Result result, - bool created, - const std::string& viewing_id); + const uint64_t start_timer_in = 0); - void OnDeleteContributionQueue(const ledger::Result result); + void SetRetryCounter(ledger::ContributionInfoPtr contribution); - void ExternalWalletCompleted( + void Retry( const ledger::Result result, - const double amount, - const std::string& contribution_id, - const ledger::RewardsType type); + const std::string& contribution_string); bat_ledger::LedgerImpl* ledger_; // NOT OWNED - std::unique_ptr phase_one_; - std::unique_ptr phase_two_; std::unique_ptr unverified_; std::unique_ptr unblinded_; + std::unique_ptr sku_; std::unique_ptr uphold_; + std::unique_ptr monthly_; + std::unique_ptr ac_; + std::unique_ptr tip_; + std::unique_ptr external_wallet_; + std::unique_ptr anon_card_; uint32_t last_reconcile_timer_id_; std::map retry_timers_; uint32_t queue_timer_id_; bool queue_in_progress_ = false; - - // For testing purposes - friend class ContributionTest; - FRIEND_TEST_ALL_PREFIXES(ContributionTest, GetAmountFromVerifiedAuto); - FRIEND_TEST_ALL_PREFIXES(ContributionTest, GetTotalFromRecurringVerified); }; } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_ac.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_ac.cc new file mode 100644 index 000000000000..5fd2af78037e --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_ac.cc @@ -0,0 +1,99 @@ +/* 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 + +#include "bat/ledger/internal/contribution/contribution_ac.h" +#include "bat/ledger/internal/ledger_impl.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace braveledger_contribution { + +ContributionAC::ContributionAC(bat_ledger::LedgerImpl* ledger, + Contribution* contribution) : + ledger_(ledger), + contribution_(contribution) { + DCHECK(ledger_ && contribution_); +} + +ContributionAC::~ContributionAC() = default; + +void ContributionAC::Process() { + if (!ledger_->GetRewardsMainEnabled() || !ledger_->GetAutoContribute()) { + BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "Auto contribution is off"; + return; + } + + BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "Starting auto contribution"; + + auto filter = ledger_->CreateActivityFilter( + "", + ledger::ExcludeFilter::FILTER_ALL_EXCEPT_EXCLUDED, + true, + ledger_->GetReconcileStamp(), + false, + ledger_->GetPublisherMinVisits()); + + auto get_callback = std::bind(&ContributionAC::PreparePublisherList, + this, + _1); + + ledger_->GetActivityInfoList(0, 0, std::move(filter), get_callback); + contribution_->ResetReconcileStamp(); +} + +void ContributionAC::PreparePublisherList(ledger::PublisherInfoList list) { + ledger::PublisherInfoList normalized_list; + + ledger_->NormalizeContributeWinners(&normalized_list, &list, 0); + + if (normalized_list.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "AC list is empty"; + return; + } + + ledger::ContributionQueuePublisherList queue_list; + ledger::ContributionQueuePublisherPtr publisher; + for (const auto &item : normalized_list) { + if (!item || item->percent == 0) { + continue; + } + + publisher = ledger::ContributionQueuePublisher::New(); + publisher->publisher_key = item->id; + publisher->amount_percent = item->weight; + queue_list.push_back(std::move(publisher)); + } + + if (queue_list.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "AC queue list is empty"; + return; + } + + auto queue = ledger::ContributionQueue::New(); + queue->type = ledger::RewardsType::AUTO_CONTRIBUTE; + queue->amount = ledger_->GetContributionAmount(); + queue->partial = true; + queue->publishers = std::move(queue_list); + + auto save_callback = std::bind(&ContributionAC::QueueSaved, + this, + _1); + + ledger_->SaveContributionQueue(std::move(queue), save_callback); +} + +void ContributionAC::QueueSaved(const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Queue was not saved"; + return; + } + + contribution_->CheckContributionQueue(); +} + +} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_ac.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_ac.h new file mode 100644 index 000000000000..0d919e7ad2ce --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_ac.h @@ -0,0 +1,38 @@ +/* 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_CONTRIBUTION_CONTRIBUTION_AC_H_ +#define BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_AC_H_ + +#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/contribution/contribution.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_contribution { + +class ContributionAC { + public: + explicit ContributionAC( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution); + + ~ContributionAC(); + + void Process(); + + private: + void PreparePublisherList(ledger::PublisherInfoList list); + + void QueueSaved(const ledger::Result result); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + Contribution* contribution_; // NOT OWNED +}; + +} // namespace braveledger_contribution +#endif // BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_AC_H_ 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 new file mode 100644 index 000000000000..9a50f9c6cb45 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.cc @@ -0,0 +1,137 @@ +/* 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 +#include + +#include "base/base64.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "base/values.h" +#include "bat/ledger/internal/contribution/contribution_anon_card.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_sku.h" +#include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/sku/sku_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; +using std::placeholders::_2; +using std::placeholders::_3; + +namespace { + +std::string GetTransactionPayload( + const double amount, + const std::string& order_id, + const std::string& destination, + const std::string& payment_id, + const std::vector& seed) { + base::Value denomination(base::Value::Type::DICTIONARY); + denomination.SetStringKey("amount", base::StringPrintf("%g", amount)); + denomination.SetStringKey("currency", "BAT"); + + base::Value octets(base::Value::Type::DICTIONARY); + octets.SetKey("denomination", std::move(denomination)); + octets.SetStringKey("destination", destination); + + std::string octets_json; + base::JSONWriter::Write(octets, &octets_json); + + const auto sign_headers = braveledger_request_util::GetSignHeaders( + order_id, + octets_json, + "primary", + seed, + true); + + base::Value headers(base::Value::Type::DICTIONARY); + headers.SetStringKey("digest", sign_headers.at("digest")); + headers.SetStringKey("idempotency-key", order_id); + headers.SetStringKey("signature", sign_headers.at("signature")); + + base::Value transaction(base::Value::Type::DICTIONARY); + transaction.SetKey("headers", std::move(headers)); + transaction.SetStringKey("octets", octets_json); + + std::string transaction_json; + base::JSONWriter::Write(transaction, &transaction_json); + std::string transaction_base64; + base::Base64Encode(transaction_json, &transaction_base64); + + base::Value body(base::Value::Type::DICTIONARY); + body.SetStringKey("paymentId", payment_id); + body.SetStringKey("kind", braveledger_sku::ConvertTransactionTypeToString( + ledger::SKUTransactionType::ANONYMOUS_CARD)); + body.SetStringKey("transaction", transaction_base64); + + std::string body_json; + base::JSONWriter::Write(body, &body_json); + + return body_json; +} + +} // namespace + +namespace braveledger_contribution { + +ContributionAnonCard::ContributionAnonCard(bat_ledger::LedgerImpl* ledger, + Contribution* contribution) : + ledger_(ledger), + contribution_(contribution) { + DCHECK(ledger_ && contribution_); +} + +ContributionAnonCard::~ContributionAnonCard() = default; + +void ContributionAnonCard::SendTransaction( + const double amount, + const std::string& order_id, + const std::string& destination, + ledger::TransactionCallback callback) { + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); + const std::string payload = GetTransactionPayload( + amount, + order_id, + destination, + ledger_->GetPaymentId(), + wallet_info.key_info_seed); + + auto url_callback = std::bind(&ContributionAnonCard::OnSendTransaction, + this, + _1, + _2, + _3, + callback); + + const std::string url = braveledger_request_util::GetCreateTransactionURL( + order_id, + ledger::SKUTransactionType::ANONYMOUS_CARD); + + ledger_->LoadURL( + url, + std::vector(), + payload, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void ContributionAnonCard::OnSendTransaction( + const int response_status_code, + const std::string& response, + const std::map& headers, + ledger::TransactionCallback callback) { + ledger_->LogResponse(__func__, response_status_code, response, headers); + if (response_status_code != net::HTTP_CREATED) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Problem sending transaction"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + callback(ledger::Result::LEDGER_OK, ""); +} + +} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.h new file mode 100644 index 000000000000..86a4aa7fa993 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_anon_card.h @@ -0,0 +1,47 @@ +/* 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_CONTRIBUTION_CONTRIBUTION_ANON_FUNDS_H_ +#define BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_ANON_FUNDS_H_ + +#include +#include + +#include "bat/ledger/internal/contribution/contribution.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_contribution { + +class ContributionAnonCard { + public: + explicit ContributionAnonCard( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution); + + ~ContributionAnonCard(); + + void SendTransaction( + const double amount, + const std::string& order_id, + const std::string& destination, + ledger::TransactionCallback callback); + + private: + void OnSendTransaction( + const int response_status_code, + const std::string& response, + const std::map& headers, + ledger::TransactionCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + Contribution* contribution_; // NOT OWNED +}; + +} // namespace braveledger_contribution +#endif // BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_ANON_FUNDS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.cc new file mode 100644 index 000000000000..c616eb07d339 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.cc @@ -0,0 +1,208 @@ +/* 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 + +#include "bat/ledger/internal/contribution/contribution_external_wallet.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/uphold/uphold_util.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace braveledger_contribution { + +ContributionExternalWallet::ContributionExternalWallet( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution, + braveledger_uphold::Uphold* uphold) : + ledger_(ledger), + contribution_(contribution), + uphold_(uphold) { + DCHECK(ledger_ && contribution_ && uphold_); +} + +ContributionExternalWallet::~ContributionExternalWallet() = default; + +void ContributionExternalWallet::Process( + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (contribution_id.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution id is empty"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto wallets_callback = std::bind( + &ContributionExternalWallet::OnExternalWallets, + this, + _1, + contribution_id, + callback); + + // Check if we have token + ledger_->GetExternalWallets(wallets_callback); +} + +void ContributionExternalWallet::OnExternalWallets( + std::map wallets, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (wallets.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "No external wallets"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto wallet = braveledger_uphold::GetWallet(std::move(wallets)); + + if (!wallet) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "External wallet null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto get_callback = std::bind(&ContributionExternalWallet::ContributionInfo, + this, + _1, + *wallet, + callback); + + ledger_->GetContributionInfo(contribution_id, get_callback); +} + +void ContributionExternalWallet::ContributionInfo( + ledger::ContributionInfoPtr contribution, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback) { + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + // In this phase we only support one wallet + // so we will just always pick uphold. + // In the future we will allow user to pick which wallet to use via UI + // and then we will extend this function + if (wallet.token.empty() || + wallet.status != ledger::WalletStatus::VERIFIED) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Wallet token is empty/wallet is not verified. Wallet status: " + << wallet.status; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (contribution->type == ledger::RewardsType::AUTO_CONTRIBUTE) { + contribution_->SKUAutoContribution( + contribution->contribution_id, + ledger::ExternalWallet::New(wallet), + callback); + return; + } + + bool single_publisher = contribution->publishers.size() == 1; + + for (const auto& publisher : contribution->publishers) { + if (publisher->total_amount == publisher->contributed_amount) { + continue; + } + + auto get_callback = + std::bind(&ContributionExternalWallet::OnServerPublisherInfo, + this, + _1, + contribution->contribution_id, + publisher->total_amount, + wallet, + contribution->type, + single_publisher, + callback); + + ledger_->GetServerPublisherInfo(publisher->publisher_key, get_callback); + return; + } + + // we processed all publishers + callback(ledger::Result::LEDGER_OK); +} + +void ContributionExternalWallet::OnSavePendingContribution( + const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Problem saving pending"; + } + ledger_->PendingContributionSaved(result); +} + +void ContributionExternalWallet::OnServerPublisherInfo( + ledger::ServerPublisherInfoPtr info, + const std::string& contribution_id, + const double amount, + const ledger::ExternalWallet& wallet, + const ledger::RewardsType type, + const bool single_publisher, + ledger::ResultCallback callback) { + if (!info) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Publisher not found"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (info->status != ledger::PublisherStatus::VERIFIED) { + BLOG(ledger_, ledger::LogLevel::LOG_INFO) << "Publisher not verified"; + + auto save_callback = + std::bind(&ContributionExternalWallet::OnSavePendingContribution, + this, + _1); + + auto contribution = ledger::PendingContribution::New(); + contribution->publisher_key = info->publisher_key; + contribution->amount = amount; + contribution->type = type; + + ledger::PendingContributionList list; + list.push_back(std::move(contribution)); + + ledger_->SavePendingContribution(std::move(list), save_callback); + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto uphold_callback = std::bind(&ContributionExternalWallet::Completed, + this, + _1, + single_publisher, + callback); + + uphold_->StartContribution( + contribution_id, + std::move(info), + amount, + ledger::ExternalWallet::New(wallet), + uphold_callback); +} + +void ContributionExternalWallet::Completed( + const ledger::Result result, + const bool single_publisher, + ledger::ResultCallback callback) { + if (single_publisher) { + callback(result); + return; + } + + callback(ledger::Result::RETRY); +} + +void ContributionExternalWallet::Retry( + ledger::ContributionInfoPtr contribution, + ledger::ResultCallback callback) { + Process(contribution->contribution_id, callback); +} + +} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.h new file mode 100644 index 000000000000..fa4c304e8413 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.h @@ -0,0 +1,77 @@ +/* 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_CONTRIBUTION_CONTRIBUTION_EXTERNAL_WALLET_H_ +#define BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_EXTERNAL_WALLET_H_ + +#include +#include + +#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/contribution/contribution.h" +#include "bat/ledger/internal/uphold/uphold.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_contribution { + +class ContributionExternalWallet { + public: + explicit ContributionExternalWallet( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution, + braveledger_uphold::Uphold* uphold); + + ~ContributionExternalWallet(); + + void Process( + const std::string& contribution_id, + ledger::ResultCallback callback); + + void Retry( + ledger::ContributionInfoPtr contribution, + ledger::ResultCallback callback); + + private: + void OnExternalWallets( + std::map wallets, + const std::string& contribution_id, + ledger::ResultCallback callback); + + void ContributionInfo( + ledger::ContributionInfoPtr contribution, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback); + + void OnAC( + const ledger::Result result, + const std::string& contribution_id); + + void OnSavePendingContribution( + const ledger::Result result); + + void OnServerPublisherInfo( + ledger::ServerPublisherInfoPtr info, + const std::string& contribution_id, + const double amount, + const ledger::ExternalWallet& wallet, + const ledger::RewardsType type, + const bool single_publisher, + ledger::ResultCallback callback); + + void Completed( + const ledger::Result result, + const bool single_publisher, + ledger::ResultCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + Contribution* contribution_; // NOT OWNED + braveledger_uphold::Uphold* uphold_; // NOT OWNED +}; + +} // namespace braveledger_contribution +#endif // BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_EXTERNAL_WALLET_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly.cc new file mode 100644 index 000000000000..7e81be7f222c --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly.cc @@ -0,0 +1,153 @@ +/* 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 + +#include "bat/ledger/internal/contribution/contribution_monthly.h" +#include "bat/ledger/internal/contribution/contribution_monthly_util.h" +#include "bat/ledger/internal/ledger_impl.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace braveledger_contribution { + +ContributionMonthly::ContributionMonthly(bat_ledger::LedgerImpl* ledger, + Contribution* contribution) : + ledger_(ledger), + contribution_(contribution) { + DCHECK(ledger_ && contribution_); +} + +ContributionMonthly::~ContributionMonthly() = default; + +void ContributionMonthly::Process(ledger::ResultCallback callback) { + auto get_callback = std::bind(&ContributionMonthly::PrepareTipList, + this, + _1, + callback); + + ledger_->GetRecurringTips(get_callback); +} + +void ContributionMonthly::PrepareTipList( + ledger::PublisherInfoList list, + ledger::ResultCallback callback) { + ledger::PublisherInfoList verified_list; + GetVerifiedTipList(list, &verified_list); + + ledger::ContributionQueuePtr queue; + ledger::ContributionQueuePublisherPtr publisher; + for (const auto &item : verified_list) { + ledger::ContributionQueuePublisherList queue_list; + publisher = ledger::ContributionQueuePublisher::New(); + publisher->publisher_key = item->id; + publisher->amount_percent = 100.0; + queue_list.push_back(std::move(publisher)); + + queue = ledger::ContributionQueue::New(); + queue->type = ledger::RewardsType::RECURRING_TIP; + queue->amount = item->weight; + queue->partial = false; + queue->publishers = std::move(queue_list); + + ledger_->SaveContributionQueue( + std::move(queue), + [](const ledger::Result _){}); + } + + // TODO(https://github.com/brave/brave-browser/issues/8804): + // we should change this logic and do batch insert with callback + contribution_->CheckContributionQueue(); + callback(ledger::Result::LEDGER_OK); +} + +void ContributionMonthly::GetVerifiedTipList( + const ledger::PublisherInfoList& list, + ledger::PublisherInfoList* verified_list) { + DCHECK(verified_list); + ledger::PendingContributionList non_verified; + + for (const auto& publisher : list) { + if (!publisher || publisher->id.empty() || publisher->weight == 0.0) { + continue; + } + + if (publisher->status != ledger::PublisherStatus::NOT_VERIFIED) { + verified_list->push_back(publisher->Clone()); + continue; + } + + auto contribution = ledger::PendingContribution::New(); + contribution->amount = publisher->weight; + contribution->publisher_key = publisher->id; + contribution->viewing_id = ""; + contribution->type = ledger::RewardsType::RECURRING_TIP; + + non_verified.push_back(std::move(contribution)); + } + + if (!non_verified.empty()) { + auto save_callback = std::bind( + &ContributionMonthly::OnSavePendingContribution, + this, + _1); + ledger_->SavePendingContribution(std::move(non_verified), save_callback); + } +} + +void ContributionMonthly::OnSavePendingContribution( + const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Problem saving pending"; + } + + ledger_->PendingContributionSaved(result); +} + +void ContributionMonthly::HasSufficientBalance( + ledger::HasSufficientBalanceToReconcileCallback callback) { + auto fetch_callback = + std::bind(&ContributionMonthly::OnSufficientBalanceWallet, + this, + _1, + _2, + callback); + + ledger_->FetchBalance(fetch_callback); +} + +void ContributionMonthly::OnSufficientBalanceWallet( + const ledger::Result result, + ledger::BalancePtr info, + ledger::HasSufficientBalanceToReconcileCallback callback) { + if (result != ledger::Result::LEDGER_OK || !info) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Problem getting balance"; + return; + } + + auto tips_callback = std::bind(&ContributionMonthly::OnHasSufficientBalance, + this, + _1, + info->total, + callback); + + ledger_->GetRecurringTips(tips_callback); +} + +void ContributionMonthly::OnHasSufficientBalance( + const ledger::PublisherInfoList& publisher_list, + const double balance, + ledger::HasSufficientBalanceToReconcileCallback callback) { + if (publisher_list.empty()) { + callback(true); + return; + } + + const auto total = GetTotalFromVerifiedTips(publisher_list); + callback(balance >= total); +} + +} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly.h new file mode 100644 index 000000000000..9563b5eb0739 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly.h @@ -0,0 +1,57 @@ +/* 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_CONTRIBUTION_CONTRIBUTION_MONTHLY_H_ +#define BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_MONTHLY_H_ + +#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/contribution/contribution.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_contribution { + +class ContributionMonthly { + public: + explicit ContributionMonthly( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution); + + ~ContributionMonthly(); + + void Process(ledger::ResultCallback callback); + + void HasSufficientBalance( + ledger::HasSufficientBalanceToReconcileCallback callback); + + private: + void PrepareTipList( + ledger::PublisherInfoList list, + ledger::ResultCallback callback); + + void GetVerifiedTipList( + const ledger::PublisherInfoList& list, + ledger::PublisherInfoList* verified_list); + + void OnSavePendingContribution(const ledger::Result result); + + void OnSufficientBalanceWallet( + const ledger::Result result, + ledger::BalancePtr info, + ledger::HasSufficientBalanceToReconcileCallback callback); + + void OnHasSufficientBalance( + const ledger::PublisherInfoList& publisher_list, + const double balance, + ledger::HasSufficientBalanceToReconcileCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + Contribution* contribution_; // NOT OWNED +}; + +} // namespace braveledger_contribution +#endif // BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_MONTHLY_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util.cc new file mode 100644 index 000000000000..2146294a62b9 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util.cc @@ -0,0 +1,26 @@ +/* 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/contribution/contribution_monthly_util.h" + +namespace braveledger_contribution { + +double GetTotalFromVerifiedTips( + const ledger::PublisherInfoList& publisher_list) { + double total_amount = 0.0; + for (const auto& publisher : publisher_list) { + if (!publisher || publisher->id.empty()) { + continue; + } + + if (publisher->status == ledger::PublisherStatus::VERIFIED) { + total_amount += publisher->weight; + } + } + + return total_amount; +} + +} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util.h new file mode 100644 index 000000000000..e77a430b3021 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util.h @@ -0,0 +1,19 @@ +/* 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_CONTRIBUTION_CONTRIBUTION_MONTHLY_UTIL_H_ +#define BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_MONTHLY_UTIL_H_ + +#include "base/values.h" +#include "bat/ledger/mojom_structs.h" + +namespace braveledger_contribution { + +double GetTotalFromVerifiedTips( + const ledger::PublisherInfoList& publisher_list); + +} // namespace braveledger_contribution + +#endif // BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_MONTHLY_UTIL_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util_unittest.cc similarity index 69% rename from vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc rename to vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util_unittest.cc index d1c8d4179cb9..a59f75bb532c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_monthly_util_unittest.cc @@ -1,4 +1,4 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. +/* Copyright (c) 2020 The Brave Authors. All rights reserved. * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -7,17 +7,15 @@ #include #include -#include "bat/ledger/internal/contribution/contribution.h" -#include "bat/ledger/internal/logging.h" -#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/contribution/contribution_monthly_util.h" #include "bat/ledger/ledger.h" #include "testing/gtest/include/gtest/gtest.h" -// npm run test -- brave_unit_tests --filter=ContributionTest.* +// npm run test -- brave_unit_tests --filter=ContributionMonthlyUtilTest.* namespace braveledger_contribution { -class ContributionTest : public testing::Test { +class ContributionMonthlyUtilTest : public testing::Test { protected: void GetPublishersForRecurring( ledger::PublisherInfoList* publisher_info_list, @@ -38,35 +36,30 @@ class ContributionTest : public testing::Test { } }; -TEST_F(ContributionTest, GetTotalFromRecurringVerified) { +TEST_F(ContributionMonthlyUtilTest, GetTotalFromVerifiedTips) { ledger::PublisherInfoList publisher_info_list; GetPublishersForRecurring(&publisher_info_list, 5, {1, 5, 10}, 2); - double amount = - Contribution::GetTotalFromRecurringVerified(publisher_info_list); + double amount = GetTotalFromVerifiedTips(publisher_info_list); EXPECT_EQ(amount, 6); publisher_info_list.clear(); GetPublishersForRecurring(&publisher_info_list, 7, {1, 5, 10}, 5); - amount = - Contribution::GetTotalFromRecurringVerified(publisher_info_list); + amount = GetTotalFromVerifiedTips(publisher_info_list); EXPECT_EQ(amount, 22); publisher_info_list.clear(); GetPublishersForRecurring(&publisher_info_list, 10, {5, 10, 20}, 7); - amount = - Contribution::GetTotalFromRecurringVerified(publisher_info_list); + amount = GetTotalFromVerifiedTips(publisher_info_list); EXPECT_EQ(amount, 75); publisher_info_list.clear(); GetPublishersForRecurring(&publisher_info_list, 10, {10, 20, 50}, 9); - amount = - Contribution::GetTotalFromRecurringVerified(publisher_info_list); + amount = GetTotalFromVerifiedTips(publisher_info_list); EXPECT_EQ(amount, 240); publisher_info_list.clear(); GetPublishersForRecurring(&publisher_info_list, 5, {1, 5, 10, 20, 50}, 5); - amount = - Contribution::GetTotalFromRecurringVerified(publisher_info_list); + amount = GetTotalFromVerifiedTips(publisher_info_list); EXPECT_EQ(amount, 86); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_sku.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_sku.cc new file mode 100644 index 000000000000..91d7ee78b63d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_sku.cc @@ -0,0 +1,568 @@ +/* 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 +#include + +#include "bat/ledger/global_constants.h" +#include "bat/ledger/internal/common/bind_util.h" +#include "bat/ledger/internal/contribution/contribution_sku.h" +#include "bat/ledger/internal/contribution/contribution_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/sku/sku_brave.h" +#include "bat/ledger/internal/static_values.h" +#include "bat/ledger/internal/uphold/uphold_util.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace { + +const char kACSKUDev[] = "AgEJYnJhdmUuY29tAiNicmF2ZSB1c2VyLXdhbGxldC12b3RlIHNrdSB0b2tlbiB2MQACFHNrdT11c2VyLXdhbGxldC12b3RlAAIKcHJpY2U9MC4yNQACDGN1cnJlbmN5PUJBVAACDGRlc2NyaXB0aW9uPQACGmNyZWRlbnRpYWxfdHlwZT1zaW5nbGUtdXNlAAAGINiB9dUmpqLyeSEdZ23E4dPXwIBOUNJCFN9d5toIME2M"; //NOLINT +const char kACSKUStaging[] = "AgEJYnJhdmUuY29tAiNicmF2ZSB1c2VyLXdhbGxldC12b3RlIHNrdSB0b2tlbiB2MQACFHNrdT11c2VyLXdhbGxldC12b3RlAAIKcHJpY2U9MC4yNQACDGN1cnJlbmN5PUJBVAACDGRlc2NyaXB0aW9uPQACGmNyZWRlbnRpYWxfdHlwZT1zaW5nbGUtdXNlAAAGIOH4Li+rduCtFOfV8Lfa2o8h4SQjN5CuIwxmeQFjOk4W"; //NOLINT +const char kACSKUProduction[] = "AgEJYnJhdmUuY29tAiNicmF2ZSB1c2VyLXdhbGxldC12b3RlIHNrdSB0b2tlbiB2MQACFHNrdT11c2VyLXdhbGxldC12b3RlAAIKcHJpY2U9MC4yNQACDGN1cnJlbmN5PUJBVAACDGRlc2NyaXB0aW9uPQACGmNyZWRlbnRpYWxfdHlwZT1zaW5nbGUtdXNlAAAGIOaNAUCBMKm0IaLqxefhvxOtAKB0OfoiPn0NPVfI602J"; //NOLINT + +const char kUserFundsSKUDev[] = "AgEJYnJhdmUuY29tAiFicmF2ZSBhbm9uLWNhcmQtdm90ZSBza3UgdG9rZW4gdjEAAhJza3U9YW5vbi1jYXJkLXZvdGUAAgpwcmljZT0wLjI1AAIMY3VycmVuY3k9QkFUAAIMZGVzY3JpcHRpb249AAIaY3JlZGVudGlhbF90eXBlPXNpbmdsZS11c2UAAAYgPpv+Al9jRgVCaR49/AoRrsjQqXGqkwaNfqVka00SJxQ="; //NOLINT +const char kUserFundsSKUStaging[] = "AgEJYnJhdmUuY29tAiFicmF2ZSBhbm9uLWNhcmQtdm90ZSBza3UgdG9rZW4gdjEAAhJza3U9YW5vbi1jYXJkLXZvdGUAAgpwcmljZT0wLjI1AAIMY3VycmVuY3k9QkFUAAIMZGVzY3JpcHRpb249AAIaY3JlZGVudGlhbF90eXBlPXNpbmdsZS11c2UAAAYgPV/WYY5pXhodMPvsilnrLzNH6MA8nFXwyg0qSWX477M="; //NOLINT +const char kUserFundsSKUProduction[] = "AgEJYnJhdmUuY29tAiFicmF2ZSBhbm9uLWNhcmQtdm90ZSBza3UgdG9rZW4gdjEAAhJza3U9YW5vbi1jYXJkLXZvdGUAAgpwcmljZT0wLjI1AAIMY3VycmVuY3k9QkFUAAIMZGVzY3JpcHRpb249AAIaY3JlZGVudGlhbF90eXBlPXNpbmdsZS11c2UAAAYgrMZm85YYwnmjPXcegy5pBM5C+ZLfrySZfYiSe13yp8o="; //NOLINT + +std::string GetACSKU() { + if (ledger::_environment == ledger::Environment::PRODUCTION) { + return kACSKUProduction; + } + + if (ledger::_environment == ledger::Environment::STAGING) { + return kACSKUStaging; + } + + if (ledger::_environment == ledger::Environment::DEVELOPMENT) { + return kACSKUDev; + } + + NOTREACHED(); + return kACSKUDev; +} + +std::string GetUserFundsSKU() { + if (ledger::_environment == ledger::Environment::PRODUCTION) { + return kUserFundsSKUProduction; + } + + if (ledger::_environment == ledger::Environment::STAGING) { + return kUserFundsSKUStaging; + } + + if (ledger::_environment == ledger::Environment::DEVELOPMENT) { + return kUserFundsSKUDev; + } + + NOTREACHED(); + return kUserFundsSKUDev; +} + +void GetCredentialTrigger( + ledger::SKUOrderPtr order, + braveledger_credentials::CredentialsTrigger* trigger) { + DCHECK(trigger); + + if (!order || order->items.size() != 1) { + return; + } + + std::vector data; + data.push_back(order->items[0]->order_item_id); + data.push_back(std::to_string(static_cast(order->items[0]->type))); + + trigger->id = order->order_id; + trigger->size = order->items[0]->quantity; + trigger->type = ledger::CredsBatchType::SKU; + trigger->data = data; +} + +} // namespace + +namespace braveledger_contribution { + +ContributionSKU::ContributionSKU( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution): + ledger_(ledger), + contribution_(contribution) { + DCHECK(ledger_); + credentials_ = braveledger_credentials::CredentialsFactory::Create( + ledger_, + ledger::CredsBatchType::SKU); + DCHECK(credentials_); + sku_ = braveledger_sku::SKUFactory::Create( + ledger_, + braveledger_sku::SKUType::kBrave); + DCHECK(sku_); +} + +ContributionSKU::~ContributionSKU() = default; + +void ContributionSKU::AutoContribution( + const std::string& contribution_id, + ledger::ExternalWalletPtr wallet, + ledger::ResultCallback callback) { + if (!wallet) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Wallet is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + ledger::SKUOrderItem item; + item.sku = GetACSKU(); + + Start( + contribution_id, + item, + std::move(wallet), + callback); +} + +void ContributionSKU::AnonUserFunds( + const std::string& contribution_id, + ledger::ExternalWalletPtr wallet, + ledger::ResultCallback callback) { + if (!wallet) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Wallet is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + ledger::SKUOrderItem item; + item.sku = GetUserFundsSKU(); + + Start( + contribution_id, + item, + std::move(wallet), + callback); +} + +void ContributionSKU::Start( + const std::string& contribution_id, + const ledger::SKUOrderItem& item, + ledger::ExternalWalletPtr wallet, + ledger::ResultCallback callback) { + if (!wallet) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Wallet is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto get_callback = std::bind(&ContributionSKU::GetContributionInfo, + this, + _1, + item, + *wallet, + callback); + + ledger_->GetContributionInfo(contribution_id, get_callback); +} + +void ContributionSKU::GetContributionInfo( + ledger::ContributionInfoPtr contribution, + const ledger::SKUOrderItem& item, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback) { + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution not found"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + ledger::ResultCallback complete_callback = std::bind( + &ContributionSKU::Completed, + this, + _1, + contribution->contribution_id, + contribution->type, + callback); + + auto process_callback = std::bind(&ContributionSKU::GetOrder, + this, + _1, + _2, + contribution->contribution_id, + complete_callback); + + ledger::SKUOrderItem new_item = item; + new_item.quantity = GetVotesFromAmount(contribution->amount); + new_item.type = ledger::SKUOrderItemType::SINGLE_USE; + new_item.price = braveledger_ledger::_vote_price; + + std::vector items; + items.push_back(new_item); + + sku_->Process( + items, + ledger::ExternalWallet::New(wallet), + process_callback, + contribution->contribution_id); +} + +void ContributionSKU::GetOrder( + const ledger::Result result, + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "SKU was not processed"; + callback(result); + return; + } + + auto get_callback = std::bind(&ContributionSKU::OnGetOrder, + this, + _1, + contribution_id, + callback); + ledger_->GetSKUOrder(order_id, get_callback); +} + +void ContributionSKU::OnGetOrder( + ledger::SKUOrderPtr order, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order was not found"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto save_callback = std::bind(&ContributionSKU::TransactionStepSaved, + this, + _1, + braveledger_bind_util::FromSKUOrderToString(std::move(order)), + callback); + + ledger_->UpdateContributionInfoStep( + contribution_id, + ledger::ContributionStep::STEP_EXTERNAL_TRANSACTION, + save_callback); +} + +void ContributionSKU::TransactionStepSaved( + const ledger::Result result, + const std::string& order_string, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "External transaction step was not saved"; + callback(result); + return; + } + + auto order = braveledger_bind_util::FromStringToSKUOrder(order_string); + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order is corrupted"; + callback(ledger::Result::RETRY); + return; + } + + DCHECK_EQ(order->items.size(), 1ul); + braveledger_credentials::CredentialsTrigger trigger; + GetCredentialTrigger(order->Clone(), &trigger); + + credentials_->Start(trigger, callback); +} + +void ContributionSKU::Completed( + const ledger::Result result, + const std::string& contribution_id, + const ledger::RewardsType type, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order not completed"; + callback(result); + return; + } + + auto save_callback = std::bind(&ContributionSKU::CredsStepSaved, + this, + _1, + contribution_id, + callback); + + ledger_->UpdateContributionInfoStep( + contribution_id, + ledger::ContributionStep::STEP_CREDS, + save_callback); +} + +void ContributionSKU::CredsStepSaved( + const ledger::Result result, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Creds step not saved"; + callback(result); + return; + } + + contribution_->StartUnblinded( + {ledger::CredsBatchType::SKU}, + contribution_id, + callback); +} + +void ContributionSKU::Merchant( + const ledger::SKUTransaction& transaction, + ledger::TransactionCallback callback) { + auto get_callback = std::bind(&ContributionSKU::GetUnblindedTokens, + this, + _1, + transaction, + callback); + + ledger_->GetUnblindedTokensByBatchTypes( + {ledger::CredsBatchType::PROMOTION}, + get_callback); +} + +void ContributionSKU::GetUnblindedTokens( + ledger::UnblindedTokenList list, + const ledger::SKUTransaction& transaction, + ledger::TransactionCallback callback) { + if (list.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "List is empty"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + std::vector token_list; + double current_amount = 0.0; + for (auto& item : list) { + if (current_amount >= transaction.amount) { + break; + } + + current_amount += item->value; + token_list.push_back(*item); + } + + if (current_amount < transaction.amount) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Not enough funds"; + callback(ledger::Result::NOT_ENOUGH_FUNDS, ""); + return; + } + + braveledger_credentials::CredentialsRedeem redeem; + redeem.type = ledger::RewardsType::PAYMENT; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = token_list; + redeem.order_id = transaction.order_id; + + auto get_callback = std::bind(&ContributionSKU::GerOrderMerchant, + this, + _1, + redeem, + callback); + + ledger_->GetSKUOrder(transaction.order_id, get_callback); +} + +void ContributionSKU::GerOrderMerchant( + ledger::SKUOrderPtr order, + const braveledger_credentials::CredentialsRedeem& redeem, + ledger::TransactionCallback callback) { + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order was not found"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + braveledger_credentials::CredentialsRedeem new_redeem = redeem; + new_redeem.publisher_key = order->location; + + auto creds_callback = std::bind(&ContributionSKU::OnRedeemTokens, + this, + _1, + callback); + + credentials_->RedeemTokens(new_redeem, creds_callback); +} + +void ContributionSKU::OnRedeemTokens( + const ledger::Result result, + ledger::TransactionCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Problem redeeming tokens"; + callback(result, ""); + return; + } + + callback(result, ""); +} + +void ContributionSKU::Retry( + const ledger::ContributionInfoPtr contribution, + ledger::ResultCallback callback) { + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution was not found"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto get_callback = std::bind(&ContributionSKU::OnOrder, + this, + _1, + braveledger_bind_util::FromContributionToString(contribution->Clone()), + callback); + + ledger_->GetSKUOrderByContributionId( + contribution->contribution_id, + get_callback); +} + +void ContributionSKU::OnOrder( + ledger::SKUOrderPtr order, + const std::string& contribution_string, + ledger::ResultCallback callback) { + auto contribution = braveledger_bind_util::FromStringToContribution( + contribution_string); + + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + switch (contribution->step) { + case ledger::ContributionStep::STEP_START: { + RetryStartStep( + std::move(contribution), + std::move(order), + callback); + return; + } + case ledger::ContributionStep::STEP_EXTERNAL_TRANSACTION: { + RetryExternalTransactionStep( + std::move(contribution), + std::move(order), + callback); + return; + } + case ledger::ContributionStep::STEP_PREPARE: + case ledger::ContributionStep::STEP_RESERVE: + case ledger::ContributionStep::STEP_CREDS: { + contribution_->RetryUnblinded( + {ledger::CredsBatchType::SKU}, + contribution->contribution_id, + callback); + return; + } + case ledger::ContributionStep::STEP_AC_TABLE_EMPTY: + case ledger::ContributionStep::STEP_NOT_ENOUGH_FUNDS: + case ledger::ContributionStep::STEP_FAILED: + case ledger::ContributionStep::STEP_COMPLETED: + case ledger::ContributionStep::STEP_NO: { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Step not correct " + << contribution->step; + NOTREACHED(); + return; + } + } +} + +void ContributionSKU::RetryStartStep( + ledger::ContributionInfoPtr contribution, + ledger::SKUOrderPtr order, + ledger::ResultCallback callback) { + if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (contribution->processor == ledger::ContributionProcessor::UPHOLD && + contribution->type == ledger::RewardsType::AUTO_CONTRIBUTE) { + std::string order_id; + if (order) { + order_id = order->order_id; + } + + auto get_callback = std::bind( + &ContributionSKU::RetryStartStepExternalWallet, + this, + _1, + _2, + order_id, + contribution->contribution_id, + callback); + ledger_->GetExternalWallet(ledger::kWalletUphold, get_callback); + return; + } + + auto wallet = ledger::ExternalWallet::New(); + wallet->type = ledger::kWalletAnonymous; + + if (!order) { + AnonUserFunds(contribution->contribution_id, std::move(wallet), callback); + return; + } + + auto retry_callback = std::bind(&ContributionSKU::GetOrder, + this, + _1, + _2, + contribution->contribution_id, + callback); + + sku_->Retry(order->order_id, std::move(wallet), retry_callback); +} + +void ContributionSKU::RetryStartStepExternalWallet( + const ledger::Result result, + ledger::ExternalWalletPtr wallet, + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (!wallet || result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "External wallet is missing"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (order_id.empty()) { + AutoContribution(contribution_id, std::move(wallet), callback); + return; + } + + auto retry_callback = std::bind(&ContributionSKU::GetOrder, + this, + _1, + _2, + contribution_id, + callback); + + sku_->Retry(order_id, std::move(wallet), retry_callback); +} + +void ContributionSKU::RetryExternalTransactionStep( + ledger::ContributionInfoPtr contribution, + ledger::SKUOrderPtr order, + ledger::ResultCallback callback) { + if (!contribution || !order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution/order is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + braveledger_credentials::CredentialsTrigger trigger; + GetCredentialTrigger(order->Clone(), &trigger); + auto complete_callback = std::bind(&ContributionSKU::Completed, + this, + _1, + contribution->contribution_id, + contribution->type, + callback); + credentials_->Start(trigger, complete_callback); +} + +} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_sku.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_sku.h new file mode 100644 index 000000000000..54428d5ff8a7 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_sku.h @@ -0,0 +1,131 @@ +/* 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_CONTRIBUTION_CONTRIBUTION_SKU_H_ +#define BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_SKU_H_ + +#include +#include + +#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/contribution/contribution.h" +#include "bat/ledger/internal/credentials/credentials_factory.h" +#include "bat/ledger/internal/sku/sku_factory.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_contribution { + +class ContributionSKU { + public: + explicit ContributionSKU( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution); + ~ContributionSKU(); + + void AutoContribution( + const std::string& contribution_id, + ledger::ExternalWalletPtr wallet, + ledger::ResultCallback callback); + + void AnonUserFunds( + const std::string& contribution_id, + ledger::ExternalWalletPtr wallet, + ledger::ResultCallback callback); + + void Merchant( + const ledger::SKUTransaction& transaction, + ledger::TransactionCallback callback); + + void Retry( + const ledger::ContributionInfoPtr contribution, + ledger::ResultCallback callback); + + private: + void Start( + const std::string& contribution_id, + const ledger::SKUOrderItem& item, + ledger::ExternalWalletPtr wallet, + ledger::ResultCallback callback); + + void GetContributionInfo( + ledger::ContributionInfoPtr contribution, + const ledger::SKUOrderItem& item, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback); + + void GetOrder( + const ledger::Result result, + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback); + + void OnGetOrder( + ledger::SKUOrderPtr order, + const std::string& contribution_id, + ledger::ResultCallback callback); + + void TransactionStepSaved( + const ledger::Result result, + const std::string& order_string, + ledger::ResultCallback callback); + + void Completed( + const ledger::Result result, + const std::string& contribution_id, + const ledger::RewardsType type, + ledger::ResultCallback callback); + + void CredsStepSaved( + const ledger::Result result, + const std::string& contribution_id, + ledger::ResultCallback callback); + + void GetUnblindedTokens( + ledger::UnblindedTokenList list, + const ledger::SKUTransaction& transaction, + ledger::TransactionCallback callback); + + void GerOrderMerchant( + ledger::SKUOrderPtr order, + const braveledger_credentials::CredentialsRedeem& redeem, + ledger::TransactionCallback callback); + + void OnRedeemTokens( + const ledger::Result result, + ledger::TransactionCallback callback); + + void OnOrder( + ledger::SKUOrderPtr order, + const std::string& contribution_string, + ledger::ResultCallback callback); + + void RetryStartStep( + ledger::ContributionInfoPtr contribution, + ledger::SKUOrderPtr order, + ledger::ResultCallback callback); + + void RetryStartStepExternalWallet( + const ledger::Result result, + ledger::ExternalWalletPtr wallet, + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback); + + void RetryExternalTransactionStep( + ledger::ContributionInfoPtr contribution, + ledger::SKUOrderPtr order, + ledger::ResultCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + Contribution* contribution_; // NOT OWNED + std::unique_ptr credentials_; + std::unique_ptr sku_; +}; + +} // namespace braveledger_contribution +#endif // BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_SKU_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_tip.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_tip.cc new file mode 100644 index 000000000000..5ca3dd93d149 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_tip.cc @@ -0,0 +1,112 @@ +/* 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 + +#include "bat/ledger/internal/contribution/contribution_tip.h" +#include "bat/ledger/internal/ledger_impl.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace braveledger_contribution { + +ContributionTip::ContributionTip(bat_ledger::LedgerImpl* ledger, + Contribution* contribution) : + ledger_(ledger), + contribution_(contribution) { + DCHECK(ledger_ && contribution_); +} + +ContributionTip::~ContributionTip() = default; + +void ContributionTip::Process( + const std::string& publisher_key, + const double amount, + ledger::ResultCallback callback) { + if (publisher_key.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Failed to do tip due to missing publisher key"; + callback(ledger::Result::NOT_FOUND); + return; + } + + const auto server_callback = std::bind(&ContributionTip::ServerPublisher, + this, + _1, + publisher_key, + amount, + callback); + + ledger_->GetServerPublisherInfo(publisher_key, server_callback); +} + +void ContributionTip::ServerPublisher( + ledger::ServerPublisherInfoPtr server_info, + const std::string& publisher_key, + const double amount, + ledger::ResultCallback callback) { + auto status = ledger::PublisherStatus::NOT_VERIFIED; + if (server_info) { + status = server_info->status; + } + + // Save to the pending list if not verified + if (status == ledger::PublisherStatus::NOT_VERIFIED) { + auto save_callback = std::bind(&ContributionTip::OnSavePending, + this, + _1, + callback); + + SavePending( + publisher_key, + amount, + save_callback); + return; + } + + ledger::ContributionQueuePublisherList queue_list; + auto publisher = ledger::ContributionQueuePublisher::New(); + publisher->publisher_key = publisher_key; + publisher->amount_percent = 100.0; + queue_list.push_back(std::move(publisher)); + + auto queue = ledger::ContributionQueue::New(); + queue->type = ledger::RewardsType::ONE_TIME_TIP; + queue->amount = amount; + queue->partial = false; + queue->publishers = std::move(queue_list); + + contribution_->Start(std::move(queue)); + callback(ledger::Result::LEDGER_OK); +} + +void ContributionTip::SavePending( + const std::string& publisher_key, + const double amount, + ledger::ResultCallback callback) { + auto contribution = ledger::PendingContribution::New(); + contribution->publisher_key = publisher_key; + contribution->amount = amount; + contribution->type = ledger::RewardsType::ONE_TIME_TIP; + + ledger::PendingContributionList list; + list.push_back(std::move(contribution)); + + ledger_->SavePendingContribution(std::move(list), callback); +} + +void ContributionTip::OnSavePending( + const ledger::Result result, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR)<< "Pending tip save failed"; + } + + ledger_->PendingContributionSaved(result); + callback(result); +} + +} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_tip.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_tip.h new file mode 100644 index 000000000000..a60a8d602cb5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_tip.h @@ -0,0 +1,54 @@ +/* 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_CONTRIBUTION_CONTRIBUTION_TIP_H_ +#define BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_TIP_H_ + +#include + +#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/contribution/contribution.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_contribution { + +class ContributionTip { + public: + explicit ContributionTip( + bat_ledger::LedgerImpl* ledger, + Contribution* contribution); + + ~ContributionTip(); + + void Process( + const std::string& publisher_key, + const double amount, + ledger::ResultCallback callback); + + private: + void ServerPublisher( + ledger::ServerPublisherInfoPtr server_info, + const std::string& publisher_key, + const double amount, + ledger::ResultCallback callback); + + void SavePending( + const std::string& publisher_key, + const double amount, + ledger::ResultCallback callback); + + void OnSavePending( + const ledger::Result result, + ledger::ResultCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + Contribution* contribution_; // NOT OWNED +}; + +} // namespace braveledger_contribution +#endif // BRAVELEDGER_CONTRIBUTION_CONTRIBUTION_TIP_H_ 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 946f90e165db..50d79b9f9baa 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 @@ -5,13 +5,13 @@ #include -#include "base/base64.h" #include "base/json/json_writer.h" #include "base/values.h" #include "bat/ledger/internal/bat_util.h" #include "bat/ledger/internal/common/time_util.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/contribution/contribution_unblinded.h" +#include "bat/ledger/internal/contribution/contribution_sku.h" #include "bat/ledger/internal/contribution/contribution_util.h" #include "bat/ledger/internal/request/request_promotion.h" #include "brave_base/random.h" @@ -23,86 +23,18 @@ using std::placeholders::_3; namespace { -std::string ConvertTypeToString(const ledger::RewardsType type) { - switch (static_cast(type)) { - case static_cast(ledger::RewardsType::AUTO_CONTRIBUTE): { - return "auto-contribute"; - } - case static_cast(ledger::RewardsType::ONE_TIME_TIP): { - return "oneoff-tip"; - } - case static_cast(ledger::RewardsType::RECURRING_TIP): { - return "recurring-tip"; - } - default: { - // missing conversion, returning dummy value. - NOTREACHED(); - return "oneoff-tip"; - } - } -} - bool HasTokenExpired(const ledger::UnblindedToken& token) { const auto now = braveledger_time_util::GetCurrentTimeStamp(); return token.expires_at > 0 && token.expires_at < now; } -std::string GenerateTokenPayload( - const std::string& publisher_key, - const ledger::RewardsType type, - const std::vector& list) { - base::Value suggestion(base::Value::Type::DICTIONARY); - suggestion.SetStringKey("type", ConvertTypeToString(type)); - suggestion.SetStringKey("channel", publisher_key); - - std::string suggestion_json; - base::JSONWriter::Write(suggestion, &suggestion_json); - std::string suggestion_encoded; - base::Base64Encode(suggestion_json, &suggestion_encoded); - - base::Value credentials(base::Value::Type::LIST); - for (auto& item : list) { - base::Value token(base::Value::Type::DICTIONARY); - bool success; - if (ledger::is_testing) { - success = braveledger_contribution::GenerateSuggestionMock( - item.token_value, - item.public_key, - suggestion_encoded, - &token); - } else { - success = braveledger_contribution::GenerateSuggestion( - item.token_value, - item.public_key, - suggestion_encoded, - &token); - } - - if (!success) { - continue; - } - - credentials.Append(std::move(token)); - } - - base::Value payload(base::Value::Type::DICTIONARY); - payload.SetStringKey("suggestion", suggestion_encoded); - payload.SetKey("credentials", std::move(credentials)); - - std::string json; - base::JSONWriter::Write(payload, &json); - return json; -} - bool GetStatisticalVotingWinner( double dart, const double amount, const std::vector& list, braveledger_contribution::Winners* winners) { - if (!winners) { - return false; - } + DCHECK(winners); double upper = 0.0; for (auto& item : list) { @@ -132,8 +64,13 @@ void GetStatisticalVotingWinners( const double amount, const ledger::ContributionPublisherList& list, braveledger_contribution::Winners* winners) { + DCHECK(winners); std::vector converted_list; + if (total_votes == 0 || list.empty()) { + return; + } + for (auto& item : list) { ledger::ContributionPublisher new_item; new_item.total_amount = item->total_amount; @@ -149,65 +86,50 @@ void GetStatisticalVotingWinners( } } -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) { + DCHECK(ledger_); + credentials_ = braveledger_credentials::CredentialsFactory::Create( + ledger_, + ledger::CredsBatchType::PROMOTION); + DCHECK(credentials_); } Unblinded::~Unblinded() = default; -void Unblinded::Initialize() { - auto callback = std::bind(&Unblinded::OnGetNotCompletedContributions, - this, - _1); - ledger_->GetIncompleteContributions( - ledger::ContributionProcessor::BRAVE_TOKENS, - callback); -} - -void Unblinded::OnGetNotCompletedContributions( - ledger::ContributionInfoList list) { - if (list.size() == 0) { - return; - } - - if (!list[0]) { +void Unblinded::Start( + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (contribution_id.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution id is empty"; + callback(ledger::Result::LEDGER_ERROR); return; } - DoRetry(std::move(list[0])); -} + auto get_callback = std::bind(&Unblinded::PrepareTokens, + this, + _1, + _2, + types, + callback); -void Unblinded::Start(const std::string& contribution_id) { - GetContributionInfoAndUnblindedTokens( - contribution_id, - std::bind(&Unblinded::PrepareTokens, - this, - _1, - _2)); + GetContributionInfoAndUnblindedTokens(types, contribution_id, get_callback); } void Unblinded::GetContributionInfoAndUnblindedTokens( + const std::vector& types, const std::string& contribution_id, GetContributionInfoAndUnblindedTokensCallback callback) { - ledger_->GetAllUnblindedTokens( - std::bind(&Unblinded::OnUnblindedTokens, - this, - _1, - contribution_id, - callback)); + auto get_callback = std::bind(&Unblinded::OnUnblindedTokens, + this, + _1, + contribution_id, + callback); + ledger_->GetUnblindedTokensByBatchTypes(types, get_callback); } void Unblinded::OnUnblindedTokens( @@ -215,7 +137,8 @@ void Unblinded::OnUnblindedTokens( const std::string& contribution_id, GetContributionInfoAndUnblindedTokensCallback callback) { if (list.empty()) { - ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, nullptr); + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Token list is empty"; + callback(nullptr, {}); return; } @@ -249,20 +172,20 @@ void Unblinded::OnGetContributionInfo( void Unblinded::PrepareTokens( ledger::ContributionInfoPtr contribution, - const std::vector& list) { + const std::vector& list, + const std::vector& types, + ledger::ResultCallback callback) { if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution not found"; + callback(ledger::Result::LEDGER_ERROR); 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){}); + if (list.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Not enough funds"; + callback(ledger::Result::NOT_ENOUGH_FUNDS); + return; + } double current_amount = 0.0; std::vector token_list; @@ -286,19 +209,24 @@ void Unblinded::PrepareTokens( } if (current_amount < contribution->amount) { - ContributionCompleted( - ledger::Result::NOT_ENOUGH_FUNDS, - std::move(contribution)); + callback(ledger::Result::NOT_ENOUGH_FUNDS); + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Not enough funds"; return; } - PreparePublishers(token_list, std::move(contribution)); + // TODO(https://github.com/brave/brave-browser/issues/8887): + // we should reserve this tokens and add step STEP_RESERVE + PreparePublishers(token_list, std::move(contribution), types, callback); } void Unblinded::PreparePublishers( const std::vector& list, - ledger::ContributionInfoPtr contribution) { + ledger::ContributionInfoPtr contribution, + const std::vector& types, + ledger::ResultCallback callback) { if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution not found"; + callback(ledger::Result::LEDGER_ERROR); return; } @@ -307,24 +235,37 @@ void Unblinded::PreparePublishers( PrepareAutoContribution(list, contribution->Clone()); if (publisher_list.empty()) { - ContributionCompleted( - ledger::Result::AC_TABLE_EMPTY, - std::move(contribution)); + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Publisher list empty"; + callback(ledger::Result::AC_TABLE_EMPTY); return; } contribution->publishers = std::move(publisher_list); + auto save_callback = std::bind(&Unblinded::OnPrepareAutoContribution, + this, + _1, + types, + contribution->contribution_id, + callback); + ledger_->SaveContributionInfo( contribution->Clone(), - std::bind(&Unblinded::OnPrepareAutoContribution, - this, - _1, - contribution->contribution_id)); + save_callback); return; } - ProcessTokens(contribution->contribution_id); + auto save_callback = std::bind(&Unblinded::PrepareStepSaved, + this, + _1, + types, + contribution->contribution_id, + callback); + + ledger_->UpdateContributionInfoStep( + contribution->contribution_id, + ledger::ContributionStep::STEP_PREPARE, + save_callback); } ledger::ContributionPublisherList Unblinded::PrepareAutoContribution( @@ -363,40 +304,68 @@ ledger::ContributionPublisherList Unblinded::PrepareAutoContribution( void Unblinded::OnPrepareAutoContribution( const ledger::Result result, - const std::string& contribution_id) { + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback) { if (result != ledger::Result::LEDGER_OK) { - SetTimer(contribution_id); + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution not saved"; + callback(ledger::Result::RETRY); return; } - ProcessTokens(contribution_id); -} + auto save_callback = std::bind(&Unblinded::PrepareStepSaved, + this, + _1, + types, + contribution_id, + callback); -void Unblinded::ProcessTokens(const std::string& contribution_id) { - GetContributionInfoAndUnblindedTokens( + ledger_->UpdateContributionInfoStep( contribution_id, - std::bind(&Unblinded::OnProcessTokens, - this, - _1, - _2)); + ledger::ContributionStep::STEP_PREPARE, + save_callback); +} + +void Unblinded::PrepareStepSaved( + const ledger::Result result, + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Prepare step was not saved"; + callback(ledger::Result::RETRY); + return; + } + + ProcessTokens(types, contribution_id, callback); +} + +void Unblinded::ProcessTokens( + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback) { + // TODO(https://github.com/brave/brave-browser/issues/8887): + // here we should fetch reserved tokens so that in OnProcessTokens + // no additional computing is needed + auto get_callback = std::bind(&Unblinded::OnProcessTokens, + this, + _1, + _2, + callback); + GetContributionInfoAndUnblindedTokens(types, contribution_id, get_callback); } void Unblinded::OnProcessTokens( ledger::ContributionInfoPtr contribution, - const std::vector& list) { - if (!contribution) { + const std::vector& list, + ledger::ResultCallback callback) { + if (!contribution || contribution->publishers.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution not found"; + callback(ledger::Result::LEDGER_ERROR); return; } - const int32_t retry_count = GetRetryCount( - ledger::ContributionStep::STEP_SUGGESTIONS, - contribution->Clone()); - - ledger_->UpdateContributionInfoStepAndCount( - contribution->contribution_id, - ledger::ContributionStep::STEP_SUGGESTIONS, - retry_count, - [](const ledger::Result){}); + bool single_publisher = contribution->publishers.size() == 1; for (auto& publisher : contribution->publishers) { if (publisher->total_amount == publisher->contributed_amount) { @@ -414,199 +383,97 @@ void Unblinded::OnProcessTokens( token_list.push_back(item); } - auto callback = std::bind(&Unblinded::TokenProcessed, + auto redeem_callback = std::bind(&Unblinded::TokenProcessed, this, _1, contribution->contribution_id, - publisher->publisher_key); - - SendTokens( publisher->publisher_key, - contribution->type, - token_list, + single_publisher, callback); - return; - } - ContributionCompleted(ledger::Result::LEDGER_OK, std::move(contribution)); -} + braveledger_credentials::CredentialsRedeem redeem; + redeem.publisher_key = publisher->publisher_key; + redeem.type = contribution->type; + redeem.processor = contribution->processor; + redeem.token_list = token_list; -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); + credentials_->RedeemTokens(redeem, redeem_callback); return; } - SetTimer(contribution_id); + // we processed all publishers + callback(ledger::Result::LEDGER_OK); } -void Unblinded::OnTokenProcessed( +void Unblinded::TokenProcessed( 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; - } - - if (completed) { - ContributionCompleted(ledger::Result::LEDGER_OK, std::move(contribution)); - return; - } - - SetTimer(contribution->contribution_id); -} - -void Unblinded::SendTokens( + const std::string& contribution_id, const std::string& publisher_key, - const ledger::RewardsType type, - const std::vector& list, + const bool single_publisher, 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)); + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Tokens were not processed correctly"; + callback(ledger::Result::RETRY); + return; } - auto url_callback = std::bind(&Unblinded::OnSendTokens, + auto save_callback = std::bind(&Unblinded::ContributionAmountSaved, this, _1, - _2, - _3, - token_id_list, + contribution_id, + single_publisher, callback); - const std::string payload = GenerateTokenPayload( + ledger_->UpdateContributionInfoContributedAmount( + contribution_id, publisher_key, - type, - list); - - const std::string url = - braveledger_request_util::GetReedemSuggestionsUrl(); - - ledger_->LoadURL( - url, - std::vector(), - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - url_callback); + save_callback); } -void Unblinded::OnSendTokens( - const int response_status_code, - const std::string& response, - const std::map& headers, - const std::vector& token_id_list, +void Unblinded::ContributionAmountSaved( + const ledger::Result result, + const std::string& contribution_id, + const bool single_publisher, ledger::ResultCallback callback) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - if (response_status_code != net::HTTP_OK) { - callback(ledger::Result::LEDGER_ERROR); + if (single_publisher) { + callback(result); return; } - ledger_->DeleteUnblindedTokens(token_id_list, [](const ledger::Result _){}); - callback(ledger::Result::LEDGER_OK); + callback(ledger::Result::RETRY_LONG); } -void Unblinded::ContributionCompleted( - const ledger::Result result, - ledger::ContributionInfoPtr contribution) { +void Unblinded::Retry( + const std::vector& types, + ledger::ContributionInfoPtr contribution, + ledger::ResultCallback callback) { if (!contribution) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution is null"; + callback(ledger::Result::LEDGER_ERROR); return; } - ledger_->ContributionCompleted( - result, - 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]); -} + const bool is_not_tokens = + contribution->processor != ledger::ContributionProcessor::BRAVE_TOKENS; -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; - } - } -} + const bool is_not_uphold_ac = + contribution->processor == ledger::ContributionProcessor::UPHOLD && + contribution->type != ledger::RewardsType::AUTO_CONTRIBUTE; -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) { + if (is_not_tokens && is_not_uphold_ac) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Retry is not for this func"; + callback(ledger::Result::LEDGER_ERROR); return; } if (contribution->step == ledger::ContributionStep::STEP_START) { - Start(contribution->contribution_id); + Start(types, contribution->contribution_id, callback); return; } - if (contribution->step == ledger::ContributionStep::STEP_SUGGESTIONS) { - ProcessTokens(contribution->contribution_id); + if (contribution->step == ledger::ContributionStep::STEP_PREPARE) { + ProcessTokens(types, contribution->contribution_id, callback); return; } 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 0b8711ddc158..dbbe0757fe33 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 @@ -9,11 +9,12 @@ #include #include +#include #include #include +#include "bat/ledger/internal/credentials/credentials_factory.h" #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" namespace bat_ledger { class LedgerImpl; @@ -32,17 +33,19 @@ class Unblinded { explicit Unblinded(bat_ledger::LedgerImpl* ledger); ~Unblinded(); - void Initialize(); - - void Start(const std::string& contribution_id); + void Start( + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback); - void OnTimer(uint32_t timer_id); + void Retry( + const std::vector& types, + ledger::ContributionInfoPtr contribution, + ledger::ResultCallback callback); private: - void OnGetNotCompletedContributions( - ledger::ContributionInfoList list); - void GetContributionInfoAndUnblindedTokens( + const std::vector& types, const std::string& contribution_id, GetContributionInfoAndUnblindedTokensCallback callback); @@ -58,11 +61,15 @@ class Unblinded { void PrepareTokens( ledger::ContributionInfoPtr contribution, - const std::vector& list); + const std::vector& list, + const std::vector& types, + ledger::ResultCallback callback); void PreparePublishers( const std::vector& list, - ledger::ContributionInfoPtr contribution); + ledger::ContributionInfoPtr contribution, + const std::vector& types, + ledger::ResultCallback callback); ledger::ContributionPublisherList PrepareAutoContribution( const std::vector& list, @@ -70,52 +77,41 @@ class Unblinded { void OnPrepareAutoContribution( const ledger::Result result, - const std::string& contribution_id); + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback); - void ProcessTokens(const std::string& contribution_id); + void PrepareStepSaved( + const ledger::Result result, + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback); + + void ProcessTokens( + const std::vector& types, + const std::string& contribution_id, + ledger::ResultCallback callback); void OnProcessTokens( ledger::ContributionInfoPtr contribution, - const std::vector& list); + const std::vector& list, + ledger::ResultCallback callback); 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 CheckIfCompleted(ledger::ContributionInfoPtr contribution); - - void SendTokens( const std::string& publisher_key, - const ledger::RewardsType type, - 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, + const bool single_publisher, ledger::ResultCallback callback); - void ContributionCompleted( + void ContributionAmountSaved( const ledger::Result result, - 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); + const bool single_publisher, + ledger::ResultCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED - std::map retry_timers_; + std::unique_ptr credentials_; }; } // 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 dfa767948ce5..9e7af9a5e4cb 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 @@ -49,7 +49,7 @@ class UnblindedTest : public ::testing::Test { info->amount = 5.0; info->type = ledger::RewardsType::ONE_TIME_TIP; info->step = ledger::ContributionStep::STEP_NO; - info->retry_count = -1; + info->retry_count = 0; callback(std::move(info)); })); @@ -57,16 +57,15 @@ class UnblindedTest : public ::testing::Test { }; TEST_F(UnblindedTest, NotEnoughFunds) { - EXPECT_CALL(*mock_ledger_impl_, - ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _)); - std::vector delete_list; delete_list.push_back("1"); EXPECT_CALL(*mock_ledger_impl_, DeleteUnblindedTokens(delete_list, _)); - ON_CALL(*mock_ledger_impl_, GetAllUnblindedTokens(_)) + ON_CALL(*mock_ledger_impl_, GetUnblindedTokensByBatchTypes(_, _)) .WillByDefault( - Invoke([](ledger::GetUnblindedTokenListCallback callback) { + Invoke([]( + const std::vector&, + ledger::GetUnblindedTokenListCallback callback) { ledger::UnblindedTokenList list; auto info = ledger::UnblindedToken::New(); @@ -79,20 +78,29 @@ TEST_F(UnblindedTest, NotEnoughFunds) { callback(std::move(list)); })); - unblinded_->Start(contribution_id); + unblinded_->Start( + {ledger::CredsBatchType::PROMOTION}, + contribution_id, + [](const ledger::Result result) { + ASSERT_EQ(result, ledger::Result::NOT_ENOUGH_FUNDS); + }); } TEST_F(UnblindedTest, PromotionExpiredDeleteToken) { - EXPECT_CALL(*mock_ledger_impl_, - ContributionCompleted(ledger::Result::LEDGER_OK, _, _, _)); + EXPECT_CALL(*mock_ledger_impl_, UpdateContributionInfoStep( + _, + ledger::ContributionStep::STEP_PREPARE, + _)); std::vector delete_list; delete_list.push_back("1"); EXPECT_CALL(*mock_ledger_impl_, DeleteUnblindedTokens(delete_list, _)); - ON_CALL(*mock_ledger_impl_, GetAllUnblindedTokens(_)) + ON_CALL(*mock_ledger_impl_, GetUnblindedTokensByBatchTypes(_, _)) .WillByDefault( - Invoke([](ledger::GetUnblindedTokenListCallback callback) { + Invoke([]( + const std::vector&, + ledger::GetUnblindedTokenListCallback callback) { ledger::UnblindedTokenList list; auto info = ledger::UnblindedToken::New(); @@ -109,21 +117,25 @@ TEST_F(UnblindedTest, PromotionExpiredDeleteToken) { callback(std::move(list)); })); - unblinded_->Start(contribution_id); + unblinded_->Start( + {ledger::CredsBatchType::PROMOTION}, + contribution_id, + [](const ledger::Result result) { + ASSERT_EQ(result, ledger::Result::LEDGER_ERROR); + }); } TEST_F(UnblindedTest, PromotionExpiredDeleteTokensNotEnoughFunds) { - EXPECT_CALL(*mock_ledger_impl_, - ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _)); - std::vector delete_list; delete_list.push_back("1"); delete_list.push_back("2"); EXPECT_CALL(*mock_ledger_impl_, DeleteUnblindedTokens(delete_list, _)); - ON_CALL(*mock_ledger_impl_, GetAllUnblindedTokens(_)) + ON_CALL(*mock_ledger_impl_, GetUnblindedTokensByBatchTypes(_, _)) .WillByDefault( - Invoke([](ledger::GetUnblindedTokenListCallback callback) { + Invoke([]( + const std::vector&, + ledger::GetUnblindedTokenListCallback callback) { ledger::UnblindedTokenList list; auto info = ledger::UnblindedToken::New(); @@ -139,7 +151,12 @@ TEST_F(UnblindedTest, PromotionExpiredDeleteTokensNotEnoughFunds) { callback(std::move(list)); })); - unblinded_->Start(contribution_id); + unblinded_->Start( + {ledger::CredsBatchType::PROMOTION}, + contribution_id, + [](const ledger::Result result) { + ASSERT_EQ(result, ledger::Result::NOT_ENOUGH_FUNDS); + }); } } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc index aed6ff10aa7d..4f3bcaf70d4d 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc @@ -5,36 +5,12 @@ #include +#include "bat/ledger/global_constants.h" #include "bat/ledger/internal/contribution/contribution_util.h" - -#include "wrapper.hpp" // NOLINT - -using challenge_bypass_ristretto::UnblindedToken; -using challenge_bypass_ristretto::VerificationKey; -using challenge_bypass_ristretto::VerificationSignature; +#include "bat/ledger/internal/static_values.h" namespace braveledger_contribution { -ledger::ReconcileDirections -FromContributionQueuePublishersToReconcileDirections( - ledger::ContributionQueuePublisherList list) { - ledger::ReconcileDirections directions; - - for (auto& item : list) { - if (!item || item->publisher_key.empty()) { - continue; - } - - ledger::ReconcileDirectionProperties direction; - direction.publisher_key = item->publisher_key, - direction.amount_percent = item->amount_percent; - - directions.push_back(direction); - } - - return directions; -} - ledger::ReportType GetReportTypeFromRewardsType( const ledger::RewardsType type) { switch (static_cast(type)) { @@ -55,41 +31,104 @@ ledger::ReportType GetReportTypeFromRewardsType( } } -bool GenerateSuggestion( - const std::string& token_value, - const std::string& public_key, - const std::string& suggestion_encoded, - base::Value* result) { - if (token_value.empty() || public_key.empty() || suggestion_encoded.empty()) { - return false; +ledger::ContributionProcessor GetProcessor(const std::string& wallet_type) { + if (wallet_type == ledger::kWalletUnBlinded) { + return ledger::ContributionProcessor::BRAVE_TOKENS; } - UnblindedToken unblinded = UnblindedToken::decode_base64(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(); + if (wallet_type == ledger::kWalletAnonymous) { + return ledger::ContributionProcessor::BRAVE_USER_FUNDS; + } + + if (wallet_type == ledger::kWalletUphold) { + return ledger::ContributionProcessor::UPHOLD; + } + + return ledger::ContributionProcessor::NONE; +} + +std::string GetNextProcessor(const std::string& current_processor) { + if (current_processor == ledger::kWalletUnBlinded) { + return ledger::kWalletAnonymous; + } + + if (current_processor == ledger::kWalletAnonymous) { + return ledger::kWalletUphold; + } + + if (current_processor == ledger::kWalletUphold) { + return ""; + } + + return ledger::kWalletUnBlinded; +} - if (challenge_bypass_ristretto::exception_occurred()) { - challenge_bypass_ristretto::TokenException e = - challenge_bypass_ristretto::get_last_exception(); +bool HaveEnoughFundsToContribute( + double* amount, + const bool partial, + const double balance) { + DCHECK(amount); + + if (partial) { + if (balance == 0) { + return false; + } + + if (*amount > balance) { + *amount = balance; + } + + return true; + } + + if (*amount > balance) { return false; } - result->SetStringKey("t", pre_image); - result->SetStringKey("publicKey", public_key); - result->SetStringKey("signature", signature.encode_base64()); return true; } -bool GenerateSuggestionMock( - const std::string& token_value, - const std::string& public_key, - const std::string& suggestion_encoded, - base::Value* result) { - result->SetStringKey("t", token_value); - result->SetStringKey("publicKey", public_key); - result->SetStringKey("signature", token_value); - return true; +void AdjustPublisherListAmounts( + ledger::ContributionQueuePublisherList publishers, + ledger::ContributionQueuePublisherList* publishers_new, + ledger::ContributionQueuePublisherList* publishers_left, + double reduce_fee_for) { + DCHECK(publishers_new && publishers_left); + + for (auto& item : publishers) { + if (!item) { + continue; + } + + if (reduce_fee_for == 0) { + publishers_left->push_back(std::move(item)); + continue; + } + + if (item->amount_percent <= reduce_fee_for) { + publishers_new->push_back(item->Clone()); + reduce_fee_for -= item->amount_percent; + continue; + } + + if (item->amount_percent > reduce_fee_for) { + // current list + const auto original_weight = item->amount_percent; + item->amount_percent = reduce_fee_for; + publishers_new->push_back(item->Clone()); + + // next list + item->amount_percent = original_weight - reduce_fee_for; + publishers_left->push_back(item->Clone()); + + reduce_fee_for = 0; + } + } +} + +int32_t GetVotesFromAmount(const double amount) { + DCHECK_GT(braveledger_ledger::_vote_price, 0); + return std::floor(amount / braveledger_ledger::_vote_price); } } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h index a51220096e2f..6ad715e53896 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h @@ -9,29 +9,28 @@ #include #include -#include "base/values.h" #include "bat/ledger/mojom_structs.h" -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" namespace braveledger_contribution { -ledger::ReconcileDirections -FromContributionQueuePublishersToReconcileDirections( - ledger::ContributionQueuePublisherList list); - ledger::ReportType GetReportTypeFromRewardsType(const ledger::RewardsType type); -bool GenerateSuggestion( - const std::string& token_value, - const std::string& public_key, - const std::string& suggestion_encoded, - base::Value* result); - -bool GenerateSuggestionMock( - const std::string& token_value, - const std::string& public_key, - const std::string& suggestion_encoded, - base::Value* result); +ledger::ContributionProcessor GetProcessor(const std::string& wallet_type); + +std::string GetNextProcessor(const std::string& current_processor); + +bool HaveEnoughFundsToContribute( + double* amount, + const bool partial, + const double balance); + +void AdjustPublisherListAmounts( + ledger::ContributionQueuePublisherList publishers, + ledger::ContributionQueuePublisherList* publishers_new, + ledger::ContributionQueuePublisherList* publishers_left, + double reduce_fee_for); + +int32_t GetVotesFromAmount(const double amount); } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util_unittest.cc deleted file mode 100644 index 02f331adc919..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util_unittest.cc +++ /dev/null @@ -1,61 +0,0 @@ -/* 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 "base/values.h" -#include "bat/ledger/internal/contribution/contribution_util.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=ContributionUtilTest.* - -namespace braveledger_contribution { - -class ContributionUtilTest : public testing::Test {}; - -TEST_F(ContributionUtilTest, GenerateSuggestionEmptyToken) { - base::Value token(base::Value::Type::DICTIONARY); - bool success = GenerateSuggestion( - "", - "rqQ1Tz26C4mv33ld7xpcLhuX1sWaD+s7VMnuX6cokT4=", - "some id", - &token); - ASSERT_FALSE(success); -} - -TEST_F(ContributionUtilTest, GenerateSuggestionEmptyPublicKey) { - base::Value token(base::Value::Type::DICTIONARY); - bool success = GenerateSuggestion( - "Twsi4QeUNcOOW/IFnYcGLHgLsfVco0oPZ+cl3YeZMQgb4NB8E29Ts+2/pQA54VksqGpg/DtmPRBV4FlQ1VXbKmiwO9BI7jDXSN33CCb+rSBe1PCG1LtigUOfzaIVF3c5", // NOLINT - "", - "some id", - &token); - ASSERT_FALSE(success); -} - -TEST_F(ContributionUtilTest, GenerateSuggestionEmptyPayload) { - base::Value token(base::Value::Type::DICTIONARY); - bool success = GenerateSuggestion( - "Twsi4QeUNcOOW/IFnYcGLHgLsfVco0oPZ+cl3YeZMQgb4NB8E29Ts+2/pQA54VksqGpg/DtmPRBV4FlQ1VXbKmiwO9BI7jDXSN33CCb+rSBe1PCG1LtigUOfzaIVF3c5", // NOLINT - "rqQ1Tz26C4mv33ld7xpcLhuX1sWaD+s7VMnuX6cokT4=", - "", - &token); - ASSERT_FALSE(success); -} - -TEST_F(ContributionUtilTest, GenerateSuggestionGenerated) { - const std::string public_key = - "rqQ1Tz26C4mv33ld7xpcLhuX1sWaD+s7VMnuX6cokT4="; - base::Value token(base::Value::Type::DICTIONARY); - bool success = GenerateSuggestion( - "Twsi4QeUNcOOW/IFnYcGLHgLsfVco0oPZ+cl3YeZMQgb4NB8E29Ts+2/pQA54VksqGpg/DtmPRBV4FlQ1VXbKmiwO9BI7jDXSN33CCb+rSBe1PCG1LtigUOfzaIVF3c5", // NOLINT - public_key, - "some id", - &token); - ASSERT_TRUE(success); - ASSERT_EQ(*token.FindStringKey("t"), "Twsi4QeUNcOOW/IFnYcGLHgLsfVco0oPZ+cl3YeZMQgb4NB8E29Ts+2/pQA54VksqGpg/DtmPRBV4FlQ1VXbKg=="); // NOLINT - ASSERT_EQ(*token.FindStringKey("publicKey"), public_key); - ASSERT_EQ(*token.FindStringKey("signature"), "qnQvRh1dWoc/YKAGVYgP4PljOoK10T8ryMqLGY6RFc3Gig8mZCzmuGH5IQtVtCZ0x42/pOFKfX3rUpzIL4wPUw=="); // NOLINT -} - -} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.cc deleted file mode 100644 index b5549bbbdbee..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.cc +++ /dev/null @@ -1,533 +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 - -#include "anon/anon.h" -#include "bat/ledger/internal/request/request_util.h" -#include "bat/ledger/internal/contribution/phase_one.h" -#include "bat/ledger/internal/contribution/phase_two.h" -#include "bat/ledger/internal/bat_util.h" -#include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/bat_helper.h" -#include "bat/ledger/internal/properties/reconcile_request_properties.h" -#include "bat/ledger/internal/properties/transaction_properties.h" -#include "bat/ledger/internal/properties/unsigned_tx_properties.h" -#include "bat/ledger/internal/properties/wallet_info_properties.h" -#include "bat/ledger/internal/state/reconcile_request_state.h" -#include "bat/ledger/internal/state/transaction_state.h" -#include "bat/ledger/internal/state/unsigned_tx_state.h" -#include "net/http/http_status_code.h" - -using std::placeholders::_1; -using std::placeholders::_2; -using std::placeholders::_3; - -namespace braveledger_contribution { - -PhaseOne::PhaseOne(bat_ledger::LedgerImpl* ledger, - Contribution* contribution) : - ledger_(ledger), - contribution_(contribution) { - initAnonize(); -} - -PhaseOne::~PhaseOne() { -} - -void PhaseOne::Start(const std::string& viewing_id) { - const std::string user_id = ledger_->GetUserId(); - if (user_id.empty()) { - auto reconcile = ledger_->GetReconcileById(viewing_id); - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); - return; - } - - ledger_->AddReconcileStep(viewing_id, - ledger::ContributionRetry::STEP_RECONCILE); - std::string url = braveledger_request_util::BuildUrl( - (std::string)RECONCILE_CONTRIBUTION + user_id, PREFIX_V2); - - auto callback = std::bind(&PhaseOne::ReconcileCallback, - this, - viewing_id, - _1, - _2, - _3); - ledger_->LoadURL(url, - std::vector(), - "", - "", - ledger::UrlMethod::GET, - callback); -} - -void PhaseOne::ReconcileCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - auto reconcile = ledger_->GetReconcileById(viewing_id); - - if (response_status_code != net::HTTP_OK || reconcile.viewing_id.empty()) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_RECONCILE, - viewing_id); - return; - } - - bool success = braveledger_bat_helper::getJSONValue( - SURVEYOR_ID, - response, - &reconcile.surveyor_id); - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_RECONCILE, - viewing_id); - return; - } - - success = ledger_->UpdateReconcile(reconcile); - if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); - return; - } - - CurrentReconcile(viewing_id); -} - -void PhaseOne::CurrentReconcile(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - ledger::ContributionRetry::STEP_CURRENT); - std::ostringstream amount; - auto reconcile = ledger_->GetReconcileById(viewing_id); - - amount << reconcile.fee; - - std::string currency = ledger_->GetCurrency(); - std::string path = (std::string)WALLET_PROPERTIES + - ledger_->GetPaymentId() + - "?refresh=true" + - "&amount=" + - amount.str() + - "&altcurrency=" + - currency; - - auto callback = std::bind(&PhaseOne::CurrentReconcileCallback, - this, - viewing_id, - _1, - _2, - _3); - ledger_->LoadURL( - braveledger_request_util::BuildUrl(path, PREFIX_V2), - std::vector(), - "", - "", - ledger::UrlMethod::GET, - callback); -} - -void PhaseOne::CurrentReconcileCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - if (response_status_code != net::HTTP_OK) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_CURRENT, - viewing_id); - return; - } - - auto reconcile = ledger_->GetReconcileById(viewing_id); - - bool success = braveledger_bat_helper::getJSONRates(response, - &reconcile.rates); - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_CURRENT, - viewing_id); - return; - } - - ledger::UnsignedTxProperties unsigned_tx; - const ledger::UnsignedTxState unsigned_tx_state; - success = unsigned_tx_state.FromJsonResponse(response, &unsigned_tx); - - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_CURRENT, - viewing_id); - return; - } - - if (unsigned_tx.amount.empty() && - unsigned_tx.currency.empty() && - unsigned_tx.destination.empty()) { - // We don't have any unsigned transactions - contribution_->AddRetry(ledger::ContributionRetry::STEP_CURRENT, - viewing_id); - return; - } - - reconcile.amount = unsigned_tx.amount; - reconcile.currency = unsigned_tx.currency; - reconcile.destination = unsigned_tx.destination; - - if (ledger::is_testing) { - std::ostringstream amount; - amount << reconcile.fee; - reconcile.amount = amount.str(); - } - - success = ledger_->UpdateReconcile(reconcile); - - if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); - return; - } - - ReconcilePayload(viewing_id); -} - -void PhaseOne::ReconcilePayload(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - ledger::ContributionRetry::STEP_PAYLOAD); - auto reconcile = ledger_->GetReconcileById(viewing_id); - ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); - - ledger::UnsignedTxProperties unsigned_tx; - unsigned_tx.amount = reconcile.amount; - unsigned_tx.currency = reconcile.currency; - unsigned_tx.destination = reconcile.destination; - const ledger::UnsignedTxState unsigned_tx_state; - 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); - - std::vector secret_key = braveledger_bat_helper::getHKDF( - wallet_info.key_info_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) { - // TODO(nejczdovc) what should we do in this case? - return; - } - - std::string headerSignature = braveledger_bat_helper::sign( - header_keys, - header_values, - "primary", - new_secret_key); - - ledger::ReconcileRequestProperties reconcile_request; - reconcile_request.type = "httpSignature"; - reconcile_request.signed_tx_headers_digest = header_digest; - reconcile_request.signed_tx_headers_signature = headerSignature; - reconcile_request.signed_tx_body = unsigned_tx; - reconcile_request.signed_tx_octets = octets; - reconcile_request.viewing_id = reconcile.viewing_id; - reconcile_request.surveyor_id = reconcile.surveyor_id; - const ledger::ReconcileRequestState reconcile_request_state; - std::string payload_stringify = - reconcile_request_state.ToJson(reconcile_request); - - std::vector wallet_header; - wallet_header.push_back("Content-Type: application/json; charset=UTF-8"); - std::string path = (std::string)WALLET_PROPERTIES + ledger_->GetPaymentId(); - - auto callback = std::bind(&PhaseOne::ReconcilePayloadCallback, - this, - viewing_id, - _1, - _2, - _3); - ledger_->LoadURL( - braveledger_request_util::BuildUrl(path, PREFIX_V2), - wallet_header, - payload_stringify, - "application/json; charset=utf-8", - ledger::UrlMethod::PUT, - callback); -} - -void PhaseOne::ReconcilePayloadCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - const auto reconcile = ledger_->GetReconcileById(viewing_id); - - if (response_status_code != net::HTTP_OK) { - if (response_status_code == net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE) { - Complete( - ledger::Result::CONTRIBUTION_AMOUNT_TOO_LOW, - viewing_id, - reconcile.type); - } else { - contribution_->AddRetry(ledger::ContributionRetry::STEP_PAYLOAD, - viewing_id); - } - return; - } - - ledger::TransactionProperties transaction; - const ledger::TransactionState transaction_state; - bool success = transaction_state.FromJsonResponse(response, &transaction); - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_PAYLOAD, - viewing_id); - return; - } - - transaction.viewing_id = reconcile.viewing_id; - transaction.surveyor_id = reconcile.surveyor_id; - transaction.contribution_rates = reconcile.rates; - - if (ledger::is_testing) { - transaction.contribution_probi = - braveledger_bat_util::ConvertToProbi(reconcile.amount); - } - - ledger::Transactions transactions = ledger_->GetTransactions(); - transactions.push_back(transaction); - ledger_->SetTransactions(transactions); - RegisterViewing(viewing_id); -} - -void PhaseOne::RegisterViewing(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - ledger::ContributionRetry::STEP_REGISTER); - auto callback = std::bind(&PhaseOne::RegisterViewingCallback, - this, - viewing_id, - _1, - _2, - _3); - ledger_->LoadURL( - braveledger_request_util::BuildUrl( - (std::string)REGISTER_VIEWING, PREFIX_V2), - std::vector(), - "", - "", - ledger::UrlMethod::GET, - callback); -} - -void PhaseOne::RegisterViewingCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - if (response_status_code != net::HTTP_OK) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_REGISTER, - viewing_id); - return; - } - - auto reconcile = ledger_->GetReconcileById(viewing_id); - - bool success = braveledger_bat_helper::getJSONValue(REGISTRARVK_FIELDNAME, - response, - &reconcile.registrar_vk); - DCHECK(!reconcile.registrar_vk.empty()); - if (!success || reconcile.registrar_vk.empty()) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_REGISTER, - viewing_id); - return; - } - - reconcile.anonize_viewing_id = reconcile.viewing_id; - reconcile.anonize_viewing_id.erase( - std::remove(reconcile.anonize_viewing_id.begin(), - reconcile.anonize_viewing_id.end(), - '-'), - reconcile.anonize_viewing_id.end()); - reconcile.anonize_viewing_id.erase(12, 1); - reconcile.proof = GetAnonizeProof(reconcile.registrar_vk, - reconcile.anonize_viewing_id, - &reconcile.pre_flight); - - success = ledger_->UpdateReconcile(reconcile); - if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); - return; - } - - ViewingCredentials(viewing_id); -} - -std::string PhaseOne::GetAnonizeProof( - const std::string& registrar_VK, - const std::string& id, - std::string* pre_flight) { - const char* cred = makeCred(id.c_str()); - if (cred != nullptr) { - *pre_flight = std::string(cred); - // should fix in - // https://github.com/brave-intl/bat-native-anonize/issues/11 - free((void*)cred); // NOLINT - } else { - return ""; - } - const char* proof_temp = registerUserMessage(pre_flight->c_str(), - registrar_VK.c_str()); - std::string proof; - if (proof_temp != nullptr) { - proof = proof_temp; - // should fix in - // https://github.com/brave-intl/bat-native-anonize/issues/11 - free((void*)proof_temp); // NOLINT - } else { - return ""; - } - - return proof; -} - -void PhaseOne::ViewingCredentials(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - ledger::ContributionRetry::STEP_VIEWING); - auto reconcile = ledger_->GetReconcileById(viewing_id); - - std::string keys[1] = {"proof"}; - std::string values[1] = {reconcile.proof}; - std::string proof_stringified = braveledger_bat_helper::stringify(keys, - values, - 1); - - std::string url = braveledger_request_util::BuildUrl( - (std::string)REGISTER_VIEWING + - "/" + - reconcile.anonize_viewing_id, - PREFIX_V2); - - auto callback = std::bind(&PhaseOne::ViewingCredentialsCallback, - this, - viewing_id, - _1, - _2, - _3); - ledger_->LoadURL(url, - std::vector(), - proof_stringified, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - callback); -} - -void PhaseOne::ViewingCredentialsCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - if (response_status_code != net::HTTP_OK) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_VIEWING, - viewing_id); - return; - } - - auto reconcile = ledger_->GetReconcileById(viewing_id); - - std::string verification; - bool success = braveledger_bat_helper::getJSONValue(VERIFICATION_FIELDNAME, - response, - &verification); - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_VIEWING, - viewing_id); - return; - } - - const char* master_user_token = registerUserFinal( - reconcile.anonize_viewing_id.c_str(), - verification.c_str(), - reconcile.pre_flight.c_str(), - reconcile.registrar_vk.c_str()); - - if (master_user_token != nullptr) { - reconcile.master_user_token = master_user_token; - // should fix in - // https://github.com/brave-intl/bat-native-anonize/issues/11 - free((void*)master_user_token); // NOLINT - } - - success = ledger_->UpdateReconcile(reconcile); - if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); - return; - } - - std::vector surveyors; - success = braveledger_bat_helper::getJSONList(SURVEYOR_IDS, - response, - &surveyors); - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_VIEWING, - viewing_id); - return; - } - - std::string probi = "0"; - // Save the rest values to transactions - ledger::Transactions transactions = ledger_->GetTransactions(); - - for (size_t i = 0; i < transactions.size(); i++) { - if (transactions[i].viewing_id != reconcile.viewing_id) { - continue; - } - - transactions[i].anonize_viewing_id = reconcile.anonize_viewing_id; - transactions[i].registrar_vk = reconcile.registrar_vk; - transactions[i].master_user_token = reconcile.master_user_token; - transactions[i].surveyor_ids = surveyors; - probi = transactions[i].contribution_probi; - } - - ledger_->SetTransactions(transactions); - Complete(ledger::Result::LEDGER_OK, - reconcile.viewing_id, - reconcile.type, - probi); -} - -void PhaseOne::Complete( - ledger::Result result, - const std::string& viewing_id, - const ledger::RewardsType type, - const std::string& probi) { - const bool error = result != ledger::Result::LEDGER_OK; - const double amount = braveledger_bat_util::ProbiToDouble(probi); - ledger_->ReconcileComplete(result, amount, viewing_id, type, error); - - if (error) { - return; - } - - ledger_->AddReconcileStep( - viewing_id, - ledger::ContributionRetry::STEP_WINNERS); - - contribution_->StartPhaseTwo(viewing_id); -} - -} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.h deleted file mode 100644 index 1ca6c94056ad..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.h +++ /dev/null @@ -1,85 +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_CONTRIBUTION_PHASE_ONE_H_ -#define BRAVELEDGER_CONTRIBUTION_PHASE_ONE_H_ - -#include -#include -#include -#include - -#include "bat/ledger/ledger.h" -#include "bat/ledger/internal/contribution/contribution.h" - -namespace bat_ledger { -class LedgerImpl; -} - -namespace braveledger_contribution { - -class PhaseOne { - public: - explicit PhaseOne( - bat_ledger::LedgerImpl* ledger, - Contribution* contribution); - - ~PhaseOne(); - - void Start(const std::string &viewing_id); - - void CurrentReconcile(const std::string& viewing_id); - - void ReconcilePayload(const std::string& viewing_id); - - void RegisterViewing(const std::string& viewing_id); - - void ViewingCredentials(const std::string& viewing_id); - - void Complete(ledger::Result result, - const std::string& viewing_id, - const ledger::RewardsType type, - const std::string& probi = "0"); - - private: - std::string GetAnonizeProof(const std::string& registrar_VK, - const std::string& id, - std::string* pre_flight); - - void ReconcileCallback(const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers); - - void CurrentReconcileCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers); - - void ReconcilePayloadCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers); - - void RegisterViewingCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers); - - void ViewingCredentialsCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers); - - bat_ledger::LedgerImpl* ledger_; // NOT OWNED - Contribution* contribution_; // NOT OWNED -}; - -} // namespace braveledger_contribution -#endif // BRAVELEDGER_CONTRIBUTION_PHASE_ONE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.cc deleted file mode 100644 index 3c21d1b70f60..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.cc +++ /dev/null @@ -1,633 +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/contribution/phase_two.h" - -#include "anon/anon.h" -#include "base/task/post_task.h" -#include "base/task_runner_util.h" -#include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/bat_helper.h" -#include "bat/ledger/internal/request/request_util.h" -#include "bat/ledger/internal/properties/ballot_properties.h" -#include "bat/ledger/internal/properties/batch_proof_properties.h" -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" -#include "bat/ledger/internal/properties/transaction_ballot_properties.h" -#include "bat/ledger/internal/properties/transaction_properties.h" -#include "bat/ledger/internal/properties/winner_properties.h" -#include "bat/ledger/internal/state/publisher_vote_state.h" -#include "bat/ledger/internal/state/surveyor_state.h" -#include "brave_base/random.h" -#include "net/http/http_status_code.h" - -#if defined(OS_IOS) -#include -#endif - -using std::placeholders::_1; -using std::placeholders::_2; -using std::placeholders::_3; - -namespace braveledger_contribution { - -PhaseTwo::PhaseTwo(bat_ledger::LedgerImpl* ledger, - Contribution* contribution) : - ledger_(ledger), - contribution_(contribution), - last_prepare_vote_batch_timer_id_(0u), - last_vote_batch_timer_id_(0u) { -} - -PhaseTwo::~PhaseTwo() { -} - -void PhaseTwo::Initialize() { - // Check if we have some more pending ballots to go out - PrepareBallots(); -} - -void PhaseTwo::Start(const std::string& viewing_id) { - unsigned int ballots_count = GetBallotsCount(viewing_id); - const auto reconcile = ledger_->GetReconcileById(viewing_id); - - switch (reconcile.type) { - case ledger::RewardsType::AUTO_CONTRIBUTE: { - GetContributeWinners(ballots_count, viewing_id, reconcile.directions); - break; - } - - case ledger::RewardsType::RECURRING_TIP: - case ledger::RewardsType::ONE_TIME_TIP: { - ledger::WinnerProperties winner; - winner.vote_count = ballots_count; - winner.direction.publisher_key = - reconcile.directions.front().publisher_key; - winner.direction.amount_percent = 100.0; - VotePublishers(ledger::Winners { winner }, viewing_id); - break; - } - - default: - // TODO(nejczdovc) what should we do here? - return; - } -} - -unsigned int PhaseTwo::GetBallotsCount( - const std::string& viewing_id) { - unsigned int count = 0; - ledger::Transactions transactions = ledger_->GetTransactions(); - for (size_t i = 0; i < transactions.size(); i++) { - if (transactions[i].vote_count < transactions[i].surveyor_ids.size() - && transactions[i].viewing_id == viewing_id) { - count += transactions[i].surveyor_ids.size() - transactions[i].vote_count; - } - } - - return count; -} - -bool PhaseTwo::GetStatisticalVotingWinner( - double dart, - const ledger::ReconcileDirections& directions, - ledger::WinnerProperties* winner) { - double upper = 0.0; - for (const auto& direction : directions) { - upper += direction.amount_percent / 100.0; - if (upper < dart) - continue; - - winner->vote_count = 1; - winner->direction = direction; - - return true; - } - - return false; -} - -ledger::Winners PhaseTwo::GetStatisticalVotingWinners( - uint32_t total_votes, - const ledger::ReconcileDirections& directions) { - ledger::Winners winners; - - while (total_votes > 0) { - double dart = brave_base::random::Uniform_01(); - ledger::WinnerProperties winner; - if (GetStatisticalVotingWinner(dart, directions, &winner)) { - winners.push_back(winner); - --total_votes; - } - } - - return winners; -} - -void PhaseTwo::GetContributeWinners( - const unsigned int ballots, - const std::string& viewing_id, - const ledger::ReconcileDirections& directions) { - ledger::Winners winners = GetStatisticalVotingWinners(ballots, directions); - VotePublishers(winners, viewing_id); -} - -void PhaseTwo::VotePublishers( - const ledger::Winners& winners, - const std::string& viewing_id) { - std::vector publishers; - for (size_t i = 0; i < winners.size(); i++) { - for (size_t j = 0; j < winners[i].vote_count; j++) { - publishers.push_back(winners[i].direction.publisher_key); - } - } - - for (size_t i = 0; i < publishers.size(); i++) { - VotePublisher(publishers[i], viewing_id); - } - - ledger_->AddReconcileStep(viewing_id, ledger::ContributionRetry::STEP_FINAL); - - PrepareBallots(); -} - -void PhaseTwo::VotePublisher(const std::string& publisher, - const std::string& viewing_id) { - DCHECK(!publisher.empty()); - if (publisher.empty()) { - // TODO(nejczdovc) what should we do in this case? - return; - } - - ledger::BallotProperties ballot; - int i = 0; - - ledger::Transactions transactions = ledger_->GetTransactions(); - - if (transactions.size() == 0) { - // TODO(nejczdovc) what should we do in this case? - return; - } - - for (i = transactions.size() - 1; i >=0; i--) { - if (transactions[i].vote_count >= transactions[i].surveyor_ids.size()) { - continue; - } - - if (transactions[i].viewing_id == viewing_id || viewing_id.empty()) { - break; - } - } - - // transaction was not found - if (i < 0) { - // TODO(nejczdovc) what should we do in this case? - return; - } - - ballot.viewing_id = transactions[i].viewing_id; - ballot.surveyor_id = transactions[i].surveyor_ids[transactions[i].vote_count]; - ballot.publisher = publisher; - ballot.count = transactions[i].vote_count; - transactions[i].vote_count++; - - ledger::Ballots ballots = ledger_->GetBallots(); - ballots.push_back(ballot); - - ledger_->SetTransactions(transactions); - ledger_->SetBallots(ballots); -} - -void PhaseTwo::PrepareBallots() { - ledger::Transactions transactions = ledger_->GetTransactions(); - ledger::Ballots ballots = ledger_->GetBallots(); - - if (ballots.size() == 0) { - // skip ballots and start sending votes - contribution_->SetTimer(&last_vote_batch_timer_id_); - return; - } - - for (int i = ballots.size() - 1; i >= 0; i--) { - for (size_t j = 0; j < transactions.size(); j++) { - if (transactions[j].viewing_id == ballots[i].viewing_id) { - if (ballots[i].prepare_ballot.empty()) { - PrepareBatch(ballots[i], transactions[j]); - return; - } - - if (ballots[i].proof_ballot.empty()) { - Proof(); - return; - } - } - } - } - - // In case we already prepared all ballots - PrepareVoteBatch(); -} - -void PhaseTwo::PrepareBatch( - const ledger::BallotProperties& ballot, - const ledger::TransactionProperties& transaction) { - std::string url = braveledger_request_util::BuildUrl( - (std::string)SURVEYOR_BATCH_VOTING + - "/" + - transaction.anonize_viewing_id, PREFIX_V2); - - auto callback = std::bind(&PhaseTwo::PrepareBatchCallback, - this, - transaction.viewing_id, - _1, - _2, - _3); - ledger_->LoadURL(url, - std::vector(), - "", - "", - ledger::UrlMethod::GET, - callback); -} - -void PhaseTwo::AssignPrepareBallots( - const std::string& viewing_id, - const std::vector& surveyors, - ledger::Ballots* ballots) { - for (size_t j = 0; j < surveyors.size(); j++) { - std::string error; - braveledger_bat_helper::getJSONValue("error", surveyors[j], &error); - if (!error.empty()) { - // TODO(nejczdovc) what should we do here - continue; - } - - std::string surveyor_id; - bool success = braveledger_bat_helper::getJSONValue("surveyorId", - surveyors[j], - &surveyor_id); - if (!success) { - // TODO(nejczdovc) what should we do here - continue; - } - - for (auto& ballot : *ballots) { - if (ballot.surveyor_id == surveyor_id && - ballot.viewing_id == viewing_id) { - ballot.prepare_ballot = surveyors[j]; - } - } - } -} - -void PhaseTwo::PrepareBatchCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - if (response_status_code != net::HTTP_OK) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_PREPARE, ""); - return; - } - - std::vector surveyors; - bool success = braveledger_bat_helper::getJSONBatchSurveyors(response, - &surveyors); - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_PREPARE, ""); - return; - } - - ledger::Ballots ballots = ledger_->GetBallots(); - - AssignPrepareBallots(viewing_id, surveyors, &ballots); - - ledger_->SetBallots(ballots); - Proof(); -} - -void PhaseTwo::Proof() { - ledger::BatchProofs batch_proofs; - - ledger::Transactions transactions = ledger_->GetTransactions(); - ledger::Ballots ballots = ledger_->GetBallots(); - - for (int i = ballots.size() - 1; i >= 0; i--) { - for (size_t k = 0; k < transactions.size(); k++) { - if (transactions[k].viewing_id == ballots[i].viewing_id) { - if (ballots[i].prepare_ballot.empty()) { - // TODO(nejczdovc) what should we do here - return; - } - - if (ballots[i].proof_ballot.empty()) { - ledger::BatchProofProperties batch_proof; - batch_proof.transaction = transactions[k]; - batch_proof.ballot = ballots[i]; - batch_proofs.push_back(batch_proof); - } - } - } - } - -#if defined(OS_IOS) - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, - 0), ^{ - const auto result = this->ProofBatch(batch_proofs); - dispatch_async(dispatch_get_main_queue(), ^{ - this->ProofBatchCallback(batch_proofs, result); - }); - }); -#else - base::PostTaskAndReplyWithResult( - ledger_->GetTaskRunner().get(), - FROM_HERE, - base::BindOnce(&PhaseTwo::ProofBatch, - base::Unretained(this), - batch_proofs), - base::BindOnce(&PhaseTwo::ProofBatchCallback, - base::Unretained(this), - batch_proofs)); -#endif -} - -std::vector PhaseTwo::ProofBatch( - const ledger::BatchProofs& batch_proofs) { - std::vector proofs; - - for (size_t i = 0; i < batch_proofs.size(); i++) { - ledger::SurveyorProperties surveyor; - const ledger::SurveyorState surveyor_state; - bool success = surveyor_state.FromJson( - batch_proofs[i].ballot.prepare_ballot, &surveyor); - - if (!success) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << - "Failed to load surveyor state: " << - batch_proofs[i].ballot.prepare_ballot; - continue; - } - - std::string signature_to_send; - size_t delimeter_pos = surveyor.signature.find(','); - if (std::string::npos != delimeter_pos && - delimeter_pos + 1 <= surveyor.signature.length()) { - signature_to_send = surveyor.signature.substr(delimeter_pos + 1); - - if (signature_to_send.length() > 1 && signature_to_send[0] == ' ') { - signature_to_send.erase(0, 1); - } - } - - if (signature_to_send.empty()) { - continue; - } - - std::string msg_key[1] = {"publisher"}; - std::string msg_value[1] = {batch_proofs[i].ballot.publisher}; - std::string msg = braveledger_bat_helper::stringify(msg_key, msg_value, 1); - - const char* proof = submitMessage( - msg.c_str(), - batch_proofs[i].transaction.master_user_token.c_str(), - batch_proofs[i].transaction.registrar_vk.c_str(), - signature_to_send.c_str(), - surveyor.surveyor_id.c_str(), - surveyor.survey_vk.c_str()); - - std::string annon_proof; - if (proof != nullptr) { - annon_proof = proof; - // should fix in - // https://github.com/brave-intl/bat-native-anonize/issues/11 - free((void*)proof); // NOLINT - } - - proofs.push_back(annon_proof); - } - - return proofs; -} - -void PhaseTwo::AssignProofs( - const ledger::BatchProofs& batch_proofs, - const std::vector& proofs, - ledger::Ballots* ballots) { - for (size_t i = 0; i < batch_proofs.size(); i++) { - for (auto& ballot : *ballots) { - if (ballot.surveyor_id == batch_proofs[i].ballot.surveyor_id && - ballot.viewing_id == batch_proofs[i].ballot.viewing_id) { - ballot.proof_ballot = proofs[i]; - } - } - } -} - -void PhaseTwo::ProofBatchCallback( - const ledger::BatchProofs& batch_proofs, - const std::vector& proofs) { - ledger::Ballots ballots = ledger_->GetBallots(); - - AssignProofs(batch_proofs, proofs, &ballots); - - ledger_->SetBallots(ballots); - - if (batch_proofs.size() != proofs.size()) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_PROOF, ""); - return; - } - - contribution_->SetTimer(&last_prepare_vote_batch_timer_id_); -} - -void PhaseTwo::PrepareVoteBatch() { - ledger::Transactions transactions = ledger_->GetTransactions(); - ledger::Ballots ballots = ledger_->GetBallots(); - ledger::PublisherVotes publisher_votes = ledger_->GetPublisherVotes(); - - if (ballots.size() == 0) { - contribution_->SetTimer(&last_vote_batch_timer_id_); - return; - } - - for (int i = ballots.size() - 1; i >= 0; i--) { - if (ballots[i].prepare_ballot.empty() || ballots[i].proof_ballot.empty()) { - // TODO(nejczdovc) what to do in this case - continue; - } - - bool transaction_exit = false; - for (size_t k = 0; k < transactions.size(); k++) { - if (transactions[k].viewing_id == ballots[i].viewing_id) { - bool ballot_exit = false; - for (size_t j = 0; j < transactions[k].transaction_ballots.size(); - j++) { - if (transactions[k].transaction_ballots[j].publisher == - ballots[i].publisher) { - transactions[k].transaction_ballots[j].count++; - ballot_exit = true; - break; - } - } - - if (!ballot_exit) { - ledger::TransactionBallotProperties transactionBallot; - transactionBallot.publisher = ballots[i].publisher; - transactionBallot.count++; - transactions[k].transaction_ballots.push_back(transactionBallot); - } - transaction_exit = true; - break; - } - } - - if (!transaction_exit) { - // TODO(nejczdovc) what to do in this case - continue; - } - - bool exist_batch = false; - ledger::PublisherVoteProperties publisher_vote; - publisher_vote.surveyor_id = ballots[i].surveyor_id; - publisher_vote.proof = ballots[i].proof_ballot; - - for (size_t k = 0; k < publisher_votes.size(); k++) { - if (publisher_votes[k].publisher == ballots[i].publisher) { - exist_batch = true; - publisher_votes[k].batch_votes.push_back(publisher_vote); - } - } - - if (!exist_batch) { - ledger::PublisherVotesProperties new_publisher_votes; - new_publisher_votes.publisher = ballots[i].publisher; - new_publisher_votes.batch_votes.push_back(publisher_vote); - publisher_votes.push_back(new_publisher_votes); - } - - ballots.erase(ballots.begin() + i); - } - - ledger_->SetTransactions(transactions); - ledger_->SetBallots(ballots); - ledger_->SetPublisherVotes(publisher_votes); - contribution_->SetTimer(&last_vote_batch_timer_id_); -} - -void PhaseTwo::VoteBatch() { - ledger::PublisherVotes publisher_votes = ledger_->GetPublisherVotes(); - if (publisher_votes.size() == 0) { - return; - } - - ledger::PublisherVotesProperties publisher_votes_properties = - publisher_votes[0]; - ledger::BatchVotes batch_votes; - - if (publisher_votes_properties.batch_votes.size() > VOTE_BATCH_SIZE) { - batch_votes.assign(publisher_votes_properties.batch_votes.begin(), - publisher_votes_properties.batch_votes.begin() + VOTE_BATCH_SIZE); - } else { - batch_votes = publisher_votes_properties.batch_votes; - } - - const ledger::PublisherVoteState publisher_vote_state; - std::string payload = publisher_vote_state.ToJson(batch_votes); - - std::string url = braveledger_request_util::BuildUrl( - (std::string)SURVEYOR_BATCH_VOTING, - PREFIX_V2); - auto callback = std::bind(&PhaseTwo::VoteBatchCallback, - this, - publisher_votes_properties.publisher, - _1, - _2, - _3); - ledger_->LoadURL(url, - std::vector(), - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - callback); -} - -void PhaseTwo::VoteBatchCallback( - const std::string& publisher, - int response_status_code, - const std::string& response, - const std::map& headers) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - if (response_status_code != net::HTTP_OK) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_VOTE, ""); - return; - } - - std::vector surveyors; - bool success = braveledger_bat_helper::getJSONBatchSurveyors(response, - &surveyors); - if (!success) { - contribution_->AddRetry(ledger::ContributionRetry::STEP_VOTE, ""); - return; - } - - ledger::PublisherVotes publisher_votes = ledger_->GetPublisherVotes(); - - for (size_t i = 0; i < publisher_votes.size(); i++) { - if (publisher_votes[i].publisher == publisher) { - size_t sizeToCheck = VOTE_BATCH_SIZE; - if (publisher_votes[i].batch_votes.size() < VOTE_BATCH_SIZE) { - sizeToCheck = publisher_votes[i].batch_votes.size(); - } - - for (int j = sizeToCheck - 1; j >= 0; j--) { - for (size_t k = 0; k < surveyors.size(); k++) { - std::string surveyor_id; - bool success = braveledger_bat_helper::getJSONValue("surveyorId", - surveyors[k], - &surveyor_id); - if (!success) { - // TODO(nejczdovc) what to do in this case - continue; - } - - if (surveyor_id == publisher_votes[i].batch_votes[j].surveyor_id) { - publisher_votes[i].batch_votes.erase( - publisher_votes[i].batch_votes.begin() + j); - break; - } - } - } - - if (publisher_votes[i].batch_votes.size() == 0) { - publisher_votes.erase(publisher_votes.begin() + i); - } - break; - } - } - - ledger_->SetPublisherVotes(publisher_votes); - - if (publisher_votes.size() > 0) { - contribution_->SetTimer(&last_vote_batch_timer_id_); - } -} - -void PhaseTwo::OnTimer(uint32_t timer_id) { - if (timer_id == last_prepare_vote_batch_timer_id_) { - last_prepare_vote_batch_timer_id_ = 0; - PrepareVoteBatch(); - return; - } - - if (timer_id == last_vote_batch_timer_id_) { - last_vote_batch_timer_id_ = 0; - VoteBatch(); - return; - } -} - -} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.h deleted file mode 100644 index fd0ed5118dfc..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.h +++ /dev/null @@ -1,123 +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_CONTRIBUTION_PHASE_TWO_H_ -#define BRAVELEDGER_CONTRIBUTION_PHASE_TWO_H_ - -#include - -#include -#include -#include - -#include "bat/ledger/ledger.h" -#include "bat/ledger/internal/contribution/contribution.h" -#include "bat/ledger/internal/properties/ballot_properties.h" -#include "bat/ledger/internal/properties/transaction_properties.h" -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" -#include "bat/ledger/internal/properties/winner_properties.h" -#include "bat/ledger/internal/properties/batch_proof_properties.h" - -namespace bat_ledger { -class LedgerImpl; -} - -namespace braveledger_contribution { - -class PhaseTwo { - public: - explicit PhaseTwo( - bat_ledger::LedgerImpl* ledger, - Contribution* contribution); - - ~PhaseTwo(); - - void Initialize(); - - void Start(const std::string& viewing_id); - - void PrepareBallots(); - - void VoteBatch(); - - void Proof(); - - void OnTimer(uint32_t timer_id); - - private: - unsigned int GetBallotsCount(const std::string& viewing_id); - - bool GetStatisticalVotingWinner( - double dart, - const ledger::ReconcileDirections& list, - ledger::WinnerProperties* winner); - - ledger::Winners GetStatisticalVotingWinners( - uint32_t total_votes, - const ledger::ReconcileDirections& list); - - void GetContributeWinners( - const unsigned int ballots, - const std::string& viewing_id, - const ledger::ReconcileDirections& list); - - void GetTipsWinners(const unsigned int ballots, - const std::string& viewing_id); - - void VotePublishers(const ledger::Winners& winners, - const std::string& viewing_id); - - void VotePublisher(const std::string& publisher, - const std::string& viewing_id); - - void PrepareBatch( - const ledger::BallotProperties& ballot, - const ledger::TransactionProperties& transaction); - - void PrepareBatchCallback( - const std::string& viewing_id, - int response_status_code, - const std::string& response, - const std::map& headers); - - static void AssignPrepareBallots( - const std::string& viewing_id, - const std::vector& surveyors, - ledger::Ballots* ballots); - - std::vector ProofBatch( - const ledger::BatchProofs& batch_proofs); - - void PrepareVoteBatch(); - - static void AssignProofs( - const ledger::BatchProofs& batch_proofs, - const std::vector& proofs, - ledger::Ballots* ballots); - - void ProofBatchCallback( - const ledger::BatchProofs& batch_proofs, - const std::vector& proofs); - - void VoteBatchCallback( - const std::string& publisher, - int response_status_code, - const std::string& response, - const std::map& headers); - - bat_ledger::LedgerImpl* ledger_; // NOT OWNED - Contribution* contribution_; // NOT OWNED - uint32_t last_prepare_vote_batch_timer_id_; - uint32_t last_vote_batch_timer_id_; - - // For testing purposes - friend class PhaseTwoTest; - FRIEND_TEST_ALL_PREFIXES(PhaseTwoTest, AssignPrepareBallotsRespectsViewingID); - FRIEND_TEST_ALL_PREFIXES(PhaseTwoTest, AssignProofsRespectsViewingID); - FRIEND_TEST_ALL_PREFIXES(PhaseTwoTest, GetStatisticalVotingWinners); -}; - -} // namespace braveledger_contribution -#endif // BRAVELEDGER_CONTRIBUTION_PHASE_TWO_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc deleted file mode 100644 index 2abd38fba307..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc +++ /dev/null @@ -1,128 +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 -#include -#include - -#include "bat/ledger/internal/contribution/phase_two.h" -#include "bat/ledger/internal/logging.h" -#include "bat/ledger/internal/properties/ballot_properties.h" -#include "bat/ledger/ledger.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=PhaseTwoTest.* - -namespace braveledger_contribution { - -class PhaseTwoTest : public testing::Test { - protected: - void PopulateDirectionsList(ledger::ReconcileDirections* list) { - ledger::ReconcileDirectionProperties publisher; - - publisher.publisher_key = "publisher1"; - publisher.amount_percent = 2.0; - list->push_back(publisher); - - publisher.publisher_key = "publisher2"; - publisher.amount_percent = 13.0; - list->push_back(publisher); - - publisher.publisher_key = "publisher3"; - publisher.amount_percent = 14.0; - list->push_back(publisher); - - publisher.publisher_key = "publisher4"; - publisher.amount_percent = 23.0; - list->push_back(publisher); - - publisher.publisher_key = "publisher5"; - publisher.amount_percent = 38.0; - list->push_back(publisher); - } -}; - -TEST_F(PhaseTwoTest, GetStatisticalVotingWinners) { - auto phase_two = - std::make_unique(nullptr, nullptr); - - ledger::ReconcileDirections list; - PopulateDirectionsList(&list); - - struct { - double dart; - const char* publisher; - } cases[] = { - {0.01, "publisher1"}, - {0.05, "publisher2"}, - {0.10, "publisher2"}, - {0.20, "publisher3"}, - {0.30, "publisher4"}, - {0.40, "publisher4"}, - {0.50, "publisher4"}, - {0.60, "publisher5"}, - {0.70, "publisher5"}, - {0.80, "publisher5"}, - {0.90, "publisher5"}, - }; - - for (size_t i = 0; i < base::size(cases); i++) { - ledger::WinnerProperties winner; - bool result = phase_two->GetStatisticalVotingWinner( - cases[i].dart, list, &winner); - EXPECT_TRUE(result); - EXPECT_STREQ(winner.direction.publisher_key.c_str(), cases[i].publisher); - } -} - -// Surveyor IDs are not unique and may be shared between different transactions. -// Ensure that when assigning prepareBallot objects to ballots, we only assign -// to ballots for the current viewing ID, even if they share a surveyor ID. -TEST_F(PhaseTwoTest, AssignPrepareBallotsRespectsViewingID) { - const std::string shared_surveyor_id = - "Ad5pNzrwhWokTOR8/hC83LWJfEy8aY7mFwPQWe6CpRF"; - const std::vector surveyors = { - "{\"surveyorId\":\"" + shared_surveyor_id + "\"}" - }; - - // Create ballots with different viewing IDs but the same surveyor ID. - ledger::Ballots ballots(2); - ballots[0].viewing_id = "00000000-0000-0000-0000-000000000000"; - ballots[0].surveyor_id = shared_surveyor_id; - ballots[1].viewing_id = "ffffffff-ffff-ffff-ffff-ffffffffffff"; - ballots[1].surveyor_id = shared_surveyor_id; - - // Check that only ballot[0] with the matching viewing ID is updated. Ballot 1 - // should remain unmodified. - PhaseTwo::AssignPrepareBallots("00000000-0000-0000-0000-000000000000", - surveyors, &ballots); - ASSERT_FALSE(ballots[0].prepare_ballot.empty()); - ASSERT_TRUE(ballots[1].prepare_ballot.empty()); -} - -// Surveyor IDs may be reused between transactions. Ensure that proofs for -// ballots for one viewing ID will not be assigned to ballots for another -// viewing ID, even if they share a surveyor ID. -TEST_F(PhaseTwoTest, AssignProofsRespectsViewingID) { - const std::vector proofs = { "proof 1", "proof 2" }; - const std::string shared_surveyor_id = - "Ad5pNzrwhWokTOR8/hC83LWJfEy8aY7mFwPQWe6CpRF"; - - ledger::Ballots ballots(2); - ballots[0].viewing_id = "00000000-0000-0000-0000-000000000000"; - ballots[0].surveyor_id = shared_surveyor_id; - ballots[1].viewing_id = "ffffffff-ffff-ffff-ffff-ffffffffffff"; - ballots[1].surveyor_id = shared_surveyor_id; - - ledger::BatchProofs batch_proofs(2); - batch_proofs[0].ballot = ballots[0]; - batch_proofs[1].ballot = ballots[1]; - - PhaseTwo::AssignProofs(batch_proofs, proofs, &ballots); - ASSERT_EQ(ballots[0].proof_ballot, proofs[0]); - ASSERT_EQ(ballots[1].proof_ballot, proofs[1]); -} - -} // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.cc index a17b4185054e..596a85bbaa35 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.cc @@ -110,7 +110,7 @@ void Unverified::OnContributeUnverifiedPublishers( queue->partial = false; queue->publishers = std::move(queue_list); - contribution_->InitReconcile(std::move(queue)); + contribution_->Start(std::move(queue)); ledger_->RemovePendingContribution( current->id, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials.h b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials.h index ccdb642f0fdd..ef313f3d347a 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials.h @@ -10,15 +10,11 @@ #include #include "bat/ledger/ledger.h" +#include "bat/ledger/internal/credentials/credentials_redeem.h" +#include "bat/ledger/internal/credentials/credentials_trigger.h" namespace braveledger_credentials { -struct CredentialsTrigger { - std::string id; - ledger::CredsBatchType type; - int size; -}; - class Credentials { public: virtual ~Credentials() = default; @@ -27,6 +23,11 @@ class Credentials { const CredentialsTrigger& trigger, ledger::ResultCallback callback) = 0; + virtual void RedeemTokens( + const CredentialsRedeem& redeem, + ledger::ResultCallback callback) = 0; + + protected: virtual void Blind( const CredentialsTrigger& trigger, ledger::ResultCallback callback) = 0; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.cc index 0ef76fc4ea06..7e0d3d1ba5e3 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.cc @@ -9,19 +9,17 @@ #include "base/values.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" +#include "base/strings/string_number_conversions.h" #include "bat/ledger/internal/credentials/credentials_common.h" #include "bat/ledger/internal/credentials/credentials_util.h" #include "bat/ledger/internal/ledger_impl.h" - -#include "wrapper.hpp" // NOLINT +#include "bat/ledger/internal/request/request_promotion.h" +#include "bat/ledger/internal/request/request_util.h" +#include "net/http/http_status_code.h" using std::placeholders::_1; - -using challenge_bypass_ristretto::BatchDLEQProof; -using challenge_bypass_ristretto::BlindedToken; -using challenge_bypass_ristretto::PublicKey; -using challenge_bypass_ristretto::SignedToken; -using challenge_bypass_ristretto::UnblindedToken; +using std::placeholders::_2; +using std::placeholders::_3; namespace { @@ -114,7 +112,13 @@ void CredentialsCommon::BlindedCredsSaved( const ledger::Result result, const std::string& blinded_creds_json, BlindedCredsCallback callback) { - callback(result, blinded_creds_json); + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Creds batch save failed"; + callback(ledger::Result::RETRY, ""); + return; + } + + callback(ledger::Result::LEDGER_OK, blinded_creds_json); } void CredentialsCommon::GetSignedCredsFromResponse( @@ -126,7 +130,7 @@ void CredentialsCommon::GetSignedCredsFromResponse( if (parsed_response.DictSize() != 3) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Parsing failed"; - callback(ledger::Result::LEDGER_ERROR); + callback(ledger::Result::RETRY); return; } @@ -174,6 +178,12 @@ void CredentialsCommon::OnSaveUnblindedCreds( const ledger::Result result, const CredentialsTrigger& trigger, ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Token list not saved"; + callback(ledger::Result::RETRY); + return; + } + ledger_->UpdateCredsBatchStatus( trigger.id, trigger.type, @@ -181,4 +191,68 @@ void CredentialsCommon::OnSaveUnblindedCreds( callback); } +void CredentialsCommon::RedeemTokens( + const CredentialsRedeem& redeem, + ledger::ResultCallback callback) { + if (redeem.publisher_key.empty() || redeem.token_list.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Pub key / token list empty"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + std::vector token_id_list; + for (const auto & item : redeem.token_list) { + token_id_list.push_back(base::NumberToString(item.id)); + } + + auto url_callback = std::bind(&CredentialsCommon::OnRedeemTokens, + this, + _1, + _2, + _3, + token_id_list, + callback); + + std::string payload; + std::string url; + std::vector headers; + if (redeem.type == ledger::RewardsType::TRANSFER) { + payload = GenerateTransferTokensPayload(redeem, ledger_->GetPaymentId()); + url = braveledger_request_util::GetTransferTokens(); + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); + headers = braveledger_request_util::BuildSignHeaders( + "post /v1/suggestions/claim", + payload, + ledger_->GetPaymentId(), + wallet_info.key_info_seed); + } else { + payload = GenerateRedeemTokensPayload(redeem); + url = braveledger_request_util::GetReedemTokensUrl(redeem.processor); + } + + ledger_->LoadURL( + url, + headers, + payload, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void CredentialsCommon::OnRedeemTokens( + const int response_status_code, + const std::string& response, + const std::map& headers, + const std::vector& token_id_list, + ledger::ResultCallback callback) { + ledger_->LogResponse(__func__, response_status_code, response, headers); + + if (response_status_code != net::HTTP_OK) { + callback(ledger::Result::LEDGER_ERROR); + return; + } + + ledger_->DeleteUnblindedTokens(token_id_list, callback); +} + } // namespace braveledger_credentials diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.h b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.h index b92da30c6401..2884102730c1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_common.h @@ -8,6 +8,7 @@ #include +#include #include #include @@ -45,6 +46,10 @@ class CredentialsCommon { const CredentialsTrigger& trigger, ledger::ResultCallback callback); + void RedeemTokens( + const CredentialsRedeem& redeem, + ledger::ResultCallback callback); + private: void BlindedCredsSaved( const ledger::Result result, @@ -56,6 +61,13 @@ class CredentialsCommon { const CredentialsTrigger& trigger, ledger::ResultCallback callback); + void OnRedeemTokens( + const int response_status_code, + const std::string& response, + const std::map& headers, + const std::vector& token_id_list, + ledger::ResultCallback callback); + bat_ledger::LedgerImpl* ledger_; // NOT OWNED }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_factory.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_factory.cc index 05afb1fa0190..6d9e35324a46 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_factory.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_factory.cc @@ -5,6 +5,7 @@ #include "bat/ledger/internal/credentials/credentials_factory.h" #include "bat/ledger/internal/credentials/credentials_promotion.h" +#include "bat/ledger/internal/credentials/credentials_sku.h" #include "bat/ledger/internal/ledger_impl.h" namespace braveledger_credentials { @@ -22,6 +23,10 @@ std::unique_ptr CredentialsFactory::Create( case ledger::CredsBatchType::PROMOTION: { return std::make_unique(ledger); } + + case ledger::CredsBatchType::SKU: { + return std::make_unique(ledger); + } } } 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 3fbf9dbf36c5..b588709e4a5c 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 @@ -123,7 +123,7 @@ void CredentialsPromotion::Claim( const CredentialsTrigger& trigger, ledger::ResultCallback callback) { if (result != ledger::Result::LEDGER_OK) { - callback(result); + callback(ledger::Result::LEDGER_ERROR); return; } @@ -418,4 +418,10 @@ void CredentialsPromotion::Completed( ledger_->UnblindedTokensReady(); } +void CredentialsPromotion::RedeemTokens( + const CredentialsRedeem& redeem, + ledger::ResultCallback callback) { + common_->RedeemTokens(redeem, callback); +} + } // namespace braveledger_credentials diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.h b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.h index f1c9713ed074..97ec242d31f8 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_promotion.h @@ -24,6 +24,10 @@ class CredentialsPromotion : public Credentials { const CredentialsTrigger& trigger, ledger::ResultCallback callback) override; + void RedeemTokens( + const CredentialsRedeem& redeem, + ledger::ResultCallback callback) override; + private: void OnStart( ledger::CredsBatchPtr creds, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_redeem.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_redeem.cc new file mode 100644 index 000000000000..04273043841d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_redeem.cc @@ -0,0 +1,17 @@ +/* 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/credentials/credentials_redeem.h" + +namespace braveledger_credentials { + +CredentialsRedeem::CredentialsRedeem() = default; + +CredentialsRedeem::CredentialsRedeem( + const CredentialsRedeem& info) = default; + +CredentialsRedeem::~CredentialsRedeem() = default; + +} // namespace braveledger_credentials diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_redeem.h b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_redeem.h new file mode 100644 index 000000000000..02a62e27deb8 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_redeem.h @@ -0,0 +1,30 @@ +/* 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_CREDENTIALS_CREDENTIALS_REDEEM_H_ +#define BRAVELEDGER_CREDENTIALS_CREDENTIALS_REDEEM_H_ + +#include +#include + +#include "bat/ledger/ledger.h" + +namespace braveledger_credentials { + +struct CredentialsRedeem { + CredentialsRedeem(); + CredentialsRedeem(const CredentialsRedeem& info); + ~CredentialsRedeem(); + + std::string publisher_key; + ledger::RewardsType type; + ledger::ContributionProcessor processor; + std::vector token_list; + std::string order_id; +}; + +} // namespace braveledger_credentials + +#endif // BRAVELEDGER_CREDENTIALS_CREDENTIALS_REDEEM_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_sku.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_sku.cc new file mode 100644 index 000000000000..a98170c6e2f0 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_sku.cc @@ -0,0 +1,379 @@ +/* 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 + +#include +#include +#include + +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/credentials/credentials_sku.h" +#include "bat/ledger/internal/credentials/credentials_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_sku.h" +#include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/static_values.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; +using std::placeholders::_2; +using std::placeholders::_3; + +namespace { + +bool IsPublicKeyValid(const std::string& public_key) { + if (public_key.empty()) { + return false; + } + + std::vector keys; + if (ledger::_environment == ledger::Environment::PRODUCTION) { + keys = { + "yr4w9Y0XZQISBOToATNEl5ADspDUgm7cBSOhfYgPWx4=", // AC + "PGLvfpIn8QXuQJEtv2ViQSWw2PppkhexKr1mlvwCpnM=" // User funds + }; + } + + if (ledger::_environment == ledger::Environment::STAGING) { + keys = { + "mMMWZrWPlO5b9IB8vF5kUJW4f7ULH1wuEop3NOYqNW0=", // AC + "CMezK92X5wmYHVYpr22QhNsTTq6trA/N9Alw+4cKyUY=" // User funds + }; + } + + if (ledger::_environment == ledger::Environment::DEVELOPMENT) { + keys = { + "RhfxGp4pT0Kqe2zx4+q+L6lwC3G9v3fIj1L+PbINNzw=", // AC + "nsSoWgGMJpIiCGVdYrne03ldQ4zqZOMERVD5eSPhhxc=" // User funds + }; + } + + auto it = std::find(keys.begin(), keys.end(), public_key); + + return it != keys.end(); +} + +std::string ConvertItemTypeToString(const std::string& type) { + int type_int; + base::StringToInt(type, &type_int); + switch (static_cast(type_int)) { + case ledger::SKUOrderItemType::SINGLE_USE: { + return "single-use"; + } + case ledger::SKUOrderItemType::NONE: { + return ""; + } + } +} + +} // namespace + +namespace braveledger_credentials { + +CredentialsSKU::CredentialsSKU(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), + common_(std::make_unique(ledger)) { + DCHECK(ledger_ && common_); +} + +CredentialsSKU::~CredentialsSKU() = default; + +void CredentialsSKU::Start( + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + DCHECK_EQ(trigger.data.size(), 2ul); + if (trigger.data.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Trigger data is missing"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto get_callback = std::bind(&CredentialsSKU::OnStart, + this, + _1, + trigger, + callback); + + ledger_->GetCredsBatchByTrigger(trigger.id, trigger.type, get_callback); +} + +void CredentialsSKU::OnStart( + ledger::CredsBatchPtr creds, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + ledger::CredsBatchStatus status = ledger::CredsBatchStatus::NONE; + if (creds) { + status = creds->status; + } + + switch (status) { + case ledger::CredsBatchStatus::NONE: + case ledger::CredsBatchStatus::BLINDED: { + Blind(trigger, callback); + break; + } + case ledger::CredsBatchStatus::CLAIMED: { + FetchSignedCreds(trigger, callback); + break; + } + case ledger::CredsBatchStatus::SIGNED: { + auto get_callback = std::bind(&CredentialsSKU::Unblind, + this, + _1, + trigger, + callback); + ledger_->GetCredsBatchByTrigger(trigger.id, trigger.type, get_callback); + break; + } + case ledger::CredsBatchStatus::FINISHED: { + callback(ledger::Result::LEDGER_OK); + break; + } + } +} + +void CredentialsSKU::Blind( + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + auto blinded_callback = std::bind(&CredentialsSKU::Claim, + this, + _1, + _2, + trigger, + callback); + common_->GetBlindedCreds(trigger, blinded_callback); +} + +void CredentialsSKU::Claim( + const ledger::Result result, + const std::string& blinded_creds_json, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Claim failed"; + callback(result); + return; + } + + auto blinded_creds = ParseStringToBaseList(blinded_creds_json); + + if (!blinded_creds || blinded_creds->empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Blinded creds are corrupted"; + callback(ledger::Result::RETRY); + return; + } + + DCHECK_EQ(trigger.data.size(), 2ul); + base::Value body(base::Value::Type::DICTIONARY); + body.SetStringKey("itemId", trigger.data[0]); + body.SetStringKey("type", ConvertItemTypeToString(trigger.data[1])); + body.SetKey("blindedCreds", base::Value(std::move(*blinded_creds))); + + std::string json; + base::JSONWriter::Write(body, &json); + + const std::string sign_url = base::StringPrintf( + "post /v1/orders/%s/credentials", + trigger.id.c_str()); + + const std::string url = + braveledger_request_util::GetOrderCredentialsURL(trigger.id); + auto url_callback = std::bind(&CredentialsSKU::OnClaim, + this, + _1, + _2, + _3, + trigger, + callback); + + ledger_->LoadURL( + url, + std::vector(), + json, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void CredentialsSKU::OnClaim( + const int response_status_code, + const std::string& response, + const std::map& headers, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + ledger_->LogResponse(__func__, response_status_code, response, headers); + + if (response_status_code != net::HTTP_OK) { + callback(ledger::Result::RETRY); + return; + } + + auto save_callback = std::bind(&CredentialsSKU::ClaimStatusSaved, + this, + _1, + trigger, + callback); + + ledger_->UpdateCredsBatchStatus( + trigger.id, + trigger.type, + ledger::CredsBatchStatus::CLAIMED, + save_callback); +} + +void CredentialsSKU::ClaimStatusSaved( + const ledger::Result result, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Claim status not saved"; + callback(ledger::Result::RETRY); + return; + } + + FetchSignedCreds(trigger, callback); +} + +void CredentialsSKU::FetchSignedCreds( + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + const std::string url = braveledger_request_util::GetOrderCredentialsURL( + trigger.id, + trigger.data[0]); + auto url_callback = std::bind(&CredentialsSKU::OnFetchSignedCreds, + this, + _1, + _2, + _3, + trigger, + callback); + + ledger_->LoadURL( + url, + std::vector(), + "", + "", + ledger::UrlMethod::GET, + url_callback); +} + +void CredentialsSKU::OnFetchSignedCreds( + const int response_status_code, + const std::string& response, + const std::map& headers, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + ledger_->LogResponse(__func__, response_status_code, response, headers); + + if (response_status_code == net::HTTP_ACCEPTED) { + callback(ledger::Result::RETRY_SHORT); + return; + } + + if (response_status_code != net::HTTP_OK) { + callback(ledger::Result::RETRY); + return; + } + + auto get_callback = std::bind(&CredentialsSKU::SignedCredsSaved, + this, + _1, + trigger, + callback); + common_->GetSignedCredsFromResponse(trigger, response, get_callback); +} + +void CredentialsSKU::SignedCredsSaved( + const ledger::Result result, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Signed creds were not saved"; + callback(ledger::Result::RETRY); + return; + } + + auto get_callback = std::bind(&CredentialsSKU::Unblind, + this, + _1, + trigger, + callback); + ledger_->GetCredsBatchByTrigger(trigger.id, trigger.type, get_callback); +} + +void CredentialsSKU::Unblind( + ledger::CredsBatchPtr creds, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + if (!creds) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Corrupted data"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + if (!IsPublicKeyValid(creds->public_key)) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Public key is not valid"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + std::vector unblinded_encoded_creds; + std::string error; + bool result; + if (ledger::is_testing) { + result = UnBlindCredsMock(*creds, &unblinded_encoded_creds); + } else { + result = UnBlindCreds(*creds, &unblinded_encoded_creds, &error); + } + + if (!result) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "UnBlindTokens: " << error; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto save_callback = std::bind(&CredentialsSKU::Completed, + this, + _1, + trigger, + callback); + + const uint64_t expires_at = 0ul; + + common_->SaveUnblindedCreds( + expires_at, + braveledger_ledger::_vote_price, + *creds, + unblinded_encoded_creds, + trigger, + save_callback); +} + +void CredentialsSKU::Completed( + const ledger::Result result, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Unblinded token save failed"; + callback(result); + return; + } + + ledger_->UnblindedTokensReady(); + callback(result); +} + +void CredentialsSKU::RedeemTokens( + const CredentialsRedeem& redeem, + ledger::ResultCallback callback) { + common_->RedeemTokens(redeem, callback); +} + +} // namespace braveledger_credentials diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_sku.h b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_sku.h new file mode 100644 index 000000000000..52c5625a5e1d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_sku.h @@ -0,0 +1,90 @@ +/* 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_CREDENTIALS_SKU_H_ +#define BRAVELEDGER_CREDENTIALS_SKU_H_ + +#include +#include +#include + +#include "bat/ledger/internal/credentials/credentials_common.h" + +namespace braveledger_credentials { + +class CredentialsSKU : public Credentials { + public: + explicit CredentialsSKU(bat_ledger::LedgerImpl* ledger); + ~CredentialsSKU() override; + + void Start( + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) override; + + void RedeemTokens( + const CredentialsRedeem& redeem, + ledger::ResultCallback callback) override; + + private: + void OnStart( + ledger::CredsBatchPtr creds, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback); + + void Blind( + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) override; + + void Claim( + const ledger::Result result, + const std::string& blinded_creds_json, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) override; + + void OnClaim( + const int response_status_code, + const std::string& response, + const std::map& headers, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback); + + void ClaimStatusSaved( + const ledger::Result result, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback); + + void FetchSignedCreds( + const CredentialsTrigger& trigger, + ledger::ResultCallback callback); + + void OnFetchSignedCreds( + const int response_status_code, + const std::string& response, + const std::map& headers, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback); + + void SignedCredsSaved( + const ledger::Result result, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback); + + void Unblind( + ledger::CredsBatchPtr creds, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) override; + + void Completed( + const ledger::Result result, + const CredentialsTrigger& trigger, + ledger::ResultCallback callback) override; + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr common_; +}; + +} // namespace braveledger_credentials + +#endif // BRAVELEDGER_CREDENTIALS_SKU_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_trigger.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_trigger.cc new file mode 100644 index 000000000000..f2677d01574f --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_trigger.cc @@ -0,0 +1,17 @@ +/* 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/credentials/credentials_trigger.h" + +namespace braveledger_credentials { + +CredentialsTrigger::CredentialsTrigger() = default; + +CredentialsTrigger::CredentialsTrigger( + const CredentialsTrigger& info) = default; + +CredentialsTrigger::~CredentialsTrigger() = default; + +} // namespace braveledger_credentials diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_trigger.h b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_trigger.h new file mode 100644 index 000000000000..bcfc86b8416b --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_trigger.h @@ -0,0 +1,29 @@ +/* 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_CREDENTIALS_CREDENTIALS_TRIGGER_H_ +#define BRAVELEDGER_CREDENTIALS_CREDENTIALS_TRIGGER_H_ + +#include +#include + +#include "bat/ledger/ledger.h" + +namespace braveledger_credentials { + +struct CredentialsTrigger { + CredentialsTrigger(); + CredentialsTrigger(const CredentialsTrigger& info); + ~CredentialsTrigger(); + + std::string id; + ledger::CredsBatchType type; + int size; + std::vector data; +}; + +} // namespace braveledger_credentials + +#endif // BRAVELEDGER_CREDENTIALS_CREDENTIALS_TRIGGER_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.cc index 88dc01301230..658752902fc7 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.cc @@ -5,6 +5,7 @@ #include +#include "base/base64.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "bat/ledger/internal/credentials/credentials_util.h" @@ -12,11 +13,11 @@ #include "wrapper.hpp" // NOLINT using challenge_bypass_ristretto::BatchDLEQProof; -using challenge_bypass_ristretto::BlindedToken; using challenge_bypass_ristretto::PublicKey; using challenge_bypass_ristretto::SignedToken; -using challenge_bypass_ristretto::Token; using challenge_bypass_ristretto::UnblindedToken; +using challenge_bypass_ristretto::VerificationKey; +using challenge_bypass_ristretto::VerificationSignature; namespace braveledger_credentials { @@ -39,9 +40,9 @@ std::string GetCredsJSON(const std::vector& creds) { auto cred_value = base::Value(cred_base64); creds_list.Append(std::move(cred_value)); } + std::string json; base::JSONWriter::Write(creds_list, &json); - return json; } @@ -67,9 +68,9 @@ std::string GetBlindedCredsJSON( auto cred_value = base::Value(cred_base64); blinded_list.Append(std::move(cred_value)); } + std::string json; base::JSONWriter::Write(blinded_list, &json); - return json; } @@ -87,10 +88,7 @@ bool UnBlindCreds( const ledger::CredsBatch& creds_batch, std::vector* unblinded_encoded_creds, std::string* error) { - DCHECK(error); - if (!unblinded_encoded_creds) { - return false; - } + DCHECK(error && unblinded_encoded_creds); auto batch_proof = BatchDLEQProof::decode_base64(creds_batch.batch_proof); @@ -173,9 +171,7 @@ bool UnBlindCreds( bool UnBlindCredsMock( const ledger::CredsBatch& creds, std::vector* unblinded_encoded_creds) { - if (!unblinded_encoded_creds) { - return false; - } + DCHECK(unblinded_encoded_creds); auto signed_creds_base64 = ParseStringToBaseList(creds.signed_creds); @@ -186,4 +182,141 @@ bool UnBlindCredsMock( return true; } +std::string ConvertRewardTypeToString(const ledger::RewardsType type) { + switch (type) { + case ledger::RewardsType::AUTO_CONTRIBUTE: { + return "auto-contribute"; + } + case ledger::RewardsType::ONE_TIME_TIP: { + return "oneoff-tip"; + } + case ledger::RewardsType::RECURRING_TIP: { + return "recurring-tip"; + } + case ledger::RewardsType::PAYMENT: { + return "payment"; + } + case ledger::RewardsType::TRANSFER: { + return ""; + } + } +} + +void GenerateCredentials( + const std::vector& token_list, + const std::string& body, + base::Value* credentials) { + DCHECK(credentials); + + for (auto& item : token_list) { + base::Value token(base::Value::Type::DICTIONARY); + bool success; + if (ledger::is_testing) { + success = GenerateSuggestionMock( + item.token_value, + item.public_key, + body, + &token); + } else { + success = GenerateSuggestion( + item.token_value, + item.public_key, + body, + &token); + } + + if (!success) { + continue; + } + + credentials->Append(std::move(token)); + } +} + +bool GenerateSuggestion( + const std::string& token_value, + const std::string& public_key, + const std::string& body, + base::Value* result) { + DCHECK(result); + if (token_value.empty() || public_key.empty() || body.empty()) { + return false; + } + + UnblindedToken unblinded = UnblindedToken::decode_base64(token_value); + VerificationKey verification_key = unblinded.derive_verification_key(); + VerificationSignature signature = verification_key.sign(body); + const std::string pre_image = unblinded.preimage().encode_base64(); + + if (challenge_bypass_ristretto::exception_occurred()) { + challenge_bypass_ristretto::TokenException e = + challenge_bypass_ristretto::get_last_exception(); + return false; + } + + result->SetStringKey("t", pre_image); + result->SetStringKey("publicKey", public_key); + result->SetStringKey("signature", signature.encode_base64()); + return true; +} + +bool GenerateSuggestionMock( + const std::string& token_value, + const std::string& public_key, + const std::string& body, + base::Value* result) { + DCHECK(result); + result->SetStringKey("t", token_value); + result->SetStringKey("publicKey", public_key); + result->SetStringKey("signature", token_value); + return true; +} + +std::string GenerateRedeemTokensPayload(const CredentialsRedeem& redeem) { + base::Value data(base::Value::Type::DICTIONARY); + data.SetStringKey( + "type", + ConvertRewardTypeToString(redeem.type)); + if (!redeem.order_id.empty()) { + data.SetStringKey("orderId", redeem.order_id); + } + data.SetStringKey("channel", redeem.publisher_key); + + const bool is_sku = + redeem.processor == ledger::ContributionProcessor::UPHOLD || + redeem.processor == ledger::ContributionProcessor::BRAVE_USER_FUNDS; + + std::string data_json; + base::JSONWriter::Write(data, &data_json); + std::string data_encoded; + base::Base64Encode(data_json, &data_encoded); + + base::Value credentials(base::Value::Type::LIST); + GenerateCredentials(redeem.token_list, data_encoded, &credentials); + + const std::string data_key = is_sku ? "vote" : "suggestion"; + base::Value payload(base::Value::Type::DICTIONARY); + payload.SetStringKey(data_key, data_encoded); + payload.SetKey("credentials", std::move(credentials)); + + std::string json; + base::JSONWriter::Write(payload, &json); + return json; +} + +std::string GenerateTransferTokensPayload( + const CredentialsRedeem& redeem, + const std::string& payment_id) { + base::Value credentials(base::Value::Type::LIST); + GenerateCredentials(redeem.token_list, payment_id, &credentials); + + base::Value body(base::Value::Type::DICTIONARY); + body.SetStringKey("paymentId", payment_id); + body.SetKey("credentials", std::move(credentials)); + + std::string json; + base::JSONWriter::Write(body, &json); + return json; +} + } // namespace braveledger_credentials diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.h index bcaa10445daa..5bd01867e34d 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/credentials/credentials_util.h @@ -3,14 +3,15 @@ * 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_CREDENTIALS_CREDENTIALS_HELPER_H_ -#define BRAVELEDGER_CREDENTIALS_CREDENTIALS_HELPER_H_ +#ifndef BRAVELEDGER_CREDENTIALS_CREDENTIALS_UTIL_H_ +#define BRAVELEDGER_CREDENTIALS_CREDENTIALS_UTIL_H_ #include #include #include #include "base/values.h" +#include "bat/ledger/internal/credentials/credentials_redeem.h" #include "bat/ledger/mojom_structs.h" #include "wrapper.hpp" @@ -40,6 +41,31 @@ namespace braveledger_credentials { const ledger::CredsBatch& creds, std::vector* unblinded_encoded_creds); + std::string ConvertRewardTypeToString(const ledger::RewardsType type); + + void GenerateCredentials( + const std::vector& token_list, + const std::string& body, + base::Value* credentials); + + bool GenerateSuggestion( + const std::string& token_value, + const std::string& public_key, + const std::string& suggestion_encoded, + base::Value* result); + + bool GenerateSuggestionMock( + const std::string& token_value, + const std::string& public_key, + const std::string& suggestion_encoded, + base::Value* result); + + std::string GenerateRedeemTokensPayload(const CredentialsRedeem& redeem); + + std::string GenerateTransferTokensPayload( + const CredentialsRedeem& redeem, + const std::string& payment_id); + } // namespace braveledger_credentials -#endif // BRAVELEDGER_CREDENTIALS_CREDENTIALS_HELPER_H_ +#endif // BRAVELEDGER_CREDENTIALS_CREDENTIALS_UTIL_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc index b2c295bd8eaf..4e474c2b6102 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc @@ -18,6 +18,8 @@ #include "bat/ledger/internal/database/database_publisher_info.h" #include "bat/ledger/internal/database/database_recurring_tip.h" #include "bat/ledger/internal/database/database_server_publisher_info.h" +#include "bat/ledger/internal/database/database_sku_order.h" +#include "bat/ledger/internal/database/database_sku_transaction.h" #include "bat/ledger/internal/database/database_unblinded_token.h" #include "bat/ledger/internal/ledger_impl.h" @@ -42,6 +44,8 @@ Database::Database(bat_ledger::LedgerImpl* ledger) : recurring_tip_ = std::make_unique(ledger_); server_publisher_info_ = std::make_unique(ledger_); + sku_transaction_ = std::make_unique(ledger_); + sku_order_ = std::make_unique(ledger_); unblinded_token_ = std::make_unique(ledger_); } @@ -119,10 +123,19 @@ void Database::GetContributionReport( contribution_info_->GetContributionReport(month, year, callback); } -void Database::GetIncompleteContributions( - const ledger::ContributionProcessor processor, +void Database::GetNotCompletedContributions( ledger::ContributionInfoListCallback callback) { - contribution_info_->GetIncompletedRecords(processor, callback); + contribution_info_->GetNotCompletedRecords(callback); +} + +void Database::UpdateContributionInfoStep( + const std::string& contribution_id, + const ledger::ContributionStep step, + ledger::ResultCallback callback) { + contribution_info_->UpdateStep( + contribution_id, + step, + callback); } void Database::UpdateContributionInfoStepAndCount( @@ -387,6 +400,69 @@ void Database::GetServerPublisherInfo( server_publisher_info_->GetRecord(publisher_key, callback); } +/** + * SKU ORDER + */ +void Database::SaveSKUOrder( + ledger::SKUOrderPtr order, + ledger::ResultCallback callback) { + sku_order_->InsertOrUpdate(std::move(order), callback); +} + +void Database::UpdateSKUOrderStatus( + const std::string& order_id, + const ledger::SKUOrderStatus status, + ledger::ResultCallback callback) { + sku_order_->UpdateStatus(order_id, status, callback); +} + +void Database::GetSKUOrder( + const std::string& order_id, + ledger::GetSKUOrderCallback callback) { + sku_order_->GetRecord(order_id, callback); +} + +void Database::GetSKUOrderByContributionId( + const std::string& contribution_id, + ledger::GetSKUOrderCallback callback) { + sku_order_->GetRecordByContributionId(contribution_id, callback); +} + +void Database::SaveContributionIdForSKUOrder( + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback) { + sku_order_->SaveContributionIdForSKUOrder( + order_id, + contribution_id, + callback); +} + +/** + * SKU TRANSACTION + */ +void Database::SaveSKUTransaction( + ledger::SKUTransactionPtr transaction, + ledger::ResultCallback callback) { + sku_transaction_->InsertOrUpdate(std::move(transaction), callback); +} + +void Database::SaveSKUExternalTransaction( + const std::string& transaction_id, + const std::string& external_transaction_id, + ledger::ResultCallback callback) { + sku_transaction_->SaveExternalTransaction( + transaction_id, + external_transaction_id, + callback); +} + +void Database::GetSKUTransactionByOrderId( + const std::string& order_id, + ledger::GetSKUTransactionCallback callback) { + sku_transaction_->GetRecordByOrderId(order_id, callback); +} + /** * UNBLINDED TOKEN */ @@ -396,11 +472,6 @@ void Database::SaveUnblindedTokenList( unblinded_token_->InsertOrUpdateList(std::move(list), callback); } -void Database::GetAllUnblindedTokens( - ledger::GetUnblindedTokenListCallback callback) { - unblinded_token_->GetAllRecords(callback); -} - void Database::DeleteUnblindedTokens( const std::vector& ids, ledger::ResultCallback callback) { @@ -418,4 +489,10 @@ void Database::CheckUnblindedTokensExpiration( unblinded_token_->CheckRecordsExpiration(callback); } +void Database::GetUnblindedTokensByBatchTypes( + const std::vector& batch_types, + ledger::GetUnblindedTokenListCallback callback) { + unblinded_token_->GetRecordsByBatchTypes(batch_types, callback); +} + } // namespace braveledger_database diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h index 19e47d09d3b7..7fa9eaa27550 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h @@ -32,6 +32,8 @@ class DatabasePromotion; class DatabasePublisherInfo; class DatabaseRecurringTip; class DatabaseServerPublisherInfo; +class DatabaseSKUOrder; +class DatabaseSKUTransaction; class DatabaseUnblindedToken; class Database { @@ -85,10 +87,14 @@ class Database { const int year, ledger::GetContributionReportCallback callback); - void GetIncompleteContributions( - const ledger::ContributionProcessor processor, + void GetNotCompletedContributions( ledger::ContributionInfoListCallback callback); + void UpdateContributionInfoStep( + const std::string& contribution_id, + const ledger::ContributionStep step, + ledger::ResultCallback callback); + void UpdateContributionInfoStepAndCount( const std::string& contribution_id, const ledger::ContributionStep step, @@ -268,6 +274,45 @@ class Database { const std::string& publisher_key, ledger::GetServerPublisherInfoCallback callback); + /** + * SKU ORDER + */ + void SaveSKUOrder(ledger::SKUOrderPtr order, ledger::ResultCallback callback); + + void UpdateSKUOrderStatus( + const std::string& order_id, + const ledger::SKUOrderStatus status, + ledger::ResultCallback callback); + + void GetSKUOrder( + const std::string& order_id, + ledger::GetSKUOrderCallback callback); + + void GetSKUOrderByContributionId( + const std::string& contribution_id, + ledger::GetSKUOrderCallback callback); + + void SaveContributionIdForSKUOrder( + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback); + + /** + * SKU TRANSACTION + */ + void SaveSKUTransaction( + ledger::SKUTransactionPtr transaction, + ledger::ResultCallback callback); + + void SaveSKUExternalTransaction( + const std::string& transaction_id, + const std::string& external_transaction_id, + ledger::ResultCallback callback); + + void GetSKUTransactionByOrderId( + const std::string& order_id, + ledger::GetSKUTransactionCallback callback); + /** * UNBLINDED TOKEN */ @@ -275,9 +320,6 @@ class Database { ledger::UnblindedTokenList list, ledger::ResultCallback callback); - void GetAllUnblindedTokens( - ledger::GetUnblindedTokenListCallback callback); - void DeleteUnblindedTokens( const std::vector& ids, ledger::ResultCallback callback); @@ -288,6 +330,11 @@ class Database { void CheckUnblindedTokensExpiration(ledger::ResultCallback callback); + void GetUnblindedTokensByBatchTypes( + const std::vector& batch_types, + ledger::GetUnblindedTokenListCallback callback); + + private: std::unique_ptr initialize_; std::unique_ptr activity_info_; @@ -301,6 +348,8 @@ class Database { std::unique_ptr publisher_info_; std::unique_ptr recurring_tip_; std::unique_ptr server_publisher_info_; + std::unique_ptr sku_order_; + std::unique_ptr sku_transaction_; std::unique_ptr unblinded_token_; bat_ledger::LedgerImpl* ledger_; // NOT OWNED }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc index 23e21f8e7957..08cedf99d0d3 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc @@ -762,23 +762,20 @@ void DatabaseContributionInfo::OnGetContributionReportPublishers( callback(std::move(report_list)); } -void DatabaseContributionInfo::GetIncompletedRecords( - const ledger::ContributionProcessor processor, +void DatabaseContributionInfo::GetNotCompletedRecords( ledger::ContributionInfoListCallback callback) { auto transaction = ledger::DBTransaction::New(); const std::string query = base::StringPrintf( "SELECT ci.contribution_id, ci.amount, ci.type, ci.step, ci.retry_count, " "ci.processor " - "FROM %s as ci WHERE ci.step > 0 AND ci.processor = ?", + "FROM %s as ci WHERE ci.step > 0", kTableName); auto command = ledger::DBCommand::New(); command->type = ledger::DBCommand::Type::READ; command->command = query; - BindInt(command.get(), 0, static_cast(processor)); - command->record_bindings = { ledger::DBCommand::RecordBindingType::STRING_TYPE, ledger::DBCommand::RecordBindingType::DOUBLE_TYPE, @@ -861,6 +858,37 @@ void DatabaseContributionInfo::OnGetListPublishers( callback(std::move(contribution_list)); } +void DatabaseContributionInfo::UpdateStep( + const std::string& contribution_id, + const ledger::ContributionStep step, + ledger::ResultCallback callback) { + if (contribution_id.empty()) { + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "UPDATE %s SET step=?, retry_count=0 WHERE contribution_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindInt(command.get(), 0, static_cast(step)); + BindString(command.get(), 1, contribution_id); + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&OnResultCallback, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + void DatabaseContributionInfo::UpdateStepAndCount( const std::string& contribution_id, const ledger::ContributionStep step, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h index 6a27c0b83518..fdad9af2bc5f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h @@ -42,9 +42,12 @@ class DatabaseContributionInfo: public DatabaseTable { const int year, ledger::GetContributionReportCallback callback); - void GetIncompletedRecords( - const ledger::ContributionProcessor processor, - ledger::ContributionInfoListCallback callback); + void GetNotCompletedRecords(ledger::ContributionInfoListCallback callback); + + void UpdateStep( + const std::string& contribution_id, + const ledger::ContributionStep step, + ledger::ResultCallback callback); void UpdateStepAndCount( const std::string& contribution_id, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.cc index 45abf1fad55c..e47e9b84eab7 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.cc @@ -17,6 +17,8 @@ #include "bat/ledger/internal/database/database_publisher_info.h" #include "bat/ledger/internal/database/database_recurring_tip.h" #include "bat/ledger/internal/database/database_server_publisher_info.h" +#include "bat/ledger/internal/database/database_sku_order.h" +#include "bat/ledger/internal/database/database_sku_transaction.h" #include "bat/ledger/internal/database/database_unblinded_token.h" #include "bat/ledger/internal/database/database_util.h" #include "bat/ledger/internal/ledger_impl.h" @@ -40,6 +42,8 @@ DatabaseMigration::DatabaseMigration(bat_ledger::LedgerImpl* ledger) : recurring_tip_ = std::make_unique(ledger_); server_publisher_info_ = std::make_unique(ledger_); + sku_order_ = std::make_unique(ledger_); + sku_transaction_ = std::make_unique(ledger_); unblinded_token_ = std::make_unique(ledger_); } @@ -110,7 +114,6 @@ bool DatabaseMigration::Migrate( if (!media_publisher_info_->Migrate(transaction, target)) { return false; } - if (!pending_contribution_->Migrate(transaction, target)) { return false; } @@ -131,6 +134,15 @@ bool DatabaseMigration::Migrate( return false; } + if (!sku_order_->Migrate(transaction, target)) { + return false; + } + + + if (!sku_transaction_->Migrate(transaction, target)) { + return false; + } + if (!unblinded_token_->Migrate(transaction, target)) { return false; } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.h index 4090ab2ae43a..307cf643ef8d 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_migration.h @@ -26,6 +26,8 @@ class DatabasePromotion; class DatabasePublisherInfo; class DatabaseRecurringTip; class DatabaseServerPublisherInfo; +class DatabaseSKUOrder; +class DatabaseSKUTransaction; class DatabaseUnblindedToken; class DatabaseMigration { @@ -50,6 +52,8 @@ class DatabaseMigration { std::unique_ptr publisher_info_; std::unique_ptr recurring_tip_; std::unique_ptr server_publisher_info_; + std::unique_ptr sku_order_; + std::unique_ptr sku_transaction_; std::unique_ptr unblinded_token_; bat_ledger::LedgerImpl* ledger_; // NOT OWNED }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order.cc new file mode 100644 index 000000000000..52842badbe01 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order.cc @@ -0,0 +1,312 @@ +/* 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 + +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/common/bind_util.h" +#include "bat/ledger/internal/database/database_sku_order.h" +#include "bat/ledger/internal/database/database_util.h" +#include "bat/ledger/internal/ledger_impl.h" + +using std::placeholders::_1; + +namespace braveledger_database { + +namespace { + +const char kTableName[] = "sku_order"; + +} // namespace + +DatabaseSKUOrder::DatabaseSKUOrder( + bat_ledger::LedgerImpl* ledger) : + DatabaseTable(ledger), + items_(std::make_unique(ledger)) { +} + +DatabaseSKUOrder::~DatabaseSKUOrder() = default; + +bool DatabaseSKUOrder::CreateTableV19(ledger::DBTransaction* transaction) { + DCHECK(transaction); + + const std::string query = base::StringPrintf( + "CREATE TABLE %s (" + "order_id TEXT NOT NULL," + "total_amount DOUBLE," + "merchant_id TEXT," + "location TEXT," + "status INTEGER NOT NULL DEFAULT 0," + "contribution_id TEXT," + "created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (order_id)" + ")", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::EXECUTE; + command->command = query; + transaction->commands.push_back(std::move(command)); + + return true; +} + +bool DatabaseSKUOrder::Migrate( + ledger::DBTransaction* transaction, + const int target) { + DCHECK(transaction); + + switch (target) { + case 19: { + return MigrateToV19(transaction); + } + default: { + return true; + } + } +} + +bool DatabaseSKUOrder::MigrateToV19(ledger::DBTransaction* transaction) { + DCHECK(transaction); + + if (!DropTable(transaction, kTableName)) { + return false; + } + + if (!CreateTableV19(transaction)) { + return false; + } + + return items_->Migrate(transaction, 19); +} + +void DatabaseSKUOrder::InsertOrUpdate( + ledger::SKUOrderPtr order, + ledger::ResultCallback callback) { + if (!order) { + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "INSERT OR REPLACE INTO %s " + "(order_id, total_amount, merchant_id, location, status, " + "contribution_id) " + "VALUES (?, ?, ?, ?, ?, ?)", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindString(command.get(), 0, order->order_id); + BindDouble(command.get(), 1, order->total_amount); + BindString(command.get(), 2, order->merchant_id); + BindString(command.get(), 3, order->location); + BindInt(command.get(), 4, static_cast(order->status)); + BindString(command.get(), 5, order->contribution_id); + + transaction->commands.push_back(std::move(command)); + + items_->InsertOrUpdateList(transaction.get(), std::move(order->items)); + + auto transaction_callback = std::bind(&OnResultCallback, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +void DatabaseSKUOrder::UpdateStatus( + const std::string& order_id, + const ledger::SKUOrderStatus status, + ledger::ResultCallback callback) { + if (order_id.empty()) { + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "UPDATE %s SET status = ? WHERE order_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindInt(command.get(), 0, static_cast(status)); + BindString(command.get(), 1, order_id); + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&OnResultCallback, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +void DatabaseSKUOrder::GetRecord( + const std::string& order_id, + ledger::GetSKUOrderCallback callback) { + if (order_id.empty()) { + callback({}); + return; + } + + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "SELECT order_id, total_amount, merchant_id, location, status, " + "created_at FROM %s WHERE order_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::READ; + command->command = query; + + BindString(command.get(), 0, order_id); + + command->record_bindings = { + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::DOUBLE_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::INT_TYPE, + ledger::DBCommand::RecordBindingType::INT64_TYPE + }; + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&DatabaseSKUOrder::OnGetRecord, + this, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +void DatabaseSKUOrder::OnGetRecord( + ledger::DBCommandResponsePtr response, + ledger::GetSKUOrderCallback callback) { + if (!response || + response->status != ledger::DBCommandResponse::Status::RESPONSE_OK) { + callback({}); + return; + } + + if (response->result->get_records().size() != 1) { + callback({}); + return; + } + + auto* record = response->result->get_records()[0].get(); + auto info = ledger::SKUOrder::New(); + info->order_id = GetStringColumn(record, 0); + info->total_amount = GetDoubleColumn(record, 1); + info->merchant_id = GetStringColumn(record, 2); + info->location = GetStringColumn(record, 3); + info->status = static_cast(GetIntColumn(record, 4)); + info->created_at = GetInt64Column(record, 5); + + auto items_callback = std::bind(&DatabaseSKUOrder::OnGetRecordItems, + this, + _1, + braveledger_bind_util::FromSKUOrderToString(info->Clone()), + callback); + items_->GetRecordsByOrderId(info->order_id, items_callback); +} + +void DatabaseSKUOrder::OnGetRecordItems( + ledger::SKUOrderItemList list, + const std::string& order_string, + ledger::GetSKUOrderCallback callback) { + auto order = braveledger_bind_util::FromStringToSKUOrder(order_string); + if (!order) { + callback({}); + return; + } + + order->items = std::move(list); + callback(std::move(order)); +} + +void DatabaseSKUOrder::GetRecordByContributionId( + const std::string& contribution_id, + ledger::GetSKUOrderCallback callback) { + if (contribution_id.empty()) { + callback({}); + return; + } + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "SELECT order_id, total_amount, merchant_id, location, status, " + "created_at FROM %s WHERE contribution_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::READ; + command->command = query; + + BindString(command.get(), 0, contribution_id); + + command->record_bindings = { + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::DOUBLE_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::INT_TYPE, + ledger::DBCommand::RecordBindingType::INT64_TYPE + }; + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&DatabaseSKUOrder::OnGetRecord, + this, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +void DatabaseSKUOrder::SaveContributionIdForSKUOrder( + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback) { + if (order_id.empty() || contribution_id.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Order/contribution id is empty"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "UPDATE %s SET contribution_id = ? WHERE order_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindString(command.get(), 0, contribution_id); + BindString(command.get(), 1, order_id); + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&OnResultCallback, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +} // namespace braveledger_database diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order.h new file mode 100644 index 000000000000..703d8e6089f1 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order.h @@ -0,0 +1,65 @@ +/* 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_DATABASE_DATABASE_ORDER_H_ +#define BRAVELEDGER_DATABASE_DATABASE_ORDER_H_ + +#include +#include + +#include "bat/ledger/internal/database/database_sku_order_items.h" +#include "bat/ledger/internal/database/database_table.h" + +namespace braveledger_database { + +class DatabaseSKUOrder: public DatabaseTable { + public: + explicit DatabaseSKUOrder(bat_ledger::LedgerImpl* ledger); + ~DatabaseSKUOrder() override; + + bool Migrate(ledger::DBTransaction* transaction, const int target) override; + + void InsertOrUpdate( + ledger::SKUOrderPtr info, + ledger::ResultCallback callback); + + void UpdateStatus( + const std::string& order_id, + const ledger::SKUOrderStatus status, + ledger::ResultCallback callback); + + void GetRecord( + const std::string& order_id, + ledger::GetSKUOrderCallback callback); + + void GetRecordByContributionId( + const std::string& contribution_id, + ledger::GetSKUOrderCallback callback); + + void SaveContributionIdForSKUOrder( + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback); + + private: + bool CreateTableV19(ledger::DBTransaction* transaction); + + bool MigrateToV19(ledger::DBTransaction* transaction); + + void OnGetRecord( + ledger::DBCommandResponsePtr response, + ledger::GetSKUOrderCallback callback); + + void OnGetRecordItems( + ledger::SKUOrderItemList list, + const std::string& order_string, + ledger::GetSKUOrderCallback callback); + + std::unique_ptr items_; +}; + +} // namespace braveledger_database + +#endif // BRAVELEDGER_DATABASE_DATABASE_ORDER_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order_items.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order_items.cc new file mode 100644 index 000000000000..f20bb4d063b5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order_items.cc @@ -0,0 +1,214 @@ +/* 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 +#include + +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/database/database_sku_order_items.h" +#include "bat/ledger/internal/database/database_util.h" +#include "bat/ledger/internal/ledger_impl.h" + +using std::placeholders::_1; + +namespace braveledger_database { + +namespace { + +const char kTableName[] = "sku_order_items"; + +} // namespace + +DatabaseSKUOrderItems::DatabaseSKUOrderItems(bat_ledger::LedgerImpl* ledger) : + DatabaseTable(ledger) { +} + +DatabaseSKUOrderItems::~DatabaseSKUOrderItems() = default; + +bool DatabaseSKUOrderItems::CreateTableV19(ledger::DBTransaction* transaction) { + DCHECK(transaction); + + const std::string query = base::StringPrintf( + "CREATE TABLE %s (" + "order_item_id TEXT NOT NULL," + "order_id TEXT NOT NULL," + "sku TEXT," + "quantity INTEGER," + "price DOUBLE," + "name TEXT," + "description TEXT," + "type INTEGER," + "expires_at TIMESTAMP," + "created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," + "CONSTRAINT %s_unique " + " UNIQUE (order_item_id, order_id)" + ")", + kTableName, + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::EXECUTE; + command->command = query; + transaction->commands.push_back(std::move(command)); + + return true; +} + +bool DatabaseSKUOrderItems::CreateIndexV19(ledger::DBTransaction* transaction) { + DCHECK(transaction); + + bool success = this->InsertIndex(transaction, kTableName, "order_id"); + + if (!success) { + return false; + } + + return this->InsertIndex(transaction, kTableName, "order_item_id"); +} + +bool DatabaseSKUOrderItems::Migrate( + ledger::DBTransaction* transaction, + const int target) { + DCHECK(transaction); + + switch (target) { + case 19: { + return MigrateToV19(transaction); + } + default: { + return true; + } + } +} + +bool DatabaseSKUOrderItems::MigrateToV19(ledger::DBTransaction* transaction) { + DCHECK(transaction); + + if (!DropTable(transaction, kTableName)) { + return false; + } + + if (!CreateTableV19(transaction)) { + return false; + } + + if (!CreateIndexV19(transaction)) { + return false; + } + + return true; +} + +void DatabaseSKUOrderItems::InsertOrUpdateList( + ledger::DBTransaction* transaction, + ledger::SKUOrderItemList list) { + DCHECK(transaction); + if (list.empty()) { + return; + } + + const std::string query = base::StringPrintf( + "INSERT OR REPLACE INTO %s " + "(order_item_id, order_id, sku, quantity, price, name, description, " + "type, expires_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + kTableName); + + for (auto& item : list) { + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindString(command.get(), 0, item->order_item_id); + BindString(command.get(), 1, item->order_id); + BindString(command.get(), 2, item->sku); + BindInt(command.get(), 3, item->quantity); + BindDouble(command.get(), 4, item->price); + BindString(command.get(), 5, item->name); + BindString(command.get(), 6, item->description); + BindInt(command.get(), 7, static_cast(item->type)); + BindInt64(command.get(), 8, item->expires_at); + + transaction->commands.push_back(std::move(command)); + } +} + +void DatabaseSKUOrderItems::GetRecordsByOrderId( + const std::string& order_id, + GetSKUOrderItemsCallback callback) { + if (order_id.empty()) { + callback({}); + return; + } + + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "SELECT order_item_id, order_id, sku, quantity, price, name, " + "description, type, expires_at FROM %s WHERE order_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::READ; + command->command = query; + + BindString(command.get(), 0, order_id); + + command->record_bindings = { + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::INT_TYPE, + ledger::DBCommand::RecordBindingType::DOUBLE_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::INT_TYPE, + ledger::DBCommand::RecordBindingType::INT64_TYPE + }; + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = + std::bind(&DatabaseSKUOrderItems::OnGetRecordsByOrderId, + this, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +void DatabaseSKUOrderItems::OnGetRecordsByOrderId( + ledger::DBCommandResponsePtr response, + GetSKUOrderItemsCallback callback) { + if (!response || + response->status != ledger::DBCommandResponse::Status::RESPONSE_OK) { + callback({}); + return; + } + + ledger::SKUOrderItemList list; + ledger::SKUOrderItemPtr info = nullptr; + for (auto const& record : response->result->get_records()) { + auto* record_pointer = record.get(); + info = ledger::SKUOrderItem::New(); + + info->order_item_id = GetStringColumn(record_pointer, 0); + info->order_id = GetStringColumn(record_pointer, 1); + info->sku = GetStringColumn(record_pointer, 2); + info->quantity = GetIntColumn(record_pointer, 3); + info->price = GetDoubleColumn(record_pointer, 4); + info->name = GetStringColumn(record_pointer, 5); + info->description = GetStringColumn(record_pointer, 6); + info->type = + static_cast(GetIntColumn(record_pointer, 7)); + info->expires_at = GetInt64Column(record_pointer, 8); + + list.push_back(std::move(info)); + } + + callback(std::move(list)); +} + +} // namespace braveledger_database diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order_items.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order_items.h new file mode 100644 index 000000000000..aae1cf729199 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_order_items.h @@ -0,0 +1,47 @@ +/* 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_DATABASE_DATABASE_SKU_ORDER_ITEMS_H_ +#define BRAVELEDGER_DATABASE_DATABASE_SKU_ORDER_ITEMS_H_ + +#include +#include + +#include "bat/ledger/internal/database/database_table.h" + +namespace braveledger_database { + +using GetSKUOrderItemsCallback = std::function; + +class DatabaseSKUOrderItems: public DatabaseTable { + public: + explicit DatabaseSKUOrderItems(bat_ledger::LedgerImpl* ledger); + ~DatabaseSKUOrderItems() override; + + bool Migrate(ledger::DBTransaction* transaction, const int target) override; + + void InsertOrUpdateList( + ledger::DBTransaction* transaction, + ledger::SKUOrderItemList list); + + void GetRecordsByOrderId( + const std::string& order_id, + GetSKUOrderItemsCallback callback); + + private: + bool CreateTableV19(ledger::DBTransaction* transaction); + + bool CreateIndexV19(ledger::DBTransaction* transaction); + + bool MigrateToV19(ledger::DBTransaction* transaction); + + void OnGetRecordsByOrderId( + ledger::DBCommandResponsePtr response, + GetSKUOrderItemsCallback callback); +}; + +} // namespace braveledger_database + +#endif // BRAVELEDGER_DATABASE_DATABASE_SKU_ORDER_ITEMS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_transaction.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_transaction.cc new file mode 100644 index 000000000000..c2fcef38ed72 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_transaction.cc @@ -0,0 +1,235 @@ +/* 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 +#include + +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/database/database_sku_transaction.h" +#include "bat/ledger/internal/database/database_util.h" +#include "bat/ledger/internal/ledger_impl.h" + +using std::placeholders::_1; + +namespace braveledger_database { + +namespace { + +const char kTableName[] = "sku_transaction"; + +} // namespace + +DatabaseSKUTransaction::DatabaseSKUTransaction( + bat_ledger::LedgerImpl* ledger) : + DatabaseTable(ledger) { +} + +DatabaseSKUTransaction::~DatabaseSKUTransaction() = default; + +bool DatabaseSKUTransaction::CreateTableV19( + ledger::DBTransaction* transaction) { + DCHECK(transaction); + + const std::string query = base::StringPrintf( + "CREATE TABLE %s (" + "transaction_id TEXT NOT NULL," + "order_id TEXT NOT NULL," + "external_transaction_id TEXT NOT NULL," + "type INTEGER NOT NULL," + "amount DOUBLE NOT NULL," + "status INTEGER NOT NULL," + "created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (transaction_id)" + ")", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::EXECUTE; + command->command = query; + transaction->commands.push_back(std::move(command)); + + return true; +} + +bool DatabaseSKUTransaction::CreateIndexV19( + ledger::DBTransaction* transaction) { + DCHECK(transaction); + + return this->InsertIndex(transaction, kTableName, "order_id"); +} + +bool DatabaseSKUTransaction::Migrate( + ledger::DBTransaction* transaction, + const int target) { + DCHECK(transaction); + + switch (target) { + case 19: { + return MigrateToV19(transaction); + } + default: { + return true; + } + } +} + +bool DatabaseSKUTransaction::MigrateToV19( + ledger::DBTransaction* transaction) { + DCHECK(transaction); + + if (!DropTable(transaction, kTableName)) { + return false; + } + + if (!CreateTableV19(transaction)) { + return false; + } + + if (!CreateIndexV19(transaction)) { + return false; + } + + return true; +} + +void DatabaseSKUTransaction::InsertOrUpdate( + ledger::SKUTransactionPtr transaction, + ledger::ResultCallback callback) { + if (!transaction) { + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto db_transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "INSERT OR REPLACE INTO %s " + "(transaction_id, order_id, external_transaction_id, type, amount, " + "status) " + "VALUES (?, ?, ?, ?, ?, ?)", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindString(command.get(), 0, transaction->transaction_id); + BindString(command.get(), 1, transaction->order_id); + BindString(command.get(), 2, transaction->external_transaction_id); + BindInt(command.get(), 3, static_cast(transaction->type)); + BindDouble(command.get(), 4, transaction->amount); + BindInt(command.get(), 5, static_cast(transaction->status)); + + db_transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&OnResultCallback, + _1, + callback); + + ledger_->RunDBTransaction(std::move(db_transaction), transaction_callback); +} + +void DatabaseSKUTransaction::SaveExternalTransaction( + const std::string& transaction_id, + const std::string& external_transaction_id, + ledger::ResultCallback callback) { + if (transaction_id.empty() || external_transaction_id.empty()) { + callback(ledger::Result::LEDGER_ERROR); + return; + } + + const std::string query = base::StringPrintf( + "UPDATE %s SET " + "external_transaction_id = ?, status = ? WHERE transaction_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindString(command.get(), 0, external_transaction_id); + BindInt(command.get(), 1, static_cast( + ledger::SKUTransactionStatus::COMPLETED)); + BindString(command.get(), 2, transaction_id); + + auto transaction = ledger::DBTransaction::New(); + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&OnResultCallback, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +void DatabaseSKUTransaction::GetRecordByOrderId( + const std::string& order_id, + ledger::GetSKUTransactionCallback callback) { + if (order_id.empty()) { + callback(nullptr); + return; + } + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "SELECT transaction_id, order_id, external_transaction_id, amount, type, " + "status FROM %s WHERE order_id = ?", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::READ; + command->command = query; + + BindString(command.get(), 0, order_id); + + command->record_bindings = { + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::INT_TYPE, + ledger::DBCommand::RecordBindingType::DOUBLE_TYPE, + ledger::DBCommand::RecordBindingType::INT_TYPE + }; + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&DatabaseSKUTransaction::OnGetRecord, + this, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + +void DatabaseSKUTransaction::OnGetRecord( + ledger::DBCommandResponsePtr response, + ledger::GetSKUTransactionCallback callback) { + if (!response || + response->status != ledger::DBCommandResponse::Status::RESPONSE_OK) { + callback(nullptr); + return; + } + + if (response->result->get_records().size() != 1) { + callback(nullptr); + return; + } + + auto* record = response->result->get_records()[0].get(); + + auto info = ledger::SKUTransaction::New(); + info->transaction_id = GetStringColumn(record, 0); + info->order_id = GetStringColumn(record, 1); + info->external_transaction_id = GetStringColumn(record, 2); + info->amount = GetDoubleColumn(record, 3); + info->type = + static_cast(GetIntColumn(record, 4)); + info->status = + static_cast(GetIntColumn(record, 5)); + + callback(std::move(info)); +} + +} // namespace braveledger_database diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_transaction.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_transaction.h new file mode 100644 index 000000000000..2310e3e3638e --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_sku_transaction.h @@ -0,0 +1,49 @@ +/* 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_DATABASE_DATABASE_SKU_TRANSACTION_H_ +#define BRAVELEDGER_DATABASE_DATABASE_SKU_TRANSACTION_H_ + +#include + +#include "bat/ledger/internal/database/database_table.h" + +namespace braveledger_database { + +class DatabaseSKUTransaction: public DatabaseTable { + public: + explicit DatabaseSKUTransaction(bat_ledger::LedgerImpl* ledger); + ~DatabaseSKUTransaction() override; + + bool Migrate(ledger::DBTransaction* transaction, const int target) override; + + void InsertOrUpdate( + ledger::SKUTransactionPtr info, + ledger::ResultCallback callback); + + void SaveExternalTransaction( + const std::string& transaction_id, + const std::string& external_transaction_id, + ledger::ResultCallback callback); + + void GetRecordByOrderId( + const std::string& order_id, + ledger::GetSKUTransactionCallback callback); + + private: + bool CreateTableV19(ledger::DBTransaction* transaction); + + bool CreateIndexV19(ledger::DBTransaction* transaction); + + bool MigrateToV19(ledger::DBTransaction* transaction); + + void OnGetRecord( + ledger::DBCommandResponsePtr response, + ledger::GetSKUTransactionCallback callback); +}; + +} // namespace braveledger_database + +#endif // BRAVELEDGER_DATABASE_DATABASE_SKU_TRANSACTION_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_table.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_table.cc index fd738e34f77e..ba768ada8d8d 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_table.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_table.cc @@ -11,7 +11,9 @@ namespace braveledger_database { -DatabaseTable::DatabaseTable(bat_ledger::LedgerImpl* ledger): ledger_(ledger) {} +DatabaseTable::DatabaseTable(bat_ledger::LedgerImpl* ledger): ledger_(ledger) { + DCHECK(ledger_); +} DatabaseTable::~DatabaseTable() = default; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.cc index 9fbcdaeca0a5..a4a3d0912df7 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.cc @@ -354,38 +354,6 @@ void DatabaseUnblindedToken::InsertOrUpdateList( ledger_->RunDBTransaction(std::move(transaction), transaction_callback); } -void DatabaseUnblindedToken::GetAllRecords( - ledger::GetUnblindedTokenListCallback callback) { - auto transaction = ledger::DBTransaction::New(); - - const std::string query = base::StringPrintf( - "SELECT token_id, token_value, public_key, value, creds_id, " - "expires_at FROM %s", - kTableName); - - auto command = ledger::DBCommand::New(); - command->type = ledger::DBCommand::Type::READ; - command->command = query; - - command->record_bindings = { - ledger::DBCommand::RecordBindingType::INT64_TYPE, - ledger::DBCommand::RecordBindingType::STRING_TYPE, - ledger::DBCommand::RecordBindingType::STRING_TYPE, - ledger::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::DBCommand::RecordBindingType::STRING_TYPE, - ledger::DBCommand::RecordBindingType::INT64_TYPE - }; - - transaction->commands.push_back(std::move(command)); - - auto transaction_callback = std::bind(&DatabaseUnblindedToken::OnGetRecords, - this, - _1, - callback); - - ledger_->RunDBTransaction(std::move(transaction), transaction_callback); -} - void DatabaseUnblindedToken::OnGetRecords( ledger::DBCommandResponsePtr response, ledger::GetUnblindedTokenListCallback callback) { @@ -507,4 +475,51 @@ void DatabaseUnblindedToken::CheckRecordsExpiration( ledger_->RunDBTransaction(std::move(transaction), transaction_callback); } +void DatabaseUnblindedToken::GetRecordsByBatchTypes( + const std::vector& batch_types, + ledger::GetUnblindedTokenListCallback callback) { + if (batch_types.empty()) { + callback({}); + return; + } + + std::vector in_case; + + for (const auto& type : batch_types) { + in_case.push_back(std::to_string(static_cast(type))); + } + + auto transaction = ledger::DBTransaction::New(); + + const std::string query = base::StringPrintf( + "SELECT ut.token_id, ut.token_value, ut.public_key, ut.value, " + "ut.creds_id, ut.expires_at FROM %s as ut " + "INNER JOIN creds_batch as cb ON cb.creds_id = ut.creds_id " + "WHERE cb.trigger_type IN (%s)", + kTableName, + base::JoinString(in_case, ",").c_str()); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::READ; + command->command = query; + + command->record_bindings = { + ledger::DBCommand::RecordBindingType::INT64_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::DOUBLE_TYPE, + ledger::DBCommand::RecordBindingType::STRING_TYPE, + ledger::DBCommand::RecordBindingType::INT64_TYPE + }; + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&DatabaseUnblindedToken::OnGetRecords, + this, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + } // namespace braveledger_database diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.h index b4a35ba552ea..8dd988a31f96 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_unblinded_token.h @@ -24,8 +24,6 @@ class DatabaseUnblindedToken: public DatabaseTable { ledger::UnblindedTokenList list, ledger::ResultCallback callback); - void GetAllRecords(ledger::GetUnblindedTokenListCallback callback); - void GetRecordsByTriggerIds( const std::vector& trigger_ids, ledger::GetUnblindedTokenListCallback callback); @@ -36,6 +34,10 @@ class DatabaseUnblindedToken: public DatabaseTable { void CheckRecordsExpiration(ledger::ResultCallback callback); + void GetRecordsByBatchTypes( + const std::vector& batch_types, + ledger::GetUnblindedTokenListCallback callback); + private: bool CreateTableV10(ledger::DBTransaction* transaction); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_util.cc index 400206833d72..ca5ffeff0797 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_util.cc @@ -11,7 +11,7 @@ namespace { -const int kCurrentVersionNumber = 18; +const int kCurrentVersionNumber = 19; const int kCompatibleVersionNumber = 1; } // namespace 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 d0af26b138f4..29b96321a595 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 @@ -59,7 +59,7 @@ class MockLedgerClient : public LedgerClient { MOCK_METHOD4(OnReconcileComplete, void( Result result, - const std::string& viewing_id, + const std::string& contribution_id, const double amount, const ledger::RewardsType type)); 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 8f435e2bb47e..70869b421b52 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 @@ -27,6 +27,8 @@ #include "bat/ledger/internal/report/report.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/helper.h" +#include "bat/ledger/internal/sku/sku_factory.h" +#include "bat/ledger/internal/sku/sku_merchant.h" #include "bat/ledger/internal/static_values.h" #include "net/http/http_status_code.h" @@ -38,6 +40,7 @@ using namespace braveledger_contribution; // NOLINT using namespace braveledger_wallet; // NOLINT using namespace braveledger_database; // NOLINT using namespace braveledger_report; // NOLINT +using namespace braveledger_sku; // NOLINT using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; @@ -82,6 +85,11 @@ LedgerImpl::LedgerImpl(ledger::LedgerClient* client) : task_runner_ = base::CreateSequencedTaskRunner( {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); + + bat_sku_ = braveledger_sku::SKUFactory::Create( + this, + braveledger_sku::SKUType::kMerchant); + DCHECK(bat_sku_); } LedgerImpl::~LedgerImpl() { @@ -181,15 +189,6 @@ void LedgerImpl::CreateWallet(ledger::ResultCallback callback) { bat_wallet_->CreateWalletIfNecessary(std::move(on_wallet)); } -ledger::CurrentReconcileProperties LedgerImpl::GetReconcileById( - const std::string& viewingId) { - return bat_state_->GetReconcileById(viewingId); -} - -void LedgerImpl::RemoveReconcileById(const std::string& viewingId) { - bat_state_->RemoveReconcileById(viewingId); -} - void LedgerImpl::OnLoad(ledger::VisitDataPtr visit_data, const uint64_t& current_time) { if (visit_data.get()) { @@ -705,28 +704,6 @@ uint64_t LedgerImpl::GetReconcileStamp() const { return bat_state_->GetReconcileStamp(); } -void LedgerImpl::ReconcileComplete( - const ledger::Result result, - const double amount, - const std::string& viewing_id, - const ledger::RewardsType type, - const bool delete_reconcile) { - const auto reconcile = GetReconcileById(viewing_id); - - if (result == ledger::Result::LEDGER_OK) { - bat_contribution_->ReconcileSuccess( - viewing_id, - amount, - delete_reconcile); - } - - ledger_client_->OnReconcileComplete( - result, - viewing_id, - amount, - type); -} - void LedgerImpl::ContributionCompleted( const ledger::Result result, const double amount, @@ -981,17 +958,6 @@ void LedgerImpl::ResetReconcileStamp() { ledger_client_->ReconcileStampReset(); } -bool LedgerImpl::UpdateReconcile( - const ledger::CurrentReconcileProperties& reconcile) { - return bat_state_->UpdateReconcile(reconcile); -} - -void LedgerImpl::AddReconcile( - const std::string& viewing_id, - const ledger::CurrentReconcileProperties& reconcile) { - bat_state_->AddReconcile(viewing_id, reconcile); -} - const std::string& LedgerImpl::GetPaymentId() const { return bat_state_->GetPaymentId(); } @@ -1074,18 +1040,6 @@ void LedgerImpl::GetRewardsInternalsInfo( secret_key, &public_key, &new_secret_key); } - // Retrieve the current reconciles. - const ledger::CurrentReconciles current_reconciles = GetCurrentReconciles(); - for (const auto& reconcile : current_reconciles) { - ledger::ReconcileInfoPtr reconcile_info = ledger::ReconcileInfo::New(); - reconcile_info->viewing_id = reconcile.second.viewing_id; - reconcile_info->amount = reconcile.second.amount; - reconcile_info->retry_step = reconcile.second.retry_step; - reconcile_info->retry_level = reconcile.second.retry_level; - info->current_reconciles.insert( - std::make_pair(reconcile.second.viewing_id, std::move(reconcile_info))); - } - callback(std::move(info)); } @@ -1102,48 +1056,6 @@ void LedgerImpl::SetWalletProperties( bat_state_->SetWalletProperties(properties); } -unsigned int LedgerImpl::GetDays() const { - return bat_state_->GetDays(); -} - -void LedgerImpl::SetDays(unsigned int days) { - bat_state_->SetDays(days); -} - -const ledger::Transactions& LedgerImpl::GetTransactions() const { - return bat_state_->GetTransactions(); -} - -void LedgerImpl::SetTransactions( - const ledger::Transactions& transactions) { - bat_state_->SetTransactions(transactions); -} - -const ledger::Ballots& LedgerImpl::GetBallots() const { - return bat_state_->GetBallots(); -} - -void LedgerImpl::SetBallots(const ledger::Ballots& ballots) { - bat_state_->SetBallots(ballots); -} - -const ledger::PublisherVotes& LedgerImpl::GetPublisherVotes() const { - return bat_state_->GetPublisherVotes(); -} - -void LedgerImpl::SetPublisherVotes( - const ledger::PublisherVotes& publisher_votes) { - bat_state_->SetPublisherVotes(publisher_votes); -} - -const std::string& LedgerImpl::GetCurrency() const { - return bat_state_->GetCurrency(); -} - -void LedgerImpl::SetCurrency(const std::string& currency) { - bat_state_->SetCurrency(currency); -} - uint64_t LedgerImpl::GetBootStamp() const { return bat_state_->GetBootStamp(); } @@ -1151,19 +1063,6 @@ uint64_t LedgerImpl::GetBootStamp() const { void LedgerImpl::SetBootStamp(uint64_t stamp) { bat_state_->SetBootStamp(stamp); } - -const std::string& LedgerImpl::GetMasterUserToken() const { - return bat_state_->GetMasterUserToken(); -} - -void LedgerImpl::SetMasterUserToken(const std::string& token) { - bat_state_->SetMasterUserToken(token); -} - -bool LedgerImpl::ReconcileExists(const std::string& viewingId) { - return bat_state_->ReconcileExists(viewingId); -} - void LedgerImpl::SaveContributionInfo( ledger::ContributionInfoPtr info, ledger::ResultCallback callback) { @@ -1181,22 +1080,6 @@ void LedgerImpl::SetTimer(uint64_t time_offset, uint32_t* timer_id) const { ledger_client_->SetTimer(time_offset, timer_id); } -bool LedgerImpl::AddReconcileStep( - const std::string& viewing_id, - ledger::ContributionRetry step, - int level) { - BLOG(this, ledger::LogLevel::LOG_DEBUG) - << "Contribution step " - << std::to_string(static_cast(step)) - << " for " - << viewing_id; - return bat_state_->AddReconcileStep(viewing_id, step, level); -} - -const ledger::CurrentReconciles& LedgerImpl::GetCurrentReconciles() const { - return bat_state_->GetCurrentReconciles(); -} - double LedgerImpl::GetDefaultContributionAmount() { return bat_state_->GetDefaultContributionAmount(); } @@ -1575,11 +1458,6 @@ void LedgerImpl::SaveUnblindedTokenList( bat_database_->SaveUnblindedTokenList(std::move(list), callback); } -void LedgerImpl::GetAllUnblindedTokens( - ledger::GetUnblindedTokenListCallback callback) { - bat_database_->GetAllUnblindedTokens(callback); -} - void LedgerImpl::DeleteUnblindedTokens( const std::vector& id_list, ledger::ResultCallback callback) { @@ -1618,10 +1496,9 @@ void LedgerImpl::GetContributionReport( bat_database_->GetContributionReport(month, year, callback); } -void LedgerImpl::GetIncompleteContributions( - const ledger::ContributionProcessor processor, +void LedgerImpl::GetNotCompletedContributions( ledger::ContributionInfoListCallback callback) { - bat_database_->GetIncompleteContributions(processor, callback); + bat_database_->GetNotCompletedContributions(callback); } void LedgerImpl::GetContributionInfo( @@ -1630,6 +1507,16 @@ void LedgerImpl::GetContributionInfo( bat_database_->GetContributionInfo(contribution_id, callback); } +void LedgerImpl::UpdateContributionInfoStep( + const std::string& contribution_id, + const ledger::ContributionStep step, + ledger::ResultCallback callback) { + bat_database_->UpdateContributionInfoStep( + contribution_id, + step, + callback); +} + void LedgerImpl::UpdateContributionInfoStepAndCount( const std::string& contribution_id, const ledger::ContributionStep step, @@ -1758,4 +1645,89 @@ void LedgerImpl::UpdateCredsBatchStatus( callback); } +void LedgerImpl::SaveSKUOrder( + ledger::SKUOrderPtr order, + ledger::ResultCallback callback) { + bat_database_->SaveSKUOrder(std::move(order), callback); +} + +void LedgerImpl::SaveSKUTransaction( + ledger::SKUTransactionPtr transaction, + ledger::ResultCallback callback) { + bat_database_->SaveSKUTransaction(std::move(transaction), callback); +} + +void LedgerImpl::SaveSKUExternalTransaction( + const std::string& transaction_id, + const std::string& external_transaction_id, + ledger::ResultCallback callback) { + bat_database_->SaveSKUExternalTransaction( + transaction_id, + external_transaction_id, + callback); +} + +void LedgerImpl::UpdateSKUOrderStatus( + const std::string& order_id, + const ledger::SKUOrderStatus status, + ledger::ResultCallback callback) { + bat_database_->UpdateSKUOrderStatus( + order_id, + status, + callback); +} + +void LedgerImpl::TransferFunds( + const ledger::SKUTransaction& transaction, + const std::string& destination, + ledger::ExternalWalletPtr wallet, + ledger::TransactionCallback callback) { + bat_contribution_->TransferFunds( + transaction, + destination, + std::move(wallet), + callback); +} + +void LedgerImpl::GetSKUOrder( + const std::string& order_id, + ledger::GetSKUOrderCallback callback) { + bat_database_->GetSKUOrder(order_id, callback); +} + +void LedgerImpl::ProcessSKU( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) { + bat_sku_->Process(items, std::move(wallet), callback); +} + +void LedgerImpl::GetSKUOrderByContributionId( + const std::string& contribution_id, + ledger::GetSKUOrderCallback callback) { + bat_database_->GetSKUOrderByContributionId(contribution_id, callback); +} + +void LedgerImpl::SaveContributionIdForSKUOrder( + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback) { + bat_database_->SaveContributionIdForSKUOrder( + order_id, + contribution_id, + callback); +} + +void LedgerImpl::GetSKUTransactionByOrderId( + const std::string& order_id, + ledger::GetSKUTransactionCallback callback) { + bat_database_->GetSKUTransactionByOrderId(order_id, callback); +} + +void LedgerImpl::GetUnblindedTokensByBatchTypes( + const std::vector& batch_types, + ledger::GetUnblindedTokenListCallback callback) { + bat_database_->GetUnblindedTokensByBatchTypes(batch_types, 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 41780a38afbb..00259f5ecd3c 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 @@ -19,9 +19,6 @@ #include "bat/ledger/internal/contribution/contribution.h" #include "bat/ledger/internal/database/database.h" #include "bat/ledger/internal/logging.h" -#include "bat/ledger/internal/properties/ballot_properties.h" -#include "bat/ledger/internal/properties/publisher_votes_properties.h" -#include "bat/ledger/internal/properties/transaction_properties.h" #include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/internal/wallet/wallet.h" #include "bat/ledger/ledger_client.h" @@ -63,6 +60,10 @@ namespace braveledger_report { class Report; } +namespace braveledger_sku { +class SKU; +} + namespace confirmations { class Confirmations; } @@ -234,14 +235,6 @@ class LedgerImpl : public ledger::Ledger { const ledger::UrlMethod method, ledger::LoadURLCallback callback); - // 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, @@ -297,11 +290,6 @@ class LedgerImpl : public ledger::Ledger { const ledger::ReportType type, const double amount); - ledger::CurrentReconcileProperties GetReconcileById( - const std::string& viewingId); - - void RemoveReconcileById(const std::string& viewingId); - void FetchFavIcon(const std::string& url, const std::string& favicon_key, ledger::FetchIconCallback callback); @@ -337,13 +325,6 @@ class LedgerImpl : public ledger::Ledger { void ResetReconcileStamp(); - bool UpdateReconcile( - const ledger::CurrentReconcileProperties& reconcile); - - void AddReconcile( - const std::string& viewing_id, - const ledger::CurrentReconcileProperties& reconcile); - virtual const std::string& GetPaymentId() const; const std::string& GetPersonaId() const; @@ -371,39 +352,10 @@ class LedgerImpl : public ledger::Ledger { void SetWalletProperties( ledger::WalletProperties* properties); - unsigned int GetDays() const; - - void SetDays(unsigned int days); - - const ledger::Transactions& GetTransactions() const; - - void SetTransactions( - const ledger::Transactions& transactions); - - const ledger::Ballots& GetBallots() const; - - void SetBallots( - const ledger::Ballots& ballots); - - const ledger::PublisherVotes& GetPublisherVotes() const; - - void SetPublisherVotes( - const ledger::PublisherVotes& publisher_votes); - - const std::string& GetCurrency() const; - - void SetCurrency(const std::string& currency); - uint64_t GetBootStamp() const override; void SetBootStamp(uint64_t stamp); - const std::string& GetMasterUserToken() const; - - void SetMasterUserToken(const std::string& token); - - bool ReconcileExists(const std::string& viewingId); - void SaveContributionInfo( ledger::ContributionInfoPtr info, ledger::ResultCallback callback); @@ -415,12 +367,6 @@ class LedgerImpl : public ledger::Ledger { void SetTimer(uint64_t time_offset, uint32_t* timer_id) const; - bool AddReconcileStep(const std::string& viewing_id, - ledger::ContributionRetry step, - int level = -1); - - const ledger::CurrentReconciles& GetCurrentReconciles() const; - double GetDefaultContributionAmount() override; void HasSufficientBalanceToReconcile( @@ -620,9 +566,6 @@ class LedgerImpl : public ledger::Ledger { ledger::UnblindedTokenList list, ledger::ResultCallback callback); - virtual void GetAllUnblindedTokens( - ledger::GetUnblindedTokenListCallback callback); - virtual void DeleteUnblindedTokens( const std::vector& id_list, ledger::ResultCallback callback); @@ -647,15 +590,19 @@ class LedgerImpl : public ledger::Ledger { const int year, ledger::GetContributionReportCallback callback) override; - void GetIncompleteContributions( - const ledger::ContributionProcessor processor, + void GetNotCompletedContributions( ledger::ContributionInfoListCallback callback); virtual void GetContributionInfo( const std::string& contribution_id, ledger::GetContributionInfoCallback callback); - void UpdateContributionInfoStepAndCount( + virtual void UpdateContributionInfoStep( + const std::string& contribution_id, + const ledger::ContributionStep step, + ledger::ResultCallback callback); + + virtual void UpdateContributionInfoStepAndCount( const std::string& contribution_id, const ledger::ContributionStep step, const int32_t retry_count, @@ -732,6 +679,59 @@ class LedgerImpl : public ledger::Ledger { const ledger::CredsBatchStatus status, ledger::ResultCallback callback); + void SaveSKUOrder(ledger::SKUOrderPtr order, ledger::ResultCallback callback); + + void SaveSKUTransaction( + ledger::SKUTransactionPtr transaction, + ledger::ResultCallback callback); + + void SaveSKUExternalTransaction( + const std::string& transaction_id, + const std::string& external_transaction_id, + ledger::ResultCallback callback); + + void UpdateSKUOrderStatus( + const std::string& order_id, + const ledger::SKUOrderStatus status, + ledger::ResultCallback callback); + + void TransferFunds( + const ledger::SKUTransaction& transaction, + const std::string& destination, + ledger::ExternalWalletPtr wallet, + ledger::TransactionCallback callback); + + void GetSKUOrder( + const std::string& order_id, + ledger::GetSKUOrderCallback callback); + + void ProcessSKU( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) override; + + void RetrySKU( + const std::string& order_id, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback); + + void GetSKUOrderByContributionId( + const std::string& contribution_id, + ledger::GetSKUOrderCallback callback); + + void SaveContributionIdForSKUOrder( + const std::string& order_id, + const std::string& contribution_id, + ledger::ResultCallback callback); + + void GetSKUTransactionByOrderId( + const std::string& order_id, + ledger::GetSKUTransactionCallback callback); + + virtual void GetUnblindedTokensByBatchTypes( + const std::vector& batch_types, + ledger::GetUnblindedTokenListCallback callback); + private: void InitializeConfirmations( const bool execute_create_script, @@ -820,6 +820,7 @@ class LedgerImpl : public ledger::Ledger { std::unique_ptr bat_database_; std::unique_ptr bat_confirmations_; std::unique_ptr bat_report_; + std::unique_ptr bat_sku_; scoped_refptr task_runner_; bool initialized_task_scheduler_; 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 78009249fdde..fabb64e490ba 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 @@ -191,13 +191,6 @@ class MockLedgerImpl : public LedgerImpl { const ledger::UrlMethod, ledger::LoadURLCallback)); - MOCK_METHOD5(ReconcileComplete, - void(ledger::Result, - const double, - const std::string&, - const ledger::RewardsType, - const bool)); - MOCK_METHOD4(ContributionCompleted, void( const ledger::Result, const double, @@ -245,12 +238,6 @@ class MockLedgerImpl : public LedgerImpl { const ledger::ReportType, const double)); - - MOCK_METHOD1(GetReconcileById, - ledger::CurrentReconcileProperties(const std::string&)); - - MOCK_METHOD1(RemoveReconcileById, void(const std::string&)); - MOCK_METHOD3(FetchFavIcon, void(const std::string&, const std::string&, @@ -259,14 +246,6 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD2(GetPublisherBanner, void(const std::string&, ledger::PublisherBannerCallback)); - MOCK_METHOD6(OnReconcileCompleteSuccess, - void(const std::string&, - const ledger::RewardsType, - const std::string&, - const ledger::ActivityMonth, - const int, - const uint32_t)); - MOCK_METHOD2(SaveRecurringTip, void(ledger::RecurringTipPtr, ledger::ResultCallback)); @@ -293,13 +272,6 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD0(ResetReconcileStamp, void()); - MOCK_METHOD1(UpdateReconcile, - bool(const ledger::CurrentReconcileProperties&)); - - MOCK_METHOD2(AddReconcile, - void(const std::string&, - const ledger::CurrentReconcileProperties&)); - MOCK_CONST_METHOD0(GetPaymentId, const std::string&()); MOCK_CONST_METHOD0(GetPersonaId, const std::string&()); @@ -334,38 +306,10 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD1(SetWalletProperties, void(ledger::WalletProperties*)); - MOCK_CONST_METHOD0(GetDays, unsigned int()); - - MOCK_METHOD1(SetDays, void(unsigned int)); - - MOCK_CONST_METHOD0(GetTransactions, - const ledger::Transactions&()); - - MOCK_METHOD1(SetTransactions, - void(const ledger::Transactions&)); - - MOCK_CONST_METHOD0(GetBallots, const ledger::Ballots&()); - - MOCK_METHOD1(SetBallots, void(const ledger::Ballots&)); - - MOCK_CONST_METHOD0(GetBatch, const ledger::BatchVotes&()); - - MOCK_METHOD1(SetBatch, void(const ledger::BatchVotes&)); - - MOCK_CONST_METHOD0(GetCurrency, const std::string&()); - - MOCK_METHOD1(SetCurrency, void(const std::string&)); - MOCK_CONST_METHOD0(GetBootStamp, uint64_t()); MOCK_METHOD1(SetBootStamp, void(uint64_t)); - MOCK_CONST_METHOD0(GetMasterUserToken, const std::string&()); - - MOCK_METHOD1(SetMasterUserToken, void(const std::string&)); - - MOCK_METHOD1(ReconcileExists, bool(const std::string&)); - MOCK_METHOD6(SaveContributionInfo, void(const std::string&, const ledger::ActivityMonth, @@ -381,14 +325,6 @@ class MockLedgerImpl : public LedgerImpl { MOCK_CONST_METHOD2(SetTimer, void(uint64_t, uint32_t*)); - MOCK_METHOD3(AddReconcileStep, - bool(const std::string&, - ledger::ContributionRetry, - int)); - - MOCK_CONST_METHOD0(GetCurrentReconciles, - const ledger::CurrentReconciles&()); - MOCK_METHOD0(GetDefaultContributionAmount, double()); MOCK_METHOD1(HasSufficientBalanceToReconcile, @@ -576,9 +512,6 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD2(SaveUnblindedTokenList, void( ledger::UnblindedTokenList, ledger::ResultCallback)); - MOCK_METHOD1(GetAllUnblindedTokens, - void(ledger::GetUnblindedTokenListCallback)); - MOCK_METHOD2(DeleteUnblindedTokens, void(const std::vector&, ledger::ResultCallback)); @@ -596,11 +529,26 @@ class MockLedgerImpl : public LedgerImpl { const std::string& contribution_id, ledger::GetContributionInfoCallback callback)); + MOCK_METHOD3(UpdateContributionInfoStep, void( + const std::string& contribution_id, + const ledger::ContributionStep step, + ledger::ResultCallback callback)); + + MOCK_METHOD4(UpdateContributionInfoStepAndCount, void( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback)); + MOCK_METHOD2(RunDBTransaction, void( ledger::DBTransactionPtr, ledger::RunDBTransactionCallback)); MOCK_METHOD1(GetCreateScript, void(ledger::GetCreateScriptCallback callback)); + + MOCK_METHOD2(GetUnblindedTokensByBatchTypes, void( + const std::vector&, + ledger::GetUnblindedTokenListCallback)); }; } // namespace bat_ledger 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 fe9cda8ea274..b8d44adf85d9 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 @@ -5,16 +5,10 @@ #include -#include "base/json/json_writer.h" -#include "base/values.h" -#include "bat/ledger/internal/contribution/contribution_util.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/promotion/promotion_transfer.h" #include "bat/ledger/internal/promotion/promotion_util.h" -#include "bat/ledger/internal/request/request_promotion.h" -#include "bat/ledger/internal/request/request_util.h" #include "bat/ledger/internal/state_keys.h" -#include "net/http/http_status_code.h" using std::placeholders::_1; using std::placeholders::_2; @@ -25,6 +19,10 @@ namespace braveledger_promotion { PromotionTransfer::PromotionTransfer(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { DCHECK(ledger_); + credentials_ = braveledger_credentials::CredentialsFactory::Create( + ledger_, + ledger::CredsBatchType::PROMOTION); + DCHECK(credentials_); } PromotionTransfer::~PromotionTransfer() = default; @@ -81,7 +79,7 @@ void PromotionTransfer::GetEligiblePromotion(ledger::ResultCallback callback) { void PromotionTransfer::GetEligibleTokens( ledger::PromotionList promotions, ledger::ResultCallback callback) { - auto tokens_callback = std::bind(&PromotionTransfer::SendTokens, + auto tokens_callback = std::bind(&PromotionTransfer::OnGetEligibleTokens, this, _1, callback); @@ -100,7 +98,7 @@ void PromotionTransfer::GetEligibleTokens( tokens_callback); } -void PromotionTransfer::SendTokens( +void PromotionTransfer::OnGetEligibleTokens( ledger::UnblindedTokenList list, ledger::ResultCallback callback) { if (list.empty()) { @@ -108,88 +106,17 @@ void PromotionTransfer::SendTokens( return; } - base::Value credentials(base::Value::Type::LIST); - std::vector tokens_ids; - + std::vector token_list; for (auto& item : list) { - if (!item) { - continue; - } - - base::Value token(base::Value::Type::DICTIONARY); - bool success = false; - if (ledger::is_testing) { - success = braveledger_contribution::GenerateSuggestionMock( - item->token_value, - item->public_key, - ledger_->GetPaymentId(), - &token); - } else { - success = braveledger_contribution::GenerateSuggestion( - item->token_value, - item->public_key, - ledger_->GetPaymentId(), - &token); - } - - if (!success) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) - << "Token was not generated successfully. Token: " - << item->token_value; - continue; - } - - credentials.Append(std::move(token)); - tokens_ids.push_back(std::to_string(item->id)); + token_list.push_back(*item); } - base::Value body(base::Value::Type::DICTIONARY); - body.SetStringKey("paymentId", ledger_->GetPaymentId()); - body.SetKey("credentials", std::move(credentials)); - - std::string json; - base::JSONWriter::Write(body, &json); - - const std::string url = braveledger_request_util::GetTransferTokens(); - - auto url_callback = std::bind(&PromotionTransfer::DeleteTokens, - this, - _1, - _2, - _3, - tokens_ids, - std::move(callback)); - - ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); - const auto headers = braveledger_request_util::BuildSignHeaders( - "post /v1/suggestions/claim", - json, - ledger_->GetPaymentId(), - wallet_info.key_info_seed); - - ledger_->LoadURL( - url, - headers, - json, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - url_callback); -} - -void PromotionTransfer::DeleteTokens( - const int response_status_code, - const std::string& response, - const std::map& headers, - const std::vector& sent_ids, - ledger::ResultCallback callback) { - ledger_->LogResponse(__func__, response_status_code, response, headers); - - if (response_status_code != net::HTTP_OK) { - callback(ledger::Result::LEDGER_ERROR); - return; - } + braveledger_credentials::CredentialsRedeem redeem; + redeem.type = ledger::RewardsType::TRANSFER; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = token_list; - ledger_->DeleteUnblindedTokens(sent_ids, callback); + credentials_->RedeemTokens(redeem, callback); } } // namespace braveledger_promotion 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 bf8459e9ce24..335f96ef7d99 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 @@ -7,9 +7,11 @@ #define BRAVELEDGER_PROMOTION_TRANSFER_H_ #include +#include #include #include +#include "bat/ledger/internal/credentials/credentials_factory.h" #include "bat/ledger/ledger.h" namespace bat_ledger { @@ -36,18 +38,12 @@ class PromotionTransfer { ledger::PromotionList promotions, ledger::ResultCallback callback); - void SendTokens( + void OnGetEligibleTokens( ledger::UnblindedTokenList list, ledger::ResultCallback callback); - void DeleteTokens( - const int response_status_code, - const std::string& response, - const std::map& headers, - const std::vector& sent_ids, - ledger::ResultCallback callback); - bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr credentials_; }; } // namespace braveledger_promotion diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.cc deleted file mode 100644 index 4568bf17bd5d..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.cc +++ /dev/null @@ -1,39 +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/properties/ballot_properties.h" - -namespace ledger { - -BallotProperties::BallotProperties() = default; - -BallotProperties::BallotProperties( - const BallotProperties& properties) { - viewing_id = properties.viewing_id; - surveyor_id = properties.surveyor_id; - publisher = properties.publisher; - count = properties.count; - prepare_ballot = properties.prepare_ballot; - proof_ballot = properties.proof_ballot; -} - -BallotProperties::~BallotProperties() = default; - -bool BallotProperties::operator==( - const BallotProperties& rhs) const { - return viewing_id == rhs.viewing_id && - surveyor_id == rhs.surveyor_id && - publisher == rhs.publisher && - count == rhs.count && - prepare_ballot == rhs.prepare_ballot && - proof_ballot == rhs.proof_ballot; -} - -bool BallotProperties::operator!=( - const BallotProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.h deleted file mode 100644 index 04d88c2e42c9..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.h +++ /dev/null @@ -1,39 +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_BALLOT_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_BALLOT_PROPERTIES_H_ - -#include -#include -#include - -namespace ledger { - -struct BallotProperties { - BallotProperties(); - BallotProperties( - const BallotProperties& properties); - ~BallotProperties(); - - bool operator==( - const BallotProperties& rhs) const; - - bool operator!=( - const BallotProperties& rhs) const; - - std::string viewing_id; - std::string surveyor_id; - std::string publisher; - uint32_t count; - std::string prepare_ballot; - std::string proof_ballot; -}; - -typedef std::vector Ballots; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_BALLOT_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.cc deleted file mode 100644 index a8ac6ee695e4..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.cc +++ /dev/null @@ -1,31 +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/properties/batch_proof_properties.h" - -namespace ledger { - -BatchProofProperties::BatchProofProperties() = default; - -BatchProofProperties::BatchProofProperties( - const BatchProofProperties& properties) { - transaction = properties.transaction; - ballot = properties.ballot; -} - -BatchProofProperties::~BatchProofProperties() = default; - -bool BatchProofProperties::operator==( - const BatchProofProperties& rhs) const { - return transaction == rhs.transaction && - ballot == rhs.ballot; -} - -bool BatchProofProperties::operator!=( - const BatchProofProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.h deleted file mode 100644 index e20b0eb76eab..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.h +++ /dev/null @@ -1,36 +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_BATCH_PROOF_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_BATCH_PROOF_PROPERTIES_H_ - -#include - -#include "bat/ledger/internal/properties/transaction_properties.h" -#include "bat/ledger/internal/properties/ballot_properties.h" - -namespace ledger { - -struct BatchProofProperties { - BatchProofProperties(); - BatchProofProperties( - const BatchProofProperties& properties); - ~BatchProofProperties(); - - bool operator==( - const BatchProofProperties& rhs) const; - - bool operator!=( - const BatchProofProperties& rhs) const; - - TransactionProperties transaction; - BallotProperties ballot; -}; - -typedef std::vector BatchProofs; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_BATCH_PROOF_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.cc index 5fbe7dbb22be..f5f1bdde70af 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.cc @@ -11,10 +11,8 @@ namespace ledger { ClientProperties::ClientProperties() : boot_timestamp(0), reconcile_timestamp(0), - settings(AD_FREE_SETTINGS), fee_amount(0), user_changed_fee(false), - days(0), auto_contribute(false), rewards_enabled(false) {} @@ -27,19 +25,11 @@ ClientProperties::ClientProperties( persona_id = properties.persona_id; user_id = properties.user_id; registrar_vk = properties.registrar_vk; - master_user_token = properties.master_user_token; pre_flight = properties.pre_flight; - fee_currency = properties.fee_currency; - settings = properties.settings; fee_amount = properties.fee_amount; user_changed_fee = properties.user_changed_fee; - days = properties.days; - transactions = properties.transactions; - ballots = properties.ballots; - publisher_votes = properties.publisher_votes; auto_contribute = properties.auto_contribute; rewards_enabled = properties.rewards_enabled; - current_reconciles = properties.current_reconciles; inline_tips = properties.inline_tips; } @@ -54,19 +44,11 @@ bool ClientProperties::operator==( persona_id == rhs.persona_id && user_id == rhs.user_id && registrar_vk == rhs.registrar_vk && - master_user_token == rhs.master_user_token && pre_flight == rhs.pre_flight && - fee_currency == rhs.fee_currency && - settings == rhs.settings && fee_amount == rhs.fee_amount && user_changed_fee == rhs.user_changed_fee && - days == rhs.days && - transactions == rhs.transactions && - ballots == rhs.ballots && - publisher_votes == rhs.publisher_votes && auto_contribute == rhs.auto_contribute && rewards_enabled == rhs.rewards_enabled && - current_reconciles == rhs.current_reconciles && inline_tips == rhs.inline_tips; } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.h index 7f91ce3230cb..f3eb7245f8b7 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.h @@ -10,10 +10,6 @@ #include #include -#include "bat/ledger/internal/properties/ballot_properties.h" -#include "bat/ledger/internal/properties/publisher_votes_properties.h" -#include "bat/ledger/internal/properties/current_reconcile_properties.h" -#include "bat/ledger/internal/properties/transaction_properties.h" #include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/mojom_structs.h" @@ -38,17 +34,9 @@ struct ClientProperties { std::string persona_id; std::string user_id; std::string registrar_vk; - std::string master_user_token; std::string pre_flight; - std::string fee_currency; - std::string settings; double fee_amount; bool user_changed_fee; - uint32_t days; - Transactions transactions; - Ballots ballots; - PublisherVotes publisher_votes; - CurrentReconciles current_reconciles; bool auto_contribute; bool rewards_enabled; std::map inline_tips; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.cc deleted file mode 100644 index c3708f199787..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.cc +++ /dev/null @@ -1,65 +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/properties/current_reconcile_properties.h" - -namespace ledger { - -CurrentReconcileProperties::CurrentReconcileProperties() - : timestamp(0), - fee(.0), - retry_step(ContributionRetry::STEP_NO), - retry_level(0) {} - -CurrentReconcileProperties::CurrentReconcileProperties( - const CurrentReconcileProperties& properties) { - viewing_id = properties.viewing_id; - anonize_viewing_id = properties.anonize_viewing_id; - registrar_vk = properties.registrar_vk; - pre_flight = properties.pre_flight; - master_user_token = properties.master_user_token; - surveyor_id = properties.surveyor_id; - timestamp = properties.timestamp; - rates = properties.rates; - amount = properties.amount; - currency = properties.currency; - fee = properties.fee; - directions = properties.directions; - type = properties.type; - retry_step = properties.retry_step; - retry_level = properties.retry_level; - destination = properties.destination; - proof = properties.proof; -} - -CurrentReconcileProperties::~CurrentReconcileProperties() = default; - -bool CurrentReconcileProperties::operator==( - const CurrentReconcileProperties& rhs) const { - return viewing_id == rhs.viewing_id && - anonize_viewing_id == rhs.anonize_viewing_id && - registrar_vk == rhs.registrar_vk && - pre_flight == rhs.pre_flight && - master_user_token == rhs.master_user_token && - surveyor_id == rhs.surveyor_id && - timestamp == rhs.timestamp && - rates == rhs.rates && - amount == rhs.amount && - currency == rhs.currency && - fee == rhs.fee && - directions == rhs.directions && - type == rhs.type && - retry_step == rhs.retry_step && - retry_level == rhs.retry_level && - destination == rhs.destination && - proof == rhs.proof; -} - -bool CurrentReconcileProperties::operator!=( - const CurrentReconcileProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.h deleted file mode 100644 index 1375d5edbfc6..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.h +++ /dev/null @@ -1,53 +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_CURRENT_RECONCILE_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_CURRENT_RECONCILE_PROPERTIES_H_ - -#include -#include -#include - -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" -#include "bat/ledger/mojom_structs.h" - -namespace ledger { - -struct CurrentReconcileProperties { - CurrentReconcileProperties(); - CurrentReconcileProperties( - const CurrentReconcileProperties& properties); - ~CurrentReconcileProperties(); - - bool operator==( - const CurrentReconcileProperties& rhs) const; - - bool operator!=( - const CurrentReconcileProperties& rhs) const; - - std::string viewing_id; - std::string anonize_viewing_id; - std::string registrar_vk; - std::string pre_flight; - std::string master_user_token; - std::string surveyor_id; - uint64_t timestamp; - std::map rates; - std::string amount; - std::string currency; - double fee; - ReconcileDirections directions; - RewardsType type; - ContributionRetry retry_step; - int32_t retry_level; - std::string destination; - std::string proof; -}; - -typedef std::map CurrentReconciles; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_CURRENT_RECONCILE_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.cc deleted file mode 100644 index 0fee86913279..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.cc +++ /dev/null @@ -1,52 +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/properties/publisher_properties.h" - -namespace ledger { - -PublisherProperties::PublisherProperties() - : duration(0), - score(0), - visits(0), - percent(0), - weight(0), - status(0) {} - -PublisherProperties::PublisherProperties( - const PublisherProperties& properties) { - id = properties.id; - duration = properties.duration; - score = properties.score; - visits = properties.visits; - percent = properties.percent; - weight = properties.weight; - status = properties.status; -} - -PublisherProperties::~PublisherProperties() = default; - -bool PublisherProperties::operator==( - const PublisherProperties& rhs) const { - return id == rhs.id && - duration == rhs.duration && - score == rhs.score && - visits == rhs.visits && - percent == rhs.percent && - weight == rhs.weight && - status == rhs.status; -} - -bool PublisherProperties::operator!=( - const PublisherProperties& rhs) const { - return !(*this == rhs); -} - -bool PublisherProperties::operator<( - const PublisherProperties& rhs) const { - return score > rhs.score; -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.h deleted file mode 100644 index 4e709d9621e8..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.h +++ /dev/null @@ -1,43 +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_PUBLISHER_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_PUBLISHER_PROPERTIES_H_ - -#include -#include -#include - -namespace ledger { - -struct PublisherProperties { - PublisherProperties(); - PublisherProperties( - const PublisherProperties& properties); - ~PublisherProperties(); - - bool operator==( - const PublisherProperties& rhs) const; - - bool operator!=( - const PublisherProperties& rhs) const; - - bool operator<( - const PublisherProperties& rhs) const; - - std::string id; - uint64_t duration; - double score; - uint32_t visits; - uint32_t percent; - double weight; - uint32_t status; -}; - -typedef std::vector Publishers; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_PUBLISHER_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.cc deleted file mode 100644 index e70ff1e166fe..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.cc +++ /dev/null @@ -1,31 +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/properties/publisher_vote_properties.h" - -namespace ledger { - -PublisherVoteProperties::PublisherVoteProperties() = default; - -PublisherVoteProperties::PublisherVoteProperties( - const PublisherVoteProperties& properties) { - surveyor_id = properties.surveyor_id; - proof = properties.proof; -} - -PublisherVoteProperties::~PublisherVoteProperties() = default; - -bool PublisherVoteProperties::operator==( - const PublisherVoteProperties& rhs) const { - return surveyor_id == rhs.surveyor_id && - proof == rhs.proof; -} - -bool PublisherVoteProperties::operator!=( - const PublisherVoteProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.h deleted file mode 100644 index 3081bd594563..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.h +++ /dev/null @@ -1,34 +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_PUBLISHER_VOTE_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_PUBLISHER_VOTE_PROPERTIES_H_ - -#include -#include - -namespace ledger { - -struct PublisherVoteProperties { - PublisherVoteProperties(); - PublisherVoteProperties( - const PublisherVoteProperties& properties); - ~PublisherVoteProperties(); - - bool operator==( - const PublisherVoteProperties& rhs) const; - - bool operator!=( - const PublisherVoteProperties& rhs) const; - - std::string surveyor_id; - std::string proof; -}; - -typedef std::vector BatchVotes; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_PUBLISHER_VOTE_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.cc deleted file mode 100644 index 3413cf91d7e2..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.cc +++ /dev/null @@ -1,31 +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/properties/publisher_votes_properties.h" - -namespace ledger { - -PublisherVotesProperties::PublisherVotesProperties() = default; - -PublisherVotesProperties::PublisherVotesProperties( - const PublisherVotesProperties& properties) { - publisher = properties.publisher; - batch_votes = properties.batch_votes; -} - -PublisherVotesProperties::~PublisherVotesProperties() = default; - -bool PublisherVotesProperties::operator==( - const PublisherVotesProperties& rhs) const { - return publisher == rhs.publisher && - batch_votes == rhs.batch_votes; -} - -bool PublisherVotesProperties::operator!=( - const PublisherVotesProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.h deleted file mode 100644 index 51b0c0b40d97..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.h +++ /dev/null @@ -1,36 +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_PUBLISHER_VOTES_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_PUBLISHER_VOTES_PROPERTIES_H_ - -#include -#include - -#include "bat/ledger/internal/properties/publisher_vote_properties.h" - -namespace ledger { - -struct PublisherVotesProperties { - PublisherVotesProperties(); - PublisherVotesProperties( - const PublisherVotesProperties& properties); - ~PublisherVotesProperties(); - - bool operator==( - const PublisherVotesProperties& rhs) const; - - bool operator!=( - const PublisherVotesProperties& rhs) const; - - std::string publisher; - BatchVotes batch_votes; -}; - -typedef std::vector PublisherVotes; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_PUBLISHER_VOTES_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.cc deleted file mode 100644 index 7ea04295d512..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.cc +++ /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/. */ - -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" - -namespace ledger { - -ReconcileDirectionProperties::ReconcileDirectionProperties() - : amount_percent(0.0) {} - -ReconcileDirectionProperties::ReconcileDirectionProperties( - const ReconcileDirectionProperties& properties) { - publisher_key = properties.publisher_key; - amount_percent = properties.amount_percent; -} - -ReconcileDirectionProperties::~ReconcileDirectionProperties() = default; - -bool ReconcileDirectionProperties::operator==( - const ReconcileDirectionProperties& rhs) const { - return publisher_key == rhs.publisher_key && - amount_percent == rhs.amount_percent; -} - -bool ReconcileDirectionProperties::operator!=( - const ReconcileDirectionProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.h deleted file mode 100644 index d98b2cfb585c..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.h +++ /dev/null @@ -1,34 +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_RECONCILE_DIRECTION_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_RECONCILE_DIRECTION_PROPERTIES_H_ - -#include -#include - -namespace ledger { - -struct ReconcileDirectionProperties { - ReconcileDirectionProperties(); - ReconcileDirectionProperties( - const ReconcileDirectionProperties& properties); - ~ReconcileDirectionProperties(); - - bool operator==( - const ReconcileDirectionProperties& rhs) const; - - bool operator!=( - const ReconcileDirectionProperties& rhs) const; - - std::string publisher_key; - double amount_percent; -}; - -typedef std::vector ReconcileDirections; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_RECONCILE_DIRECTION_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.cc deleted file mode 100644 index 6bf5e375dde5..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.cc +++ /dev/null @@ -1,41 +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/properties/reconcile_request_properties.h" - -namespace ledger { - -ReconcileRequestProperties::ReconcileRequestProperties() = default; - -ReconcileRequestProperties::ReconcileRequestProperties( - const ReconcileRequestProperties& properties) { - type = properties.type; - signed_tx_headers_digest = properties.signed_tx_headers_digest; - signed_tx_headers_signature = properties.signed_tx_headers_signature; - signed_tx_body = properties.signed_tx_body; - signed_tx_octets = properties.signed_tx_octets; - viewing_id = properties.viewing_id; - surveyor_id = properties.surveyor_id; -} - -ReconcileRequestProperties::~ReconcileRequestProperties() = default; - -bool ReconcileRequestProperties::operator==( - const ReconcileRequestProperties& rhs) const { - return type == rhs.type && - signed_tx_headers_digest == rhs.signed_tx_headers_digest && - signed_tx_headers_signature == rhs.signed_tx_headers_signature && - signed_tx_body == rhs.signed_tx_body && - signed_tx_octets == rhs.signed_tx_octets && - viewing_id == rhs.viewing_id && - surveyor_id == rhs.surveyor_id; -} - -bool ReconcileRequestProperties::operator!=( - const ReconcileRequestProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.h deleted file mode 100644 index 8cb8d06c1cbe..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.h +++ /dev/null @@ -1,38 +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_RECONCILE_REQUEST_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_RECONCILE_REQUEST_PROPERTIES_H_ - -#include - -#include "bat/ledger/internal/properties/unsigned_tx_properties.h" - -namespace ledger { - -struct ReconcileRequestProperties { - ReconcileRequestProperties(); - ReconcileRequestProperties( - const ReconcileRequestProperties& properties); - ~ReconcileRequestProperties(); - - bool operator==( - const ReconcileRequestProperties& rhs) const; - - bool operator!=( - const ReconcileRequestProperties& rhs) const; - - std::string type; - std::string signed_tx_headers_digest; - std::string signed_tx_headers_signature; - UnsignedTxProperties signed_tx_body; - std::string signed_tx_octets; - std::string viewing_id; - std::string surveyor_id; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_RECONCILE_REQUEST_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.cc deleted file mode 100644 index 570191de99a0..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.cc +++ /dev/null @@ -1,37 +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/properties/surveyor_properties.h" - -namespace ledger { - -SurveyorProperties::SurveyorProperties() = default; - -SurveyorProperties::SurveyorProperties( - const SurveyorProperties& properties) { - signature = properties.signature; - surveyor_id = properties.surveyor_id; - survey_vk = properties.survey_vk; - registrar_vk = properties.registrar_vk; - survey_sk = properties.survey_sk; -} - -SurveyorProperties::~SurveyorProperties() = default; - -bool SurveyorProperties::operator==( - const SurveyorProperties& rhs) const { - return signature == rhs.signature && - surveyor_id == rhs.surveyor_id && - survey_vk == rhs.survey_vk && - registrar_vk == rhs.registrar_vk && - survey_sk == rhs.survey_sk; -} - -bool SurveyorProperties::operator!=( - const SurveyorProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.h deleted file mode 100644 index 51a709727ecf..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.h +++ /dev/null @@ -1,34 +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_SURVEYOR_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_SURVEYOR_PROPERTIES_H_ - -#include - -namespace ledger { - -struct SurveyorProperties { - SurveyorProperties(); - SurveyorProperties( - const SurveyorProperties& properties); - ~SurveyorProperties(); - - bool operator==( - const SurveyorProperties& rhs) const; - - bool operator!=( - const SurveyorProperties& rhs) const; - - std::string signature; - std::string surveyor_id; - std::string survey_vk; - std::string registrar_vk; - std::string survey_sk; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_SURVEYOR_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.cc deleted file mode 100644 index 74a9b9a13c59..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.cc +++ /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/. */ - -#include "bat/ledger/internal/properties/transaction_ballot_properties.h" - -namespace ledger { - -TransactionBallotProperties::TransactionBallotProperties() - : count(0) {} - -TransactionBallotProperties::TransactionBallotProperties( - const TransactionBallotProperties& properties) { - publisher = properties.publisher; - count = properties.count; -} - -TransactionBallotProperties::~TransactionBallotProperties() = default; - -bool TransactionBallotProperties::operator==( - const TransactionBallotProperties& rhs) const { - return publisher == rhs.publisher && - count == rhs.count; -} - -bool TransactionBallotProperties::operator!=( - const TransactionBallotProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.h deleted file mode 100644 index 2fc1041b07dd..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.h +++ /dev/null @@ -1,35 +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_TRANSACTION_BALLOT_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_TRANSACTION_BALLOT_PROPERTIES_H_ - -#include -#include -#include - -namespace ledger { - -struct TransactionBallotProperties { - TransactionBallotProperties(); - TransactionBallotProperties( - const TransactionBallotProperties& properties); - ~TransactionBallotProperties(); - - bool operator==( - const TransactionBallotProperties& rhs) const; - - bool operator!=( - const TransactionBallotProperties& rhs) const; - - std::string publisher; - uint32_t count; -}; - -typedef std::vector TransactionBallots; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_TRANSACTION_BALLOT_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.cc deleted file mode 100644 index 0f5077051142..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.cc +++ /dev/null @@ -1,51 +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/properties/transaction_properties.h" - -namespace ledger { - -TransactionProperties::TransactionProperties() - : vote_count(0) {} - -TransactionProperties::TransactionProperties( - const TransactionProperties& properties) { - viewing_id = properties.viewing_id; - surveyor_id = properties.surveyor_id; - contribution_rates = properties.contribution_rates; - contribution_probi = properties.contribution_probi; - submission_timestamp = properties.submission_timestamp; - contribution_rates = properties.contribution_rates; - anonize_viewing_id = properties.anonize_viewing_id; - registrar_vk = properties.registrar_vk; - master_user_token = properties.master_user_token; - surveyor_ids = properties.surveyor_ids; - vote_count = properties.vote_count; - transaction_ballots = properties.transaction_ballots; -} - -TransactionProperties::~TransactionProperties() = default; - -bool TransactionProperties::operator==( - const TransactionProperties& rhs) const { - return viewing_id == rhs.viewing_id && - surveyor_id == rhs.surveyor_id && - contribution_rates == rhs.contribution_rates && - contribution_probi == rhs.contribution_probi && - submission_timestamp == rhs.submission_timestamp && - anonize_viewing_id == rhs.anonize_viewing_id && - registrar_vk == rhs.registrar_vk && - master_user_token == rhs.master_user_token && - surveyor_ids == rhs.surveyor_ids && - vote_count == rhs.vote_count && - transaction_ballots == rhs.transaction_ballots; -} - -bool TransactionProperties::operator!=( - const TransactionProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.h deleted file mode 100644 index 94cc3f1b8349..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.h +++ /dev/null @@ -1,47 +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_TRANSACTION_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_TRANSACTION_PROPERTIES_H_ - -#include -#include -#include -#include - -#include "bat/ledger/internal/properties/transaction_ballot_properties.h" - -namespace ledger { - -struct TransactionProperties { - TransactionProperties(); - TransactionProperties( - const TransactionProperties& properties); - ~TransactionProperties(); - - bool operator==( - const TransactionProperties& rhs) const; - - bool operator!=( - const TransactionProperties& rhs) const; - - std::string viewing_id; - std::string surveyor_id; - std::map contribution_rates; - std::string contribution_probi; - std::string submission_timestamp; - std::string anonize_viewing_id; - std::string registrar_vk; - std::string master_user_token; - std::vector surveyor_ids; - uint32_t vote_count; - TransactionBallots transaction_ballots; -}; - -typedef std::vector Transactions; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_TRANSACTION_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.cc deleted file mode 100644 index d0bec517b794..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.cc +++ /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/. */ - -#include "bat/ledger/internal/properties/winner_properties.h" - -namespace ledger { - -WinnerProperties::WinnerProperties() - : vote_count(0) {} - -WinnerProperties::WinnerProperties( - const WinnerProperties& properties) { - direction = properties.direction; - vote_count = properties.vote_count; -} - -WinnerProperties::~WinnerProperties() = default; - -bool WinnerProperties::operator==( - const WinnerProperties& rhs) const { - return direction == rhs.direction && - vote_count == rhs.vote_count; -} - -bool WinnerProperties::operator!=( - const WinnerProperties& rhs) const { - return !(*this == rhs); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.h deleted file mode 100644 index 9bf0ade3490c..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.h +++ /dev/null @@ -1,36 +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_WINNER_PROPERTIES_H_ -#define BRAVELEDGER_PROPERTIES_WINNER_PROPERTIES_H_ - -#include -#include - -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" - -namespace ledger { - -struct WinnerProperties { - WinnerProperties(); - WinnerProperties( - const WinnerProperties& properties); - ~WinnerProperties(); - - bool operator==( - const WinnerProperties& rhs) const; - - bool operator!=( - const WinnerProperties& rhs) const; - - ReconcileDirectionProperties direction; - uint32_t vote_count; -}; - -typedef std::vector Winners; - -} // namespace ledger - -#endif // BRAVELEDGER_PROPERTIES_WINNER_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h index 8102b5091295..2e7fca71c22c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h @@ -12,7 +12,6 @@ #include #include "base/gtest_prod_util.h" -#include "bat/ledger/internal/properties/publisher_properties.h" #include "bat/ledger/internal/properties/publisher_settings_properties.h" #include "bat/ledger/ledger.h" @@ -213,9 +212,6 @@ class Publisher { void SetMigrateScore(bool value); - bool isPublisherVisible( - const ledger::PublisherProperties& publisher_st); - void OnSaveVisitInternal( ledger::Result result, ledger::PublisherInfoPtr info); 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 9d34a25b0d73..e2352f5e3c9a 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 @@ -44,8 +44,16 @@ std::string FetchSignedCredsUrl( return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); } -std::string GetReedemSuggestionsUrl() { - return BuildUrl("/suggestions", PREFIX_V1, ServerTypes::kPromotion); +std::string GetReedemTokensUrl(const ledger::ContributionProcessor processor) { + std::string path = "/suggestions"; + ServerTypes type = ServerTypes::kPromotion; + if (processor == ledger::ContributionProcessor::UPHOLD || + processor == ledger::ContributionProcessor::BRAVE_USER_FUNDS) { + path = "/votes"; + type = ServerTypes::kPayments; + } + + return BuildUrl(path, PREFIX_V1, type); } std::string ReportClobberedClaimsUrl() { 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 9c31802db99f..7e351ea165ae 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 @@ -7,6 +7,7 @@ #define BRAVELEDGER_COMMON_PROMOTION_REQUESTS_H_ #include +#include "bat/ledger/mojom_structs.h" namespace braveledger_request_util { @@ -20,7 +21,7 @@ std::string FetchSignedCredsUrl( const std::string& promotion_id, const std::string& claim_id); -std::string GetReedemSuggestionsUrl(); +std::string GetReedemTokensUrl(const ledger::ContributionProcessor processor); std::string ReportClobberedClaimsUrl(); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_sku.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_sku.cc new file mode 100644 index 000000000000..1b53fd8b6779 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_sku.cc @@ -0,0 +1,68 @@ +/* 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 "base/strings/stringprintf.h" +#include "bat/ledger/internal/static_values.h" +#include "bat/ledger/internal/request/request_sku.h" +#include "bat/ledger/internal/request/request_util.h" + +namespace { + +std::string GetTransactionSuffix(const ledger::SKUTransactionType type) { + switch (type) { + case ledger::SKUTransactionType::NONE: + case ledger::SKUTransactionType::TOKENS: { + return ""; + } + case ledger::SKUTransactionType::UPHOLD: { + return "uphold"; + } + case ledger::SKUTransactionType::ANONYMOUS_CARD: { + return "anonymousCard"; + } + } +} + +} // namespace + +namespace braveledger_request_util { + +std::string GetCreateOrderURL() { + return BuildUrl("/orders", PREFIX_V1, ServerTypes::kPayments); +} + +std::string GetOrderCredentialsURL( + const std::string& order_id, + const std::string& item_id) { + std::string item_path = ""; + if (!item_id.empty()) { + item_path = base::StringPrintf("/%s", item_id.c_str()); + } + + const std::string path = base::StringPrintf( + "/orders/%s/credentials%s", + order_id.c_str(), + item_path.c_str()); + + return BuildUrl(path, PREFIX_V1, ServerTypes::kPayments); +} + +std::string GetCreateTransactionURL( + const std::string& order_id, + const ledger::SKUTransactionType type) { + const std::string suffix = GetTransactionSuffix(type); + const std::string path = base::StringPrintf( + "/orders/%s/transactions/%s", + order_id.c_str(), + suffix.c_str()); + + return BuildUrl(path, PREFIX_V1, ServerTypes::kPayments); +} + +std::string GetReedemSKUUrl() { + return BuildUrl("/votes", PREFIX_V1, ServerTypes::kPayments); +} + +} // namespace braveledger_request_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_sku.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_sku.h new file mode 100644 index 000000000000..02d81712a630 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_sku.h @@ -0,0 +1,29 @@ +/* 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_COMMON_REQUEST_SKU_H_ +#define BRAVELEDGER_COMMON_REQUEST_SKU_H_ + +#include + +#include "bat/ledger/mojom_structs.h" + +namespace braveledger_request_util { + +std::string GetCreateOrderURL(); + +std::string GetOrderCredentialsURL( + const std::string& order_id, + const std::string& item_id = ""); + +std::string GetCreateTransactionURL( + const std::string& order_id, + const ledger::SKUTransactionType type); + +std::string GetReedemSKUUrl(); + +} // namespace braveledger_request_util + +#endif // BRAVELEDGER_COMMON_REQUEST_SKU_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 f1736585212d..f1a2101d6329 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 @@ -101,6 +101,26 @@ std::string BuildPromotionUrl() { return url; } +std::string BuildPaymentsUrl() { + std::string url; + switch (ledger::_environment) { + case ledger::Environment::STAGING: { + url = PAYMENTS_STAGING_SERVER; + break; + } + case ledger::Environment::PRODUCTION: { + url = PAYMENTS_PRODUCTION_SERVER; + break; + } + case ledger::Environment::DEVELOPMENT: { + url = PAYMENTS_DEVELOPMENT_SERVER; + break; + } + } + + return url; +} + } // namespace namespace braveledger_request_util { @@ -131,6 +151,10 @@ std::string BuildUrl( url = BuildPromotionUrl(); break; } + case ServerTypes::kPayments: { + url = BuildPaymentsUrl(); + break; + } } if (url.empty()) { @@ -150,10 +174,11 @@ std::string DigestValue(const std::string& body) { } std::string SignatureHeaderValue( - const std::string& url, + const std::string& data, const std::string& body, - const std::string payment_id, - const std::vector& private_key) { + const std::string key_id, + const std::vector& private_key, + const bool idempotency_key) { DCHECK(!body.empty()); DCHECK(!private_key.empty()); @@ -161,25 +186,52 @@ std::string SignatureHeaderValue( std::vector> headers; headers.push_back({{"digest", digest_header_value}}); - headers.push_back({{"(request-target)", url}}); + if (idempotency_key) { + headers.push_back({{"idempotency-key", data}}); + } else { + headers.push_back({{"(request-target)", data}}); + } return braveledger_helper::Security::Sign( headers, - payment_id, + key_id, private_key); } +std::map GetSignHeaders( + const std::string& data, + const std::string& body, + 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 signature_header = SignatureHeaderValue( + data, + body, + key_id, + private_key, + idempotency_key).c_str(); + + return { + { "digest", digest_header }, + { "signature", signature_header} + }; +} + std::vector BuildSignHeaders( const std::string& url, const std::string& body, - const std::string& payment_id, + const std::string& key_id, const std::vector& private_key) { + auto headers = GetSignHeaders(url, body, key_id, private_key); + DCHECK_EQ(headers.size(), 2ul); + const std::string digest_header = base::StringPrintf( "digest: %s", - DigestValue(body).c_str()); + headers.at("digest").c_str()); const std::string signature_header = base::StringPrintf( "signature: %s", - SignatureHeaderValue(url, body, payment_id, private_key).c_str()); + headers.at("signature").c_str()); const std::string accept_header = "accept: application/json"; 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 e786e2198caf..8462aa428dde 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 @@ -6,6 +6,7 @@ #ifndef BRAVELEDGER_COMMON_REQUEST_UTIL_H_ #define BRAVELEDGER_COMMON_REQUEST_UTIL_H_ +#include #include #include @@ -16,7 +17,8 @@ enum class ServerTypes { BALANCE, PUBLISHER, PUBLISHER_DISTRO, - kPromotion + kPromotion, + kPayments }; std::string BuildUrl( @@ -24,10 +26,17 @@ std::string BuildUrl( const std::string& prefix = "", const ServerTypes& server = ServerTypes::LEDGER); +std::map GetSignHeaders( + const std::string& url, + const std::string& body, + const std::string& key_id, + const std::vector& private_key, + const bool idempotency_key = false); + std::vector BuildSignHeaders( const std::string& url, const std::string& body, - const std::string& payment_id, + const std::string& key_id, const std::vector& private_key); } // namespace braveledger_request_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku.h new file mode 100644 index 000000000000..c3ae10fa414d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku.h @@ -0,0 +1,35 @@ +/* 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_SKU_H_ +#define BRAVELEDGER_SKU_H_ + +#include +#include +#include + +#include "bat/ledger/ledger.h" + +namespace braveledger_sku { + +class SKU { + public: + virtual ~SKU() = default; + + virtual void Retry( + const std::string& order_id, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) = 0; + + virtual void Process( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback, + const std::string& contribution_id = "") = 0; +}; + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_brave.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_brave.cc new file mode 100644 index 000000000000..3994432992a2 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_brave.cc @@ -0,0 +1,157 @@ +/* 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 + +#include "bat/ledger/global_constants.h" +#include "bat/ledger/internal/common/bind_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/sku/sku_brave.h" +#include "bat/ledger/internal/sku/sku_util.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace braveledger_sku { + +SKUBrave::SKUBrave(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), + common_(std::make_unique(ledger)) { + DCHECK(ledger_); +} + +SKUBrave::~SKUBrave() = default; + +void SKUBrave::Process( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback, + const std::string& contribution_id) { + if (!wallet) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Wallet is null"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + auto create_callback = std::bind(&SKUBrave::OrderCreated, + this, + _1, + _2, + *wallet, + contribution_id, + callback); + + common_->CreateOrder(items, create_callback); +} + +void SKUBrave::OrderCreated( + const ledger::Result result, + const std::string& order_id, + const ledger::ExternalWallet& wallet, + const std::string& contribution_id, + ledger::SKUOrderCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order was not successful"; + callback(result, ""); + return; + } + + auto save_callback = std::bind(&SKUBrave::ContributionIdSaved, + this, + _1, + order_id, + wallet, + callback); + + ledger_->SaveContributionIdForSKUOrder( + order_id, + contribution_id, + save_callback); +} + +void SKUBrave::ContributionIdSaved( + const ledger::Result result, + const std::string& order_id, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Contribution id not saved"; + callback(result, ""); + return; + } + + auto get_callback = std::bind(&SKUBrave::CreateTransaction, + this, + _1, + wallet, + callback); + + ledger_->GetSKUOrder(order_id, get_callback); +} + +void SKUBrave::CreateTransaction( + ledger::SKUOrderPtr order, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback) { + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order not found"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + const std::string destination = GetBraveDestination(wallet.type); + + common_->CreateTransaction(std::move(order), destination, wallet, callback); +} + +void SKUBrave::Retry( + const std::string& order_id, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) { + auto get_callback = std::bind(&SKUBrave::OnOrder, + this, + _1, + *wallet, + callback); + + ledger_->GetSKUOrder(order_id, get_callback); +} + +void SKUBrave::OnOrder( + ledger::SKUOrderPtr order, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback) { + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order is null"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + switch (order->status) { + case ledger::SKUOrderStatus::PENDING: { + ContributionIdSaved( + ledger::Result::LEDGER_OK, + order->order_id, + wallet, + callback); + return; + } + case ledger::SKUOrderStatus::PAID: { + common_->SendExternalTransaction(order->order_id, callback); + return; + } + case ledger::SKUOrderStatus::FULFILLED: { + callback(ledger::Result::LEDGER_OK, order->order_id); + return; + } + case ledger::SKUOrderStatus::CANCELED: + case ledger::SKUOrderStatus::NONE: { + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + } +} + +} // namespace braveledger_sku diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_brave.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_brave.h new file mode 100644 index 000000000000..051297ac4d3f --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_brave.h @@ -0,0 +1,69 @@ +/* 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_SKU_BRAVE_H_ +#define BRAVELEDGER_SKU_BRAVE_H_ + +#include +#include +#include + +#include "bat/ledger/internal/sku/sku.h" +#include "bat/ledger/internal/sku/sku_common.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_sku { + +class SKUBrave : public SKU { + public: + explicit SKUBrave(bat_ledger::LedgerImpl* ledger); + ~SKUBrave() override; + + void Process( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback, + const std::string& contribution_id = "") override; + + void Retry( + const std::string& order_id, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) override; + + private: + void OrderCreated( + const ledger::Result result, + const std::string& order_id, + const ledger::ExternalWallet& wallet, + const std::string& contribution_id, + ledger::SKUOrderCallback callback); + + void ContributionIdSaved( + const ledger::Result result, + const std::string& order_id, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback); + + void CreateTransaction( + ledger::SKUOrderPtr order, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback); + + void OnOrder( + ledger::SKUOrderPtr order, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr common_; +}; + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_BRAVE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_common.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_common.cc new file mode 100644 index 000000000000..ed2517635733 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_common.cc @@ -0,0 +1,102 @@ +/* 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 + +#include "bat/ledger/global_constants.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/sku/sku_common.h" + +using std::placeholders::_1; + +namespace braveledger_sku { + +SKUCommon::SKUCommon(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), + order_(std::make_unique(ledger)), + transaction_(std::make_unique(ledger)) { + DCHECK(ledger_); +} + +SKUCommon::~SKUCommon() = default; + +void SKUCommon::CreateOrder( + const std::vector& items, + ledger::SKUOrderCallback callback) { + order_->Create(items, callback); +} + +void SKUCommon::CreateTransaction( + ledger::SKUOrderPtr order, + const std::string& destination, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback) { + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order not found"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + auto create_callback = std::bind(&SKUCommon::OnTransactionCompleted, + this, + _1, + order->order_id, + callback); + + transaction_->Create( + order->Clone(), + destination, + wallet, + create_callback); +} + +void SKUCommon::OnTransactionCompleted( + const ledger::Result result, + const std::string& order_id, + ledger::SKUOrderCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Order status was not updated"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + callback(ledger::Result::LEDGER_OK, order_id); +} + +void SKUCommon::SendExternalTransaction( + const std::string& order_id, + ledger::SKUOrderCallback callback) { + auto get_callback = std::bind(&SKUCommon::GetSKUTransactionByOrderId, + this, + _1, + callback); + + ledger_->GetSKUTransactionByOrderId(order_id, get_callback); +} + +void SKUCommon::GetSKUTransactionByOrderId( + ledger::SKUTransactionPtr transaction, + ledger::SKUOrderCallback callback) { + if (!transaction) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Transaction is null"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + auto create_callback = std::bind(&SKUCommon::OnTransactionCompleted, + this, + _1, + transaction->order_id, + callback); + + transaction_->SendExternalTransaction( + ledger::Result::LEDGER_OK, + *transaction, + create_callback); +} + +} // namespace braveledger_sku diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_common.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_common.h new file mode 100644 index 000000000000..b4c6a1e84b42 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_common.h @@ -0,0 +1,59 @@ +/* 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_SKU_COMMON_H_ +#define BRAVELEDGER_SKU_COMMON_H_ + +#include +#include +#include + +#include "bat/ledger/internal/sku/sku_order.h" +#include "bat/ledger/internal/sku/sku_transaction.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_sku { + +class SKUCommon { + public: + explicit SKUCommon(bat_ledger::LedgerImpl* ledger); + ~SKUCommon(); + + void CreateOrder( + const std::vector& items, + ledger::SKUOrderCallback callback); + + void CreateTransaction( + ledger::SKUOrderPtr order, + const std::string& destination, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback); + + void SendExternalTransaction( + const std::string& order_id, + ledger::SKUOrderCallback callback); + + private: + void OnTransactionCompleted( + const ledger::Result result, + const std::string& order_id, + ledger::SKUOrderCallback callback); + + void GetSKUTransactionByOrderId( + ledger::SKUTransactionPtr transaction, + ledger::SKUOrderCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr order_; + std::unique_ptr transaction_; +}; + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_COMMON_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_factory.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_factory.cc new file mode 100644 index 000000000000..43a76204d021 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_factory.cc @@ -0,0 +1,27 @@ +/* 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/sku/sku_factory.h" +#include "bat/ledger/internal/ledger_impl.h" + +namespace braveledger_sku { + +std::unique_ptr SKUFactory::Create( + bat_ledger::LedgerImpl* ledger, + const SKUType type) { + DCHECK(ledger); + + switch (type) { + case SKUType::kBrave: { + return std::make_unique(ledger); + } + + case SKUType::kMerchant: { + return std::make_unique(ledger); + } + } +} + +} // namespace braveledger_sku diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_factory.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_factory.h new file mode 100644 index 000000000000..f73e692a4c97 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_factory.h @@ -0,0 +1,35 @@ +/* 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_SKU_FACTORY_H_ +#define BRAVELEDGER_SKU_FACTORY_H_ + +#include + +#include "bat/ledger/internal/sku/sku.h" +#include "bat/ledger/internal/sku/sku_brave.h" +#include "bat/ledger/internal/sku/sku_merchant.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_sku { + +enum SKUType { + kBrave = 0, + kMerchant = 1 +}; + +class SKUFactory { + public: + static std::unique_ptr Create( + bat_ledger::LedgerImpl* ledger, + const SKUType type); +}; + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_FACTORY_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_merchant.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_merchant.cc new file mode 100644 index 000000000000..c7a961b7caf3 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_merchant.cc @@ -0,0 +1,124 @@ +/* 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 + +#include "bat/ledger/global_constants.h" +#include "bat/ledger/internal/common/bind_util.h" +#include "bat/ledger/internal/sku/sku_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/sku/sku_merchant.h" + +using std::placeholders::_1; +using std::placeholders::_2; + +namespace braveledger_sku { + +SKUMerchant::SKUMerchant(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), + common_(std::make_unique(ledger)) { + DCHECK(ledger_); +} + +SKUMerchant::~SKUMerchant() = default; + +void SKUMerchant::Process( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback, + const std::string& contribution_id) { + if (!wallet) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Wallet is null"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + auto create_callback = std::bind(&SKUMerchant::OrderCreated, + this, + _1, + _2, + *wallet, + callback); + + common_->CreateOrder(items, create_callback); +} + +void SKUMerchant::OrderCreated( + const ledger::Result result, + const std::string& order_id, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order was not successful"; + callback(result, ""); + return; + } + + auto get_callback = std::bind(&SKUMerchant::OnOrder, + this, + _1, + wallet, + callback); + + ledger_->GetSKUOrder(order_id, get_callback); +} + +void SKUMerchant::OnOrder( + ledger::SKUOrderPtr order, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback) { + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order is null"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + if (wallet.type == ledger::kWalletUphold) { + auto publisher_callback = + std::bind(&SKUMerchant::OnServerPublisherInfo, + this, + _1, + braveledger_bind_util::FromSKUOrderToString(std::move(order)), + wallet, + callback); + + ledger_->GetServerPublisherInfo(order->merchant_id, publisher_callback); + return; + } + + common_->CreateTransaction(std::move(order), "", wallet, callback); +} + +void SKUMerchant::OnServerPublisherInfo( + ledger::ServerPublisherInfoPtr info, + const std::string& order_string, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback) { + auto order = braveledger_bind_util::FromStringToSKUOrder(order_string); + if (!order || !info) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order/Publisher not found"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + if (info->address.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Publisher address is empty"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + common_->CreateTransaction(std::move(order), info->address, wallet, callback); +} + +void SKUMerchant::Retry( + const std::string& order_id, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) { + // We will implement retry logic when we will have more complex flows, + // right now there is nothing to retry + NOTREACHED(); +} + +} // namespace braveledger_sku diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_merchant.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_merchant.h new file mode 100644 index 000000000000..5f1bc8dac0d3 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_merchant.h @@ -0,0 +1,63 @@ +/* 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_SKU_MERCHANT_H_ +#define BRAVELEDGER_SKU_MERCHANT_H_ + +#include +#include +#include + +#include "bat/ledger/internal/sku/sku.h" +#include "bat/ledger/internal/sku/sku_common.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_sku { + +class SKUMerchant : public SKU { + public: + explicit SKUMerchant(bat_ledger::LedgerImpl* ledger); + ~SKUMerchant() override; + + void Process( + const std::vector& items, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback, + const std::string& contribution_id = "") override; + + void Retry( + const std::string& order_id, + ledger::ExternalWalletPtr wallet, + ledger::SKUOrderCallback callback) override; + + private: + void OrderCreated( + const ledger::Result result, + const std::string& order_id, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback); + + void OnOrder( + ledger::SKUOrderPtr order, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback); + + void OnServerPublisherInfo( + ledger::ServerPublisherInfoPtr info, + const std::string& order_string, + const ledger::ExternalWallet& wallet, + ledger::SKUOrderCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr common_; +}; + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_MERCHANT_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_order.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_order.cc new file mode 100644 index 000000000000..852bbdf17c86 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_order.cc @@ -0,0 +1,107 @@ +/* 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 + +#include "base/json/json_writer.h" +#include "base/values.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_sku.h" +#include "bat/ledger/internal/sku/sku_order.h" +#include "bat/ledger/internal/sku/sku_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; +using std::placeholders::_2; +using std::placeholders::_3; + +namespace braveledger_sku { + +SKUOrder::SKUOrder(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { + DCHECK(ledger_); +} + +SKUOrder::~SKUOrder() = default; + +void SKUOrder::Create( + const std::vector& items, + ledger::SKUOrderCallback callback) { + base::Value order_items(base::Value::Type::LIST); + for (const auto& item : items) { + base::Value order_item(base::Value::Type::DICTIONARY); + order_item.SetStringKey("sku", item.sku); + order_item.SetIntKey("quantity", item.quantity); + order_items.Append(std::move(order_item)); + } + + base::Value body(base::Value::Type::DICTIONARY); + body.SetKey("items", std::move(order_items)); + + std::string json; + base::JSONWriter::Write(body, &json); + + auto url_callback = std::bind(&SKUOrder::OnCreate, + this, + _1, + _2, + _3, + items, + callback); + + const std::string url = braveledger_request_util::GetCreateOrderURL(); + + ledger_->LoadURL( + url, + std::vector(), + json, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void SKUOrder::OnCreate( + const int response_status_code, + const std::string& response, + const std::map& headers, + const std::vector& order_items, + ledger::SKUOrderCallback callback) { + ledger_->LogResponse(__func__, response_status_code, response, headers); + if (response_status_code != net::HTTP_CREATED) { + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + auto order = ParseOrderCreateResponse(response, order_items); + + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Order response could not be parsed"; + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + auto save_callback = std::bind(&SKUOrder::OnCreateSave, + this, + _1, + order->order_id, + callback); + + ledger_->SaveSKUOrder(order->Clone(), save_callback); +} + +void SKUOrder::OnCreateSave( + const ledger::Result result, + const std::string& order_id, + ledger::SKUOrderCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order couldn't be saved"; + callback(result, ""); + return; + } + + callback(ledger::Result::LEDGER_OK, order_id); +} + +} // namespace braveledger_sku diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_order.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_order.h new file mode 100644 index 000000000000..22238c3415fa --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_order.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_SKU_ORDER_H_ +#define BRAVELEDGER_SKU_ORDER_H_ + +#include +#include +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_sku { + +class SKUOrder { + public: + explicit SKUOrder(bat_ledger::LedgerImpl* ledger); + ~SKUOrder(); + + void Create( + const std::vector& items, + ledger::SKUOrderCallback callback); + + private: + void OnCreate( + const int response_status_code, + const std::string& response, + const std::map& headers, + const std::vector& order_items, + ledger::SKUOrderCallback callback); + + void OnCreateSave( + const ledger::Result result, + const std::string& order_id, + ledger::SKUOrderCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_ORDER_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_transaction.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_transaction.cc new file mode 100644 index 000000000000..d01de792a7f1 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_transaction.cc @@ -0,0 +1,232 @@ +/* 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 + +#include "base/guid.h" +#include "base/json/json_writer.h" +#include "base/values.h" +#include "bat/ledger/global_constants.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_sku.h" +#include "bat/ledger/internal/sku/sku_transaction.h" +#include "bat/ledger/internal/sku/sku_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; +using std::placeholders::_2; +using std::placeholders::_3; + +namespace { + +ledger::SKUTransactionType GetTransactionTypeFromWalletType( + const std::string& wallet_type) { + if (wallet_type == ledger::kWalletUphold) { + return ledger::SKUTransactionType::UPHOLD; + } + + if (wallet_type == ledger::kWalletAnonymous) { + return ledger::SKUTransactionType::ANONYMOUS_CARD; + } + + if (wallet_type == ledger::kWalletUnBlinded) { + return ledger::SKUTransactionType::TOKENS; + } + + NOTREACHED(); + return ledger::SKUTransactionType::ANONYMOUS_CARD; +} + +} // namespace + +namespace braveledger_sku { + +SKUTransaction::SKUTransaction(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger) { + DCHECK(ledger_); +} + +SKUTransaction::~SKUTransaction() = default; + +void SKUTransaction::Create( + ledger::SKUOrderPtr order, + const std::string& destination, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback) { + if (!order) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order is null"; + callback(ledger::Result::LEDGER_ERROR); + return; + } + + auto transaction = ledger::SKUTransaction::New(); + transaction->transaction_id = base::GenerateGUID(); + transaction->order_id = order->order_id; + transaction->type = GetTransactionTypeFromWalletType(wallet.type); + transaction->amount = order->total_amount; + transaction->status = ledger::SKUTransactionStatus::CREATED; + + auto save_callback = std::bind(&SKUTransaction::OnTransactionSaved, + this, + _1, + *transaction, + destination, + wallet, + callback); + + ledger_->SaveSKUTransaction(transaction->Clone(), save_callback); +} + +void SKUTransaction::OnTransactionSaved( + const ledger::Result result, + const ledger::SKUTransaction& transaction, + const std::string& destination, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Transaction was not saved"; + callback(result); + return; + } + + auto transfer_callback = std::bind(&SKUTransaction::OnTransfer, + this, + _1, + _2, + transaction, + callback); + + ledger_->TransferFunds( + transaction, + destination, + ledger::ExternalWallet::New(wallet), + transfer_callback); +} + +void SKUTransaction::OnTransfer( + const ledger::Result result, + const std::string& external_transaction_id, + const ledger::SKUTransaction& transaction, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "Transaction for order failed " + << transaction.order_id; + callback(result); + return; + } + + if (external_transaction_id.empty()) { + callback(ledger::Result::LEDGER_OK); + return; + } + + auto transaction_new = transaction; + transaction_new.external_transaction_id = external_transaction_id; + + auto save_callback = std::bind(&SKUTransaction::OnSaveSKUExternalTransaction, + this, + _1, + transaction_new, + callback); + + // We save SKUTransactionStatus::COMPLETED status in this call + ledger_->SaveSKUExternalTransaction( + transaction.transaction_id, + external_transaction_id, + save_callback); +} + +void SKUTransaction::OnSaveSKUExternalTransaction( + const ledger::Result result, + const ledger::SKUTransaction& transaction, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "External transaction was not saved"; + callback(result); + return; + } + + auto save_callback = std::bind(&SKUTransaction::SendExternalTransaction, + this, + _1, + transaction, + callback); + + ledger_->UpdateSKUOrderStatus( + transaction.order_id, + ledger::SKUOrderStatus::PAID, + save_callback); +} + +void SKUTransaction::SendExternalTransaction( + const ledger::Result result, + const ledger::SKUTransaction& transaction, + ledger::ResultCallback callback) { + if (result != ledger::Result::LEDGER_OK) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Order status not updated"; + callback(ledger::Result::RETRY); + return; + } + + // we only want to report external transaction id when we have it + // we don't have it for all transactions + if (transaction.external_transaction_id.empty()) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "External transaction id is empty for transaction id " + << transaction.transaction_id; + callback(ledger::Result::LEDGER_OK); + return; + } + + base::Value body(base::Value::Type::DICTIONARY); + body.SetStringKey( + "externalTransactionId", + transaction.external_transaction_id); + body.SetStringKey( + "kind", + ConvertTransactionTypeToString(transaction.type)); + + std::string json; + base::JSONWriter::Write(body, &json); + + auto url_callback = std::bind(&SKUTransaction::OnSendExternalTransaction, + this, + _1, + _2, + _3, + callback); + + const std::string url = braveledger_request_util::GetCreateTransactionURL( + transaction.order_id, + transaction.type); + + ledger_->LoadURL( + url, + std::vector(), + json, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void SKUTransaction::OnSendExternalTransaction( + const int response_status_code, + const std::string& response, + const std::map& headers, + ledger::ResultCallback callback) { + ledger_->LogResponse(__func__, response_status_code, response, headers); + if (response_status_code != net::HTTP_CREATED) { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) + << "External transaction not sent"; + callback(ledger::Result::RETRY); + return; + } + + callback(ledger::Result::LEDGER_OK); +} + +} // namespace braveledger_sku diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_transaction.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_transaction.h new file mode 100644 index 000000000000..86d4d49335f9 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_transaction.h @@ -0,0 +1,66 @@ +/* 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_SKU_TRANSACTION_H_ +#define BRAVELEDGER_SKU_TRANSACTION_H_ + +#include +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace braveledger_sku { + +class SKUTransaction { + public: + explicit SKUTransaction(bat_ledger::LedgerImpl* ledger); + ~SKUTransaction(); + + void Create( + ledger::SKUOrderPtr order, + const std::string& destination, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback); + + void SendExternalTransaction( + const ledger::Result result, + const ledger::SKUTransaction& transaction, + ledger::ResultCallback callback); + + private: + void OnTransactionSaved( + const ledger::Result result, + const ledger::SKUTransaction& transaction, + const std::string& destination, + const ledger::ExternalWallet& wallet, + ledger::ResultCallback callback); + + void OnTransfer( + const ledger::Result result, + const std::string& external_transaction_id, + const ledger::SKUTransaction& transaction, + ledger::ResultCallback callback); + + void OnSaveSKUExternalTransaction( + const ledger::Result result, + const ledger::SKUTransaction& transaction, + ledger::ResultCallback callback); + + void OnSendExternalTransaction( + const int response_status_code, + const std::string& response, + const std::map& headers, + ledger::ResultCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_TRANSACTION_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_util.cc new file mode 100644 index 000000000000..6729183c89b4 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_util.cc @@ -0,0 +1,180 @@ +/* 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 + +#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/sku/sku_util.h" +#include "bat/ledger/ledger.h" + +namespace braveledger_sku { + +const char kAnonCardDestinationDev[] = + "9094c3f2-b3ae-438f-bd59-92aaad92de5c"; +const char kAnonCardDestinationStaging[] = + "6654ecb0-6079-4f6c-ba58-791cc890a561"; +const char kAnonCardDestinationProduction[] = + "86f26f49-9d3b-4f97-9b56-d305ad7a856f"; + +const char kUpholdDestinationDev[] = + "9094c3f2-b3ae-438f-bd59-92aaad92de5c"; +const char kUpholdDestinationStaging[] = + "6654ecb0-6079-4f6c-ba58-791cc890a561"; +const char kUpholdDestinationProduction[] = + "5d4be2ad-1c65-4802-bea1-e0f3a3a487cb"; + +ledger::SKUOrderPtr ParseOrderCreateResponse( + const std::string& response, + const std::vector& order_items) { + base::Optional dictionary = base::JSONReader::Read(response); + if (!dictionary || !dictionary->is_dict()) { + return nullptr; + } + + auto order = ledger::SKUOrder::New(); + + const auto* id = dictionary->FindStringKey("id"); + if (id) { + order->order_id = *id; + } + + if (order->order_id.empty()) { + return nullptr; + } + + const auto* total_amount = dictionary->FindStringKey("totalPrice"); + if (total_amount) { + order->total_amount = std::stod(*total_amount); + } + + const auto* merchant_id = dictionary->FindStringKey("merchantId"); + if (merchant_id) { + order->merchant_id = *merchant_id; + } + + const auto* location = dictionary->FindStringKey("location"); + if (location) { + order->location = *location; + } + + order->status = ledger::SKUOrderStatus::PENDING; + + auto* items = dictionary->FindListKey("items"); + if (items) { + if (items->GetList().size() != order_items.size()) { + return nullptr; + } + + int count = 0; + for (auto& item : items->GetList()) { + auto order_item = ledger::SKUOrderItem::New(); + order_item->order_id = order->order_id; + order_item->sku = order_items[count].sku; + order_item->type = order_items[count].type; + + const auto* id = item.FindStringKey("id"); + if (id) { + order_item->order_item_id = *id; + } + + const auto quantity = item.FindIntKey("quantity"); + if (quantity) { + order_item->quantity = *quantity; + } + + const auto* price = item.FindStringKey("price"); + if (price) { + const bool success = base::StringToDouble(*price, &order_item->price); + if (!success) { + order_item->price = 0.0; + } + } + + const auto* name = item.FindStringKey("name"); + if (name) { + order_item->name = *name; + } + + const auto* description = item.FindStringKey("description"); + if (description) { + order_item->description = *description; + } + + order->items.push_back(std::move(order_item)); + + count++; + } + } + + return order; +} + +std::string ConvertTransactionTypeToString( + const ledger::SKUTransactionType type) { + switch (type) { + case ledger::SKUTransactionType::UPHOLD: { + return "uphold"; + } + case ledger::SKUTransactionType::ANONYMOUS_CARD: { + return "anonymous-card"; + } + case ledger::SKUTransactionType::NONE: + case ledger::SKUTransactionType::TOKENS: { + return ""; + } + } +} + +std::string GetBraveDestination(const std::string& wallet_type) { + if (wallet_type == ledger::kWalletUphold) { + return GetUpholdDestination(); + } + + if (wallet_type == ledger::kWalletAnonymous) { + return GetAnonCardDestination(); + } + + NOTREACHED(); + return ""; +} + +std::string GetAnonCardDestination() { + if (ledger::_environment == ledger::Environment::PRODUCTION) { + return kAnonCardDestinationProduction; + } + + if (ledger::_environment == ledger::Environment::STAGING) { + return kAnonCardDestinationStaging; + } + + if (ledger::_environment == ledger::Environment::DEVELOPMENT) { + return kAnonCardDestinationDev; + } + + NOTREACHED(); + return kAnonCardDestinationDev; +} + +std::string GetUpholdDestination() { + if (ledger::_environment == ledger::Environment::PRODUCTION) { + return kUpholdDestinationProduction; + } + + if (ledger::_environment == ledger::Environment::STAGING) { + return kUpholdDestinationStaging; + } + + if (ledger::_environment == ledger::Environment::DEVELOPMENT) { + return kUpholdDestinationDev; + } + + NOTREACHED(); + return kUpholdDestinationDev; +} + +} // namespace braveledger_sku diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_util.h new file mode 100644 index 000000000000..5640ab5e6893 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/sku/sku_util.h @@ -0,0 +1,31 @@ +/* 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_SKU_SKU_UTIL_H_ +#define BRAVELEDGER_SKU_SKU_UTIL_H_ + +#include +#include + +#include "bat/ledger/mojom_structs.h" + +namespace braveledger_sku { + +ledger::SKUOrderPtr ParseOrderCreateResponse( + const std::string& response, + const std::vector& order_items); + +std::string ConvertTransactionTypeToString( + const ledger::SKUTransactionType type); + +std::string GetBraveDestination(const std::string& wallet_type); + +std::string GetAnonCardDestination(); + +std::string GetUpholdDestination(); + +} // namespace braveledger_sku + +#endif // BRAVELEDGER_SKU_SKU_UTIL_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.cc deleted file mode 100644 index ed4b79b45042..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.cc +++ /dev/null @@ -1,160 +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/state/ballot_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kCountKey[] = "offset"; -const char kPrepareBallotKey[] = "prepareBallot"; -const char kPublisherKey[] = "publisher"; -const char kSurveyorIdKey[] = "surveyorId"; -const char kViewingIdKey[] = "viewingId"; - -} // namespace - -BallotState::BallotState() = default; - -BallotState::~BallotState() = default; - -bool BallotState::FromJson( - const std::string& json, - BallotProperties* 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 BallotState::FromDict( - const base::DictionaryValue* dictionary, - BallotProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - BallotProperties ballot_properties; - - // Viewing Id - const auto* viewing_id = dictionary->FindStringKey(kViewingIdKey); - if (!viewing_id) { - NOTREACHED(); - return false; - } - ballot_properties.viewing_id = *viewing_id; - - // Surveyor Id - const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); - if (!surveyor_id) { - NOTREACHED(); - return false; - } - ballot_properties.surveyor_id = *surveyor_id; - - // Publisher - const auto* publisher = dictionary->FindStringKey(kPublisherKey); - if (!publisher) { - NOTREACHED(); - return false; - } - ballot_properties.publisher = *publisher; - - // Offset (There is no support for unsigned int. Writing JSON with such types - // violates the spec. As we need an unsigned int, we need to a double and cast - // to an unsigned int) - const auto count = dictionary->FindDoubleKey(kCountKey); - if (!count) { - NOTREACHED(); - return false; - } - ballot_properties.count = static_cast(*count); - - // Prepare Ballot - const auto* prepare_ballot = dictionary->FindStringKey(kPrepareBallotKey); - if (!prepare_ballot) { - NOTREACHED(); - return false; - } - ballot_properties.prepare_ballot = *prepare_ballot; - - *properties = ballot_properties; - - return true; -} - -bool BallotState::ToJson( - JsonWriter* writer, - const BallotProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kViewingIdKey); - writer->String(properties.viewing_id.c_str()); - - writer->String(kSurveyorIdKey); - writer->String(properties.surveyor_id.c_str()); - - writer->String(kPublisherKey); - writer->String(properties.publisher.c_str()); - - writer->String(kCountKey); - writer->Uint(properties.count); - - writer->String(kPrepareBallotKey); - writer->String(properties.prepare_ballot.c_str()); - - writer->EndObject(); - - return true; -} - -std::string BallotState::ToJson( - const BallotProperties& 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/state/ballot_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.h deleted file mode 100644 index 4aa3ab5c26a5..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.h +++ /dev/null @@ -1,45 +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_STATE_BALLOT_STATE_H_ -#define BRAVELEDGER_STATE_BALLOT_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/ballot_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class BallotState - : public state::Reader, - public state::Writer { - public: - BallotState(); - ~BallotState(); - - bool FromJson( - const std::string& json, - BallotProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - BallotProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const BallotProperties& properties) const override; - - std::string ToJson( - const BallotProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_BALLOT_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc deleted file mode 100644 index 85de9c0be184..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc +++ /dev/null @@ -1,54 +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 - -#include "bat/ledger/internal/state/ballot_state.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=BallotStateTest.* - -namespace ledger { - -TEST(BallotStateTest, ToJsonSerialization) { - // Arrange - BallotProperties ballot_properties; - ballot_properties.viewing_id = "ViewingId"; - ballot_properties.surveyor_id = "SurveyorId"; - ballot_properties.publisher = "Publisher"; - ballot_properties.count = std::numeric_limits::max(); - ballot_properties.prepare_ballot = "PrepareBallot"; - - // Act - const BallotState ballot_state; - const std::string json = ballot_state.ToJson(ballot_properties); - - // Assert - BallotProperties expected_ballot_properties; - ballot_state.FromJson(json, &expected_ballot_properties); - EXPECT_EQ(expected_ballot_properties, ballot_properties); -} - -TEST(BallotStateTest, FromJsonDeserialization) { - // Arrange - BallotProperties ballot_properties; - ballot_properties.viewing_id = "ViewingId"; - ballot_properties.surveyor_id = "SurveyorId"; - ballot_properties.publisher = "Publisher"; - ballot_properties.count = std::numeric_limits::max(); - ballot_properties.prepare_ballot = "PrepareBallot"; - - const std::string json = "{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"}"; // NOLINT - - // Act - BallotProperties expected_ballot_properties; - const BallotState ballot_state; - ballot_state.FromJson(json, &expected_ballot_properties); - - // Assert - EXPECT_EQ(expected_ballot_properties, ballot_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.cc index f57f8a920937..8f72e4cde234 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.cc @@ -7,10 +7,6 @@ #include #include "bat/ledger/internal/state/client_state.h" -#include "bat/ledger/internal/state/ballot_state.h" -#include "bat/ledger/internal/state/publisher_votes_state.h" -#include "bat/ledger/internal/state/transaction_state.h" -#include "bat/ledger/internal/state/current_reconcile_state.h" #include "bat/ledger/internal/state/wallet_info_state.h" #include "bat/ledger/internal/state/wallet_state.h" #include "base/json/json_reader.h" @@ -22,22 +18,14 @@ namespace { // Do not change these values as they are required to transition legacy state const char kAutoContributeKey[] = "auto_contribute"; -const char kBallotsKey[] = "ballots"; -const char kPublisherVotesKey[] = "batch"; const char kBootTimestampKey[] = "bootStamp"; -const char kCurrentReconcilesKey[] = "current_reconciles"; -const char kDaysKey[] = "days"; const char kFeeAmountKey[] = "fee_amount"; -const char kFeeCurrencyKey[] = "fee_currency"; const char kInlineTipsKey[] = "inlineTip"; -const char kMasterUserTokenKey[] = "masterUserToken"; const char kPersonaIdKey[] = "personaId"; const char kPreFlightKey[] = "preFlight"; const char kReconcileTimestampKey[] = "reconcileStamp"; const char kRegistrarVkKey[] = "registrarVK"; const char kRewardsEnabledKey[] = "rewards_enabled"; -const char kSettingsKey[] = "settings"; -const char kTransactionsKey[] = "transactions"; const char kUserChangedFeeKey[] = "user_changed_fee"; const char kUserIdKey[] = "userId"; const char kWalletInfoKey[] = "walletInfo"; @@ -157,15 +145,6 @@ bool ClientState::FromDict( } client_properties.registrar_vk = *registrar_vk; - // Master User Token - const auto* master_user_token = - dictionary->FindStringKey(kMasterUserTokenKey); - if (!master_user_token) { - NOTREACHED(); - return false; - } - client_properties.master_user_token = *master_user_token; - // Pre Flight const auto* pre_flight = dictionary->FindStringKey(kPreFlightKey); if (!pre_flight) { @@ -174,22 +153,6 @@ bool ClientState::FromDict( } client_properties.pre_flight = *pre_flight; - // Fee Currency - const auto* fee_currency = dictionary->FindStringKey(kFeeCurrencyKey); - if (!fee_currency) { - NOTREACHED(); - return false; - } - client_properties.fee_currency = *fee_currency; - - // Settings - const auto* settings = dictionary->FindStringKey(kSettingsKey); - if (!settings) { - NOTREACHED(); - return false; - } - client_properties.settings = *settings; - // Fee Amount const auto fee_amount = dictionary->FindDoubleKey(kFeeAmountKey); if (!fee_amount) { @@ -206,16 +169,6 @@ bool ClientState::FromDict( } client_properties.user_changed_fee = *user_changed_fee; - // Days (There is no support for unsigned int. Writing JSON with such types - // violates the spec. As we need an unsigned int, we need to a double and cast - // to an unsigned int) - const auto days = dictionary->FindDoubleKey(kDaysKey); - if (!days) { - NOTREACHED(); - return false; - } - client_properties.days = static_cast(*days); - // Auto Contribute const auto auto_contribute = dictionary->FindBoolKey(kAutoContributeKey); if (!auto_contribute) { @@ -232,132 +185,6 @@ bool ClientState::FromDict( } client_properties.rewards_enabled = *rewards_enabled; - // Transactions - const auto* transaction_list = dictionary->FindListKey(kTransactionsKey); - if (!transaction_list) { - NOTREACHED(); - return false; - } - - const TransactionState transaction_state; - for (const auto& transaction_value : transaction_list->GetList()) { - if (!transaction_value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* transaction_dictionary = nullptr; - transaction_value.GetAsDictionary(&transaction_dictionary); - if (!transaction_dictionary) { - NOTREACHED(); - continue; - } - - TransactionProperties transaction; - if (!transaction_state.FromDict(transaction_dictionary, &transaction)) { - continue; - } - - client_properties.transactions.push_back(transaction); - } - - // Ballots - const auto* ballot_list = dictionary->FindListKey(kBallotsKey); - if (!ballot_list) { - NOTREACHED(); - return false; - } - - const BallotState ballot_state; - for (const auto& ballot_value : ballot_list->GetList()) { - if (!ballot_value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* ballot_dictionary = nullptr; - ballot_value.GetAsDictionary(&ballot_dictionary); - if (!ballot_dictionary) { - NOTREACHED(); - continue; - } - - BallotProperties ballot; - if (!ballot_state.FromDict(ballot_dictionary, &ballot)) { - continue; - } - - client_properties.ballots.push_back(ballot); - } - - // Publisher Votes - const auto* publisher_votes_list = - dictionary->FindListKey(kPublisherVotesKey); - if (!publisher_votes_list) { - NOTREACHED(); - return false; - } - - const PublisherVotesState publisher_votes_state; - for (const auto& publisher_votes_value : publisher_votes_list->GetList()) { - if (!publisher_votes_value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* publisher_votes_dictionary = nullptr; - publisher_votes_value.GetAsDictionary(&publisher_votes_dictionary); - if (!publisher_votes_dictionary) { - NOTREACHED(); - continue; - } - - PublisherVotesProperties publisher_votes; - if (!publisher_votes_state.FromDict(publisher_votes_dictionary, - &publisher_votes)) { - continue; - } - - client_properties.publisher_votes.push_back(publisher_votes); - } - - // Current Reconciles - const auto* current_reconciles_value = - dictionary->FindKey(kCurrentReconcilesKey); - if (current_reconciles_value) { - if (!current_reconciles_value->is_dict()) { - NOTREACHED(); - return false; - } - - const CurrentReconcileState current_reconcile_state; - for (const auto& current_reconcile_value : - current_reconciles_value->DictItems()) { - const auto& key = current_reconcile_value.first; - const auto& value = current_reconcile_value.second; - - if (!value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* current_reconcile_dictionary = nullptr; - value.GetAsDictionary(¤t_reconcile_dictionary); - if (!current_reconcile_dictionary) { - NOTREACHED(); - continue; - } - - CurrentReconcileProperties current_reconcile; - if (!current_reconcile_state.FromDict(current_reconcile_dictionary, - ¤t_reconcile)) { - continue; - } - - client_properties.current_reconciles.insert({key, current_reconcile}); - } - } - // Wallet const auto* wallet_value = dictionary->FindKey(kWalletKey); if (!wallet_value || !wallet_value->is_dict()) { @@ -435,75 +262,21 @@ bool ClientState::ToJson( writer->String(kRegistrarVkKey); writer->String(properties.registrar_vk.c_str()); - writer->String(kMasterUserTokenKey); - writer->String(properties.master_user_token.c_str()); - writer->String(kPreFlightKey); writer->String(properties.pre_flight.c_str()); - writer->String(kFeeCurrencyKey); - writer->String(properties.fee_currency.c_str()); - - writer->String(kSettingsKey); - writer->String(properties.settings.c_str()); - writer->String(kFeeAmountKey); writer->Double(properties.fee_amount); writer->String(kUserChangedFeeKey); writer->Bool(properties.user_changed_fee); - writer->String(kDaysKey); - writer->Uint(properties.days); - writer->String(kRewardsEnabledKey); writer->Bool(properties.rewards_enabled); writer->String(kAutoContributeKey); writer->Bool(properties.auto_contribute); - writer->String(kTransactionsKey); - writer->StartArray(); - const TransactionState transaction_state; - for (const auto& transaction : properties.transactions) { - transaction_state.ToJson(writer, transaction); - } - writer->EndArray(); - - writer->String(kBallotsKey); - writer->StartArray(); - const BallotState ballot_state; - for (const auto& ballot : properties.ballots) { - if (!ballot_state.ToJson(writer, ballot)) { - NOTREACHED(); - continue; - } - } - writer->EndArray(); - - writer->String(kPublisherVotesKey); - writer->StartArray(); - const PublisherVotesState publisher_votes_state; - for (const auto& publisher_vote : properties.publisher_votes) { - if (!publisher_votes_state.ToJson(writer, publisher_vote)) { - NOTREACHED(); - continue; - } - } - writer->EndArray(); - - writer->String(kCurrentReconcilesKey); - writer->StartObject(); - const CurrentReconcileState current_reconcile_state; - for (const auto& current_reconcile : properties.current_reconciles) { - writer->Key(current_reconcile.first.c_str()); - if (!current_reconcile_state.ToJson(writer, current_reconcile.second)) { - NOTREACHED(); - continue; - } - } - writer->EndObject(); - writer->String(kWalletKey); const WalletState wallet_state; wallet_state.ToJson(writer, properties.wallet); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc index a92cce4838ca..af2bf77e03d5 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc @@ -69,125 +69,6 @@ class ClientStateTest : public ::testing::Test { return wallet_properties; } - Transactions GetTransactions( - const int count) const { - TransactionProperties transaction_properties; - transaction_properties.viewing_id = "ViewingId"; - transaction_properties.surveyor_id = "SurveyorId"; - transaction_properties.contribution_probi = "ContributionProbi"; - transaction_properties.submission_timestamp = "SubmissionTimestamp"; - transaction_properties.anonize_viewing_id = "AnonizeViewingId"; - transaction_properties.registrar_vk = "RegistrarVk"; - transaction_properties.master_user_token = "MasterUserToken"; - transaction_properties.surveyor_ids = { "SurveyorId" }; - transaction_properties.vote_count = - std::numeric_limits::max(); - transaction_properties.contribution_rates = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 } - }; - - TransactionBallotProperties transaction_ballot_properties; - transaction_ballot_properties.publisher = "Publisher"; - transaction_ballot_properties.count = - std::numeric_limits::max(); - transaction_properties.transaction_ballots.push_back( - transaction_ballot_properties); - - Transactions transactions; - for (int i = 0; i < count; i++) { - transactions.push_back(transaction_properties); - } - - return transactions; - } - - Ballots GetBallots( - const int count) const { - BallotProperties ballot_properties; - ballot_properties.viewing_id = "ViewingId"; - ballot_properties.surveyor_id = "SurveyorId"; - ballot_properties.publisher = "Publisher"; - ballot_properties.count = std::numeric_limits::max(); - ballot_properties.prepare_ballot = "PrepareBallot"; - - Ballots ballots; - for (int i = 0; i < count; i++) { - ballots.push_back(ballot_properties); - } - - return ballots; - } - - PublisherVotes GetPublisherVotes( - const int count) const { - PublisherVotesProperties publisher_votes_properties; - publisher_votes_properties.publisher = "Publisher"; - - PublisherVoteProperties publisher_vote_properties; - publisher_vote_properties.surveyor_id = "SurveyorId"; - publisher_vote_properties.proof = "Proof"; - publisher_votes_properties.batch_votes.push_back(publisher_vote_properties); - - PublisherVotes publisher_votes; - for (int i = 0; i < count; i++) { - publisher_votes.push_back(publisher_votes_properties); - } - - return publisher_votes; - } - - CurrentReconciles GetCurrentReconciles( - const int count) const { - CurrentReconcileProperties current_reconcile_properties; - current_reconcile_properties.viewing_id = "ViewingId"; - current_reconcile_properties.anonize_viewing_id = "AnonizeViewingId"; - current_reconcile_properties.registrar_vk = "RegistrarVk"; - current_reconcile_properties.pre_flight = "PreFlight"; - current_reconcile_properties.master_user_token = "MasterUserToken"; - current_reconcile_properties.surveyor_id = "SurveyorId"; - - current_reconcile_properties.timestamp = - std::numeric_limits::max(); - current_reconcile_properties.rates = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 } - }; - current_reconcile_properties.amount = "Amount"; - current_reconcile_properties.currency = "Currency"; - current_reconcile_properties.fee = std::numeric_limits::max(); - - ReconcileDirectionProperties reconcile_direction_properties; - reconcile_direction_properties.publisher_key = "PublisherKey"; - reconcile_direction_properties.amount_percent = - std::numeric_limits::max(); - current_reconcile_properties.directions.push_back( - reconcile_direction_properties); - - current_reconcile_properties.type = RewardsType::ONE_TIME_TIP; - current_reconcile_properties.retry_step = ContributionRetry::STEP_RECONCILE; - current_reconcile_properties.retry_level = - std::numeric_limits::max(); - current_reconcile_properties.destination = "Destination"; - current_reconcile_properties.proof = "Proof"; - - CurrentReconciles current_reconciles; - for (int i = 0; i < count; i++) { - const std::string key = std::to_string(i); - current_reconciles.insert({key, current_reconcile_properties}); - } - - return current_reconciles; - } - std::map GetInlineTips( const int count) const { std::map inline_tips; @@ -212,17 +93,9 @@ TEST_F(ClientStateTest, ToJsonSerializationWithMinValues) { client_properties.persona_id = "PersonaId"; client_properties.user_id = "UserId"; client_properties.registrar_vk = "RegistrarVk"; - client_properties.master_user_token = "MasterUserToken"; client_properties.pre_flight = "PreFlight"; - client_properties.fee_currency = "FeeCurrency"; - client_properties.settings = "Settings"; client_properties.fee_amount = std::numeric_limits::min(); client_properties.user_changed_fee = true; - client_properties.days = std::numeric_limits::min(); - client_properties.transactions = GetTransactions(1); - client_properties.ballots = GetBallots(1); - client_properties.publisher_votes = GetPublisherVotes(1); - client_properties.current_reconciles = GetCurrentReconciles(1); client_properties.auto_contribute = true; client_properties.rewards_enabled = true; client_properties.inline_tips = GetInlineTips(1); @@ -249,17 +122,9 @@ TEST_F(ClientStateTest, FromJsonDeserializationWithMinValues) { client_properties.persona_id = "PersonaId"; client_properties.user_id = "UserId"; client_properties.registrar_vk = "RegistrarVk"; - client_properties.master_user_token = "MasterUserToken"; client_properties.pre_flight = "PreFlight"; - client_properties.fee_currency = "FeeCurrency"; - client_properties.settings = "Settings"; client_properties.fee_amount = std::numeric_limits::min(); client_properties.user_changed_fee = true; - client_properties.days = std::numeric_limits::min(); - client_properties.transactions = GetTransactions(1); - client_properties.ballots = GetBallots(1); - client_properties.publisher_votes = GetPublisherVotes(1); - client_properties.current_reconciles = GetCurrentReconciles(1); client_properties.auto_contribute = true; client_properties.rewards_enabled = true; client_properties.inline_tips = GetInlineTips(1); @@ -287,17 +152,9 @@ TEST_F(ClientStateTest, ToJsonSerializationWithMaxValues) { client_properties.persona_id = "PersonaId"; client_properties.user_id = "UserId"; client_properties.registrar_vk = "RegistrarVk"; - client_properties.master_user_token = "MasterUserToken"; client_properties.pre_flight = "PreFlight"; - client_properties.fee_currency = "FeeCurrency"; - client_properties.settings = "Settings"; client_properties.fee_amount = std::numeric_limits::max(); client_properties.user_changed_fee = true; - client_properties.days = std::numeric_limits::max(); - client_properties.transactions = GetTransactions(3); - client_properties.ballots = GetBallots(7); - client_properties.publisher_votes = GetPublisherVotes(1); - client_properties.current_reconciles = GetCurrentReconciles(5); client_properties.auto_contribute = true; client_properties.rewards_enabled = true; client_properties.inline_tips = GetInlineTips(9); @@ -324,17 +181,9 @@ TEST_F(ClientStateTest, FromJsonDeserializationWithMaxValues) { client_properties.persona_id = "PersonaId"; client_properties.user_id = "UserId"; client_properties.registrar_vk = "RegistrarVk"; - client_properties.master_user_token = "MasterUserToken"; client_properties.pre_flight = "PreFlight"; - client_properties.fee_currency = "FeeCurrency"; - client_properties.settings = "Settings"; client_properties.fee_amount = std::numeric_limits::max(); client_properties.user_changed_fee = true; - client_properties.days = std::numeric_limits::max(); - client_properties.transactions = GetTransactions(3); - client_properties.ballots = GetBallots(7); - client_properties.publisher_votes = GetPublisherVotes(1); - client_properties.current_reconciles = GetCurrentReconciles(5); client_properties.auto_contribute = true; client_properties.rewards_enabled = true; client_properties.inline_tips = GetInlineTips(9); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.cc deleted file mode 100644 index e477fc96b499..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.cc +++ /dev/null @@ -1,382 +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 - -#include "bat/ledger/internal/state/current_reconcile_state.h" -#include "bat/ledger/internal/state/reconcile_direction_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kAmountKey[] = "amount"; -const char kAnonizeViewingIdKey[] = "anonizeViewingId"; -const char kCategoryKey[] = "category"; -const char kCurrencyKey[] = "currency"; -const char kDestinationKey[] = "destination"; -const char kDirectionsKey[] = "directions"; -const char kFeeKey[] = "fee"; -const char kIdKey[] = "id"; -const char kListKey[] = "list"; -const char kMasterUserTokenKey[] = "masterUserToken"; -const char kPreFlightKey[] = "preFlight"; -const char kProofKey[] = "proof"; -const char kRatesKey[] = "rates"; -const char kRegistrarVkKey[] = "registrarVK"; -const char kRetryLevelKey[] = "retry_level"; -const char kRetryStepKey[] = "retry_step"; -const char kSurveyorIdKey[] = "surveyorId"; -const char kSurveyorInfoKey[] = "surveyorInfo"; -const char kTimestampKey[] = "timestamp"; -const char kTypeKey[] = "type"; -const char kViewingIdKey[] = "viewingId"; -const char kWeightKey[] = "weight"; - -} // namespace - -CurrentReconcileState::CurrentReconcileState() = default; - -CurrentReconcileState::~CurrentReconcileState() = default; - -bool CurrentReconcileState::FromJson( - const std::string& json, - CurrentReconcileProperties* 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 CurrentReconcileState::FromDict( - const base::DictionaryValue* dictionary, - CurrentReconcileProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - CurrentReconcileProperties current_reconcile_properties; - - // Viewing Id - const auto* viewing_id = dictionary->FindStringKey(kViewingIdKey); - if (!viewing_id) { - NOTREACHED(); - return false; - } - current_reconcile_properties.viewing_id = *viewing_id; - - // Anonize Viewing Id - const auto* anonize_viewing_id = - dictionary->FindStringKey(kAnonizeViewingIdKey); - if (anonize_viewing_id) { - current_reconcile_properties.anonize_viewing_id = *anonize_viewing_id; - } - - // Registrar Vk - const auto* registrar_vk = dictionary->FindStringKey(kRegistrarVkKey); - if (registrar_vk) { - current_reconcile_properties.registrar_vk = *registrar_vk; - } - - // Pre Flight - const auto* pre_flight = dictionary->FindStringKey(kPreFlightKey); - if (pre_flight) { - current_reconcile_properties.pre_flight = *pre_flight; - } - - // Master User Token - const auto* master_user_token = - dictionary->FindStringKey(kMasterUserTokenKey); - if (master_user_token) { - current_reconcile_properties.master_user_token = *master_user_token; - } - - // Timestamp (There is no support for uint64_t. Writing JSON with such types - // violates the spec. As we need a uint64_t, we need to use an unsigned int - // and cast to a uint64_t) - const auto timestamp = dictionary->FindDoubleKey(kTimestampKey); - if (timestamp) { - current_reconcile_properties.timestamp = static_cast(*timestamp); - } - - // Amount - const auto* amount = dictionary->FindStringKey(kAmountKey); - if (amount) { - current_reconcile_properties.amount = *amount; - } - - // Currency - const auto* currency = dictionary->FindStringKey(kCurrencyKey); - if (currency) { - current_reconcile_properties.currency = *currency; - } - - // Fee - const auto fee = dictionary->FindDoubleKey(kFeeKey); - if (!fee) { - NOTREACHED(); - return false; - } - current_reconcile_properties.fee = *fee; - - // Type - const auto type = dictionary->FindIntKey(kTypeKey); - if (type) { - current_reconcile_properties.type = static_cast(*type); - } else { - const auto category = dictionary->FindIntKey(kCategoryKey); - if (!category) { - NOTREACHED(); - return false; - } - - // Transition from legacy Category to Type - current_reconcile_properties.type = static_cast(*category); - } - - // Surveyor Info - const auto* surveyor_info_dictionary = - dictionary->FindDictKey(kSurveyorInfoKey); - if (surveyor_info_dictionary) { - const auto* surveyor_id = - surveyor_info_dictionary->FindStringKey(kSurveyorIdKey); - if (!surveyor_id) { - NOTREACHED(); - return false; - } - - current_reconcile_properties.surveyor_id = *surveyor_id; - } - - // Rates - const auto* rates = dictionary->FindDictKey(kRatesKey); - if (rates) { - for (const auto& rate : rates->DictItems()) { - const std::string currency_code = rate.first; - - const auto& exchange_rate_value = rate.second; - const double exchange_rate = exchange_rate_value.GetDouble(); - - current_reconcile_properties.rates.insert({currency_code, exchange_rate}); - } - } - - // Reconcile Directions - const auto* reconcile_directions_list = - dictionary->FindListKey(kDirectionsKey); - if (reconcile_directions_list) { - const ReconcileDirectionState reconcile_direction_state; - for (const auto& reconcile_direction_value : - reconcile_directions_list->GetList()) { - if (!reconcile_direction_value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* reconcile_direction_dictionary = nullptr; - reconcile_direction_value.GetAsDictionary( - &reconcile_direction_dictionary); - if (!reconcile_direction_dictionary) { - NOTREACHED(); - continue; - } - - ReconcileDirectionProperties reconcile_direction; - if (!reconcile_direction_state.FromDict(reconcile_direction_dictionary, - &reconcile_direction)) { - continue; - } - - current_reconcile_properties.directions.push_back(reconcile_direction); - } - } - - // Transition legacy list to reconcile directions - const auto* list_list = dictionary->FindListKey(kListKey); - if (list_list) { - for (const auto& list_value : list_list->GetList()) { - if (!list_value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* list_dictionary = nullptr; - list_value.GetAsDictionary(&list_dictionary); - if (!list_dictionary) { - NOTREACHED(); - continue; - } - - ReconcileDirectionProperties reconcile_direction; - - const auto* id = list_dictionary->FindStringKey(kIdKey); - if (!id) { - NOTREACHED(); - continue; - } - reconcile_direction.publisher_key = *id; - - const auto weight = list_dictionary->FindDoubleKey(kWeightKey); - if (!weight) { - NOTREACHED(); - continue; - } - reconcile_direction.amount_percent = *weight; - - current_reconcile_properties.directions.push_back(reconcile_direction); - } - } - - // Retry Step - const auto retry_step = dictionary->FindIntKey(kRetryStepKey); - if (retry_step) { - current_reconcile_properties.retry_step = - static_cast(*retry_step); - } - - // Retry Level - const auto retry_level = dictionary->FindIntKey(kRetryLevelKey); - if (retry_level) { - current_reconcile_properties.retry_level = *retry_level; - } - - // Destination - const auto* destination = dictionary->FindStringKey(kDestinationKey); - if (destination) { - current_reconcile_properties.destination = *destination; - } - - // Proof - const auto* proof = dictionary->FindStringKey(kProofKey); - if (proof) { - current_reconcile_properties.proof = *proof; - } - - *properties = current_reconcile_properties; - - return true; -} - -bool CurrentReconcileState::ToJson( - JsonWriter* writer, - const CurrentReconcileProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kViewingIdKey); - writer->String(properties.viewing_id.c_str()); - - writer->String(kAnonizeViewingIdKey); - writer->String(properties.anonize_viewing_id.c_str()); - - writer->String(kRegistrarVkKey); - writer->String(properties.registrar_vk.c_str()); - - writer->String(kPreFlightKey); - writer->String(properties.pre_flight.c_str()); - - writer->String(kMasterUserTokenKey); - writer->String(properties.master_user_token.c_str()); - - writer->String(kSurveyorInfoKey); - writer->StartObject(); - writer->String(kSurveyorIdKey); - writer->String(properties.surveyor_id.c_str()); - writer->EndObject(); - - writer->String(kTimestampKey); - writer->Uint64(properties.timestamp); - - writer->String(kAmountKey); - writer->String(properties.amount.c_str()); - - writer->String(kCurrencyKey); - writer->String(properties.currency.c_str()); - - writer->String(kFeeKey); - writer->Double(properties.fee); - - writer->String(kTypeKey); - writer->Int(static_cast(properties.type)); - - writer->String(kRatesKey); - writer->StartObject(); - for (const auto &rate : properties.rates) { - writer->String(rate.first.c_str()); - writer->Double(rate.second); - } - writer->EndObject(); - - writer->String(kDirectionsKey); - writer->StartArray(); - const ReconcileDirectionState reconcile_direction_state; - for (const auto& direction : properties.directions) { - reconcile_direction_state.ToJson(writer, direction); - } - writer->EndArray(); - - writer->String(kRetryStepKey); - writer->Int(static_cast(properties.retry_step)); - - writer->String(kRetryLevelKey); - writer->Int(properties.retry_level); - - writer->String(kDestinationKey); - writer->String(properties.destination.c_str()); - - writer->String(kProofKey); - writer->String(properties.proof.c_str()); - - writer->EndObject(); - - return true; -} - -std::string CurrentReconcileState::ToJson( - const CurrentReconcileProperties& 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/state/current_reconcile_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.h deleted file mode 100644 index 6f6bf9bcdbe5..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.h +++ /dev/null @@ -1,45 +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_STATE_CURRENT_RECONCILE_STATE_H_ -#define BRAVELEDGER_STATE_CURRENT_RECONCILE_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/current_reconcile_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class CurrentReconcileState - : public state::Reader, - public state::Writer { - public: - CurrentReconcileState(); - ~CurrentReconcileState(); - - bool FromJson( - const std::string& json, - CurrentReconcileProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - CurrentReconcileProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const CurrentReconcileProperties& properties) const override; - - std::string ToJson( - const CurrentReconcileProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_CURRENT_RECONCILE_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc deleted file mode 100644 index e81ee5cc48e5..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc +++ /dev/null @@ -1,120 +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 - -#include "bat/ledger/internal/state/current_reconcile_state.h" -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=CurrentReconcileStateTest.* - -namespace ledger { - -// TODO(tmancey): Test transition from legacy list to reconcile directions - -TEST(CurrentReconcileStateTest, ToJsonSerialization) { - // Arrange - CurrentReconcileProperties current_reconcile_properties; - current_reconcile_properties.viewing_id = "ViewingId"; - current_reconcile_properties.anonize_viewing_id = "AnonizeViewingId"; - current_reconcile_properties.registrar_vk = "RegistrarVk"; - current_reconcile_properties.pre_flight = "PreFlight"; - current_reconcile_properties.master_user_token = "MasterUserToken"; - current_reconcile_properties.surveyor_id = "SurveyorId"; - - current_reconcile_properties.timestamp = - std::numeric_limits::max(); - current_reconcile_properties.rates = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 } - }; - current_reconcile_properties.amount = "Amount"; - current_reconcile_properties.currency = "Currency"; - current_reconcile_properties.fee = std::numeric_limits::max(); - - ReconcileDirectionProperties reconcile_direction_properties; - reconcile_direction_properties.publisher_key = "PublisherKey"; - reconcile_direction_properties.amount_percent = - std::numeric_limits::max(); - current_reconcile_properties.directions.push_back( - reconcile_direction_properties); - - current_reconcile_properties.type = RewardsType::ONE_TIME_TIP; - current_reconcile_properties.retry_step = ContributionRetry::STEP_RECONCILE; - current_reconcile_properties.retry_level = - std::numeric_limits::max(); - current_reconcile_properties.destination = "Destination"; - current_reconcile_properties.proof = "Proof"; - - // Act - const CurrentReconcileState current_reconcile_state; - const std::string json = - current_reconcile_state.ToJson(current_reconcile_properties); - - // Assert - CurrentReconcileProperties expected_current_reconcile_properties; - current_reconcile_state.FromJson(json, - &expected_current_reconcile_properties); - EXPECT_EQ(expected_current_reconcile_properties, - current_reconcile_properties); -} - -TEST(CurrentReconcileStateTest, FromJsonDeserialization) { - // Arrange - CurrentReconcileProperties current_reconcile_properties; - current_reconcile_properties.viewing_id = "ViewingId"; - current_reconcile_properties.anonize_viewing_id = "AnonizeViewingId"; - current_reconcile_properties.registrar_vk = "RegistrarVk"; - current_reconcile_properties.pre_flight = "PreFlight"; - current_reconcile_properties.master_user_token = "MasterUserToken"; - current_reconcile_properties.surveyor_id = "SurveyorId"; - - current_reconcile_properties.timestamp = - std::numeric_limits::max(); - current_reconcile_properties.rates = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 } - }; - current_reconcile_properties.amount = "Amount"; - current_reconcile_properties.currency = "Currency"; - current_reconcile_properties.fee = std::numeric_limits::max(); - - ReconcileDirectionProperties reconcile_direction_properties; - reconcile_direction_properties.publisher_key = "PublisherKey"; - reconcile_direction_properties.amount_percent = - std::numeric_limits::max(); - current_reconcile_properties.directions.push_back( - reconcile_direction_properties); - - current_reconcile_properties.type = RewardsType::ONE_TIME_TIP; - current_reconcile_properties.retry_step = ContributionRetry::STEP_RECONCILE; - current_reconcile_properties.retry_level = - std::numeric_limits::max(); - current_reconcile_properties.destination = "Destination"; - current_reconcile_properties.proof = "Proof"; - - const std::string json = "{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"}"; // NOLINT - - // Act - CurrentReconcileProperties expected_current_reconcile_properties; - const CurrentReconcileState current_reconcile_state; - current_reconcile_state.FromJson(json, - &expected_current_reconcile_properties); - - // Assert - EXPECT_EQ(expected_current_reconcile_properties, - current_reconcile_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.cc deleted file mode 100644 index e9ce8160a1ea..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.cc +++ /dev/null @@ -1,206 +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/state/publisher_state.h" -#include "bat/ledger/mojom_structs.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kDurationKey[] = "duration"; -const char kIdKey[] = "id"; -const char kPercentKey[] = "percent"; -const char kScoreKey[] = "score"; -const char kStatusKey[] = "status"; -const char kVerifiedKey[] = "verified"; -const char kVisitsKey[] = "visits"; -const char kWeightKey[] = "weight"; - -} // namespace - -PublisherState::PublisherState() = default; - -PublisherState::~PublisherState() = default; - -bool PublisherState::FromJson( - const std::string& json, - PublisherProperties* 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 PublisherState::FromDict( - const base::DictionaryValue* dictionary, - PublisherProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - PublisherProperties publisher_properties; - - // Id - const auto* id = dictionary->FindStringKey(kIdKey); - if (!id) { - NOTREACHED(); - return false; - } - publisher_properties.id = *id; - - // Duration (There is no support for uint64_t. Writing JSON with such types - // violates the spec. As we need a uint64_t, we need to use an unsigned int - // and cast to a uint64_t) - const auto duration = dictionary->FindDoubleKey(kDurationKey); - if (!duration) { - NOTREACHED(); - return false; - } - publisher_properties.duration = static_cast(*duration); - - // Score - auto score = dictionary->FindDoubleKey(kScoreKey); - if (!score) { - NOTREACHED(); - return false; - } - publisher_properties.score = *score; - - // Visits (There is no support for unsigned int. Writing JSON with such types - // violates the spec. As we need an unsigned int, we need to a double and cast - // to an unsigned int) - const auto visits = dictionary->FindDoubleKey(kVisitsKey); - if (!visits) { - NOTREACHED(); - return false; - } - publisher_properties.visits = static_cast(*visits); - - // Percent (There is no support for unsigned int. Writing JSON with such types - // violates the spec. As we need an unsigned int, we need to a double and cast - // to an unsigned int) - const auto percent = dictionary->FindDoubleKey(kPercentKey); - if (!percent) { - NOTREACHED(); - return false; - } - publisher_properties.percent = static_cast(*percent); - - // Weight - const auto weight = dictionary->FindDoubleKey(kWeightKey); - if (!weight) { - NOTREACHED(); - return false; - } - publisher_properties.weight = *weight; - - // Verified - const auto verified = dictionary->FindBoolKey(kVerifiedKey); - if (!verified) { - // Status (There is no support for unsigned int. Writing JSON with such - // types violates the spec. As we need an unsigned int, we need to a double - // and cast to an unsigned int) - const auto status = dictionary->FindDoubleKey(kStatusKey); - if (!status) { - NOTREACHED(); - return false; - } - - publisher_properties.status = static_cast(*status); - } else { - // Transition legacy verified flag to PublisherStatus enum - if (*verified) { - publisher_properties.status = static_cast( - PublisherStatus::VERIFIED); - } else { - publisher_properties.status = static_cast( - PublisherStatus::NOT_VERIFIED); - } - } - - *properties = publisher_properties; - - return true; -} - -bool PublisherState::ToJson( - JsonWriter* writer, - const PublisherProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kIdKey); - writer->String(properties.id.c_str()); - - writer->String(kDurationKey); - writer->Uint64(properties.duration); - - writer->String(kScoreKey); - writer->Double(properties.score); - - writer->String(kVisitsKey); - writer->Uint(properties.visits); - - writer->String(kPercentKey); - writer->Uint(properties.percent); - - writer->String(kWeightKey); - writer->Double(properties.weight); - - writer->String(kStatusKey); - writer->Uint(properties.status); - - writer->EndObject(); - - return true; -} - -std::string PublisherState::ToJson( - const PublisherProperties& 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/state/publisher_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.h deleted file mode 100644 index d74923821eee..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.h +++ /dev/null @@ -1,45 +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_STATE_PUBLISHER_STATE_H_ -#define BRAVELEDGER_STATE_PUBLISHER_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/publisher_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class PublisherState - : public state::Reader, - public state::Writer { - public: - PublisherState(); - ~PublisherState(); - - bool FromJson( - const std::string& json, - PublisherProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - PublisherProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const PublisherProperties& properties) const override; - - std::string ToJson( - const PublisherProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_PUBLISHER_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc deleted file mode 100644 index 7ac6208f2d9a..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc +++ /dev/null @@ -1,58 +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 - -#include "bat/ledger/internal/state/publisher_state.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=PublisherStateTest.* - -namespace ledger { - -TEST(PublisherStateTest, ToJsonSerialization) { - // Arrange - PublisherProperties publisher_properties; - publisher_properties.id = "Id"; - publisher_properties.duration = std::numeric_limits::max(); - publisher_properties.score = std::numeric_limits::max(); - publisher_properties.visits = std::numeric_limits::max(); - publisher_properties.percent = std::numeric_limits::max(); - publisher_properties.weight = std::numeric_limits::max(); - publisher_properties.status = std::numeric_limits::max(); - - // Act - const PublisherState publisher_state; - const std::string json = publisher_state.ToJson(publisher_properties); - - // Assert - PublisherProperties expected_publisher_properties; - publisher_state.FromJson(json, &expected_publisher_properties); - EXPECT_EQ(expected_publisher_properties, publisher_properties); -} - -TEST(PublisherStateTest, FromJsonDeserialization) { - // Arrange - PublisherProperties publisher_properties; - publisher_properties.id = "Id"; - publisher_properties.duration = std::numeric_limits::max(); - publisher_properties.score = std::numeric_limits::max(); - publisher_properties.visits = std::numeric_limits::max(); - publisher_properties.percent = std::numeric_limits::max(); - publisher_properties.weight = std::numeric_limits::max(); - publisher_properties.status = std::numeric_limits::max(); - - const std::string json = "{\"id\":\"Id\",\"duration\":4294967295,\"score\":1.7976931348623157e308,\"visits\":4294967295,\"percent\":4294967295,\"weight\":1.7976931348623157e308,\"status\":4294967295}"; // NOLINT - - // Act - PublisherProperties expected_publisher_properties; - const PublisherState publisher_state; - publisher_state.FromJson(json, &expected_publisher_properties); - - // Assert - EXPECT_EQ(expected_publisher_properties, publisher_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.cc deleted file mode 100644 index 5ea018923197..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.cc +++ /dev/null @@ -1,139 +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/state/publisher_vote_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kProofKey[] = "proof"; -const char kSurveyorIdKey[] = "surveyorId"; - -} // namespace - -PublisherVoteState::PublisherVoteState() = default; - -PublisherVoteState::~PublisherVoteState() = default; - -bool PublisherVoteState::FromJson( - const std::string& json, - PublisherVoteProperties* 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 PublisherVoteState::FromDict( - const base::DictionaryValue* dictionary, - PublisherVoteProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - PublisherVoteProperties vote_properties; - - // Surveyor Id - const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); - if (!surveyor_id) { - NOTREACHED(); - return false; - } - vote_properties.surveyor_id = *surveyor_id; - - // Proof - const auto* proof = dictionary->FindStringKey(kProofKey); - if (!proof) { - NOTREACHED(); - return false; - } - vote_properties.proof = *proof; - - *properties = vote_properties; - - return true; -} - -bool PublisherVoteState::ToJson( - JsonWriter* writer, - const PublisherVoteProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String("surveyorId"); - writer->String(properties.surveyor_id.c_str()); - - writer->String("proof"); - writer->String(properties.proof.c_str()); - - writer->EndObject(); - - return true; -} - -std::string PublisherVoteState::ToJson( - const PublisherVoteProperties& properties) const { - rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); - - if (!ToJson(&writer, properties)) { - NOTREACHED(); - return ""; - } - - return buffer.GetString(); -} - -std::string PublisherVoteState::ToJson( - const BatchVotes& batch_votes) const { - rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); - - writer.StartArray(); - for (const auto& batch_vote : batch_votes) { - if (!ToJson(&writer, batch_vote)) { - NOTREACHED(); - continue; - } - } - writer.EndArray(); - - return buffer.GetString(); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.h deleted file mode 100644 index 0d9e11e3a91e..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_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_STATE_PUBLISHER_VOTE_STATE_H_ -#define BRAVELEDGER_STATE_PUBLISHER_VOTE_STATE_H_ - -#include -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/publisher_vote_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class PublisherVoteState - : public state::Reader, - public state::Writer { - public: - PublisherVoteState(); - ~PublisherVoteState(); - - bool FromJson( - const std::string& json, - PublisherVoteProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - PublisherVoteProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const PublisherVoteProperties& properties) const override; - - std::string ToJson( - const PublisherVoteProperties& properties) const override; - - std::string ToJson( - const BatchVotes& batch_votes) const; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_PUBLISHER_VOTE_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc deleted file mode 100644 index 03c1e1d32a8b..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc +++ /dev/null @@ -1,46 +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/state/publisher_vote_state.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=VoteStateTest.* - -namespace ledger { - -TEST(VoteStateTest, ToJsonSerialization) { - // Arrange - PublisherVoteProperties vote_properties; - vote_properties.surveyor_id = "SurveyorId"; - vote_properties.proof = "Proof"; - - // Act - const PublisherVoteState vote_state; - const std::string json = vote_state.ToJson(vote_properties); - - // Assert - PublisherVoteProperties expected_vote_properties; - vote_state.FromJson(json, &expected_vote_properties); - EXPECT_EQ(expected_vote_properties, vote_properties); -} - -TEST(VoteStateTest, FromJsonDeserialization) { - // Arrange - PublisherVoteProperties vote_properties; - vote_properties.surveyor_id = "SurveyorId"; - vote_properties.proof = "Proof"; - - const std::string json = "{\"surveyorId\":\"SurveyorId\",\"proof\":\"Proof\"}"; // NOLINT - - // Act - PublisherVoteProperties expected_vote_properties; - const PublisherVoteState vote_state; - vote_state.FromJson(json, &expected_vote_properties); - - // Assert - EXPECT_EQ(expected_vote_properties, vote_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.cc deleted file mode 100644 index e2635ff46ff6..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.cc +++ /dev/null @@ -1,151 +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/state/publisher_votes_state.h" -#include "bat/ledger/internal/state/publisher_vote_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kPublisherKey[] = "publisher"; -const char kBatchVotesKey[] = "batchVotesInfo"; - -} // namespace - -PublisherVotesState::PublisherVotesState() = default; - -PublisherVotesState::~PublisherVotesState() = default; - -bool PublisherVotesState::FromJson( - const std::string& json, - PublisherVotesProperties* 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 PublisherVotesState::FromDict( - const base::DictionaryValue* dictionary, - PublisherVotesProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - PublisherVotesProperties publisher_votes_properties; - - // Publisher - const auto* publisher = dictionary->FindStringKey(kPublisherKey); - if (!publisher) { - NOTREACHED(); - return false; - } - publisher_votes_properties.publisher = *publisher; - - // Batch Votes - const auto* batch_votes_list = dictionary->FindListKey(kBatchVotesKey); - if (!batch_votes_list) { - NOTREACHED(); - return false; - } - - const PublisherVoteState publisher_vote_state; - for (const auto& batch_votes_value : batch_votes_list->GetList()) { - if (!batch_votes_value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* batch_votes_dictionary = nullptr; - batch_votes_value.GetAsDictionary(&batch_votes_dictionary); - if (!batch_votes_dictionary) { - NOTREACHED(); - continue; - } - - PublisherVoteProperties publisher_vote_properties; - if (!publisher_vote_state.FromDict(batch_votes_dictionary, - &publisher_vote_properties)) { - continue; - } - - publisher_votes_properties.batch_votes.push_back( - publisher_vote_properties); - } - - *properties = publisher_votes_properties; - - return true; -} - -bool PublisherVotesState::ToJson( - JsonWriter* writer, - const PublisherVotesProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kPublisherKey); - writer->String(properties.publisher.c_str()); - - writer->String(kBatchVotesKey); - writer->StartArray(); - const PublisherVoteState publisher_vote_state; - for (const auto& batch_vote : properties.batch_votes) { - publisher_vote_state.ToJson(writer, batch_vote); - } - writer->EndArray(); - - writer->EndObject(); - - return true; -} - -std::string PublisherVotesState::ToJson( - const PublisherVotesProperties& 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/state/publisher_votes_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.h deleted file mode 100644 index 9a7750a47e14..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.h +++ /dev/null @@ -1,45 +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_STATE_PUBLISHER_VOTES_STATE_H_ -#define BRAVELEDGER_STATE_PUBLISHER_VOTES_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/publisher_votes_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class PublisherVotesState - : public state::Reader, - public state::Writer { - public: - PublisherVotesState(); - ~PublisherVotesState(); - - bool FromJson( - const std::string& json, - PublisherVotesProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - PublisherVotesProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const PublisherVotesProperties& properties) const override; - - std::string ToJson( - const PublisherVotesProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_PUBLISHER_VOTES_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc deleted file mode 100644 index ae4eb51968ba..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc +++ /dev/null @@ -1,56 +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/state/publisher_votes_state.h" -#include "bat/ledger/internal/properties/transaction_ballot_properties.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=PublisherVotesStateTest.* - -namespace ledger { - -TEST(PublisherVotesStateTest, ToJsonSerialization) { - // Arrange - PublisherVotesProperties publisher_votes_properties; - publisher_votes_properties.publisher = "Publisher"; - - PublisherVoteProperties publisher_vote_properties; - publisher_vote_properties.surveyor_id = "SurveyorId"; - publisher_vote_properties.proof = "Proof"; - publisher_votes_properties.batch_votes.push_back(publisher_vote_properties); - - // Act - const PublisherVotesState publisher_votes_state; - const std::string json = - publisher_votes_state.ToJson(publisher_votes_properties); - - // Assert - PublisherVotesProperties expected_publisher_votes_properties; - publisher_votes_state.FromJson(json, &expected_publisher_votes_properties); - EXPECT_EQ(expected_publisher_votes_properties, publisher_votes_properties); -} - -TEST(PublisherVotesStateTest, FromJsonDeserialization) { - // Arrange - PublisherVotesProperties publisher_votes_properties; - publisher_votes_properties.publisher = "Publisher"; - - PublisherVoteProperties publisher_vote_properties; - publisher_vote_properties.surveyor_id = "SurveyorId"; - publisher_vote_properties.proof = "Proof"; - publisher_votes_properties.batch_votes.push_back(publisher_vote_properties); - - const std::string json = "{\"publisher\":\"Publisher\",\"batchVotesInfo\":[{\"surveyorId\":\"SurveyorId\",\"proof\":\"Proof\"}]}"; // NOLINT - - // Act - PublisherVotesProperties expected_publisher_votes_properties; - const PublisherVotesState publisher_votes_state; - publisher_votes_state.FromJson(json, &expected_publisher_votes_properties); - - // Assert - EXPECT_EQ(expected_publisher_votes_properties, publisher_votes_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.cc deleted file mode 100644 index ae2d5f348eb2..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.cc +++ /dev/null @@ -1,127 +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/state/reconcile_direction_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kAmountKey[] = "amount"; -const char kAmountPercentKey[] = "amount_percent"; -const char kPublisherKeyKey[] = "publisher_key"; - -} // namespace - -ReconcileDirectionState::ReconcileDirectionState() = default; - -ReconcileDirectionState::~ReconcileDirectionState() = default; - -bool ReconcileDirectionState::FromJson( - const std::string& json, - ReconcileDirectionProperties* 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 ReconcileDirectionState::FromDict( - const base::DictionaryValue* dictionary, - ReconcileDirectionProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - ReconcileDirectionProperties reconcile_direction_properties; - - // Publisher Key - const auto* publisher_key = dictionary->FindStringKey(kPublisherKeyKey); - if (!publisher_key) { - NOTREACHED(); - return false; - } - reconcile_direction_properties.publisher_key = *publisher_key; - - // Amount Percent - const auto amount_percent = dictionary->FindDoubleKey(kAmountPercentKey); - if (amount_percent) { - reconcile_direction_properties.amount_percent = *amount_percent; - } else { - const auto amount_percent = dictionary->FindDoubleKey(kAmountKey); - if (!amount_percent) { - NOTREACHED(); - return false; - } - } - - *properties = reconcile_direction_properties; - - return true; -} - -bool ReconcileDirectionState::ToJson( - JsonWriter* writer, - const ReconcileDirectionProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kAmountPercentKey); - writer->Double(properties.amount_percent); - - writer->String(kPublisherKeyKey); - writer->String(properties.publisher_key.c_str()); - - writer->EndObject(); - - return true; -} - -std::string ReconcileDirectionState::ToJson( - const ReconcileDirectionProperties& 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/state/reconcile_direction_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.h deleted file mode 100644 index 54ee4ed5e3bc..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.h +++ /dev/null @@ -1,45 +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_STATE_RECONCILE_DIRECTION_STATE_H_ -#define BRAVELEDGER_STATE_RECONCILE_DIRECTION_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/reconcile_direction_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class ReconcileDirectionState - : public state::Reader, - public state::Writer { - public: - ReconcileDirectionState(); - ~ReconcileDirectionState(); - - bool FromJson( - const std::string& json, - ReconcileDirectionProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - ReconcileDirectionProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const ReconcileDirectionProperties& properties) const override; - - std::string ToJson( - const ReconcileDirectionProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_RECONCILE_DIRECTION_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc deleted file mode 100644 index 0f24f67fb123..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc +++ /dev/null @@ -1,55 +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 - -#include "bat/ledger/internal/state/reconcile_direction_state.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=ReconcileDirectionStateTest.* - -namespace ledger { - -TEST(ReconcileDirectionStateTest, ToJsonSerialization) { - // Arrange - ReconcileDirectionProperties reconcile_direction_properties; - reconcile_direction_properties.publisher_key = "ViewingId"; - reconcile_direction_properties.amount_percent = - std::numeric_limits::max(); - - // Act - const ReconcileDirectionState reconcile_direction_state; - const std::string json = - reconcile_direction_state.ToJson(reconcile_direction_properties); - - // Assert - ReconcileDirectionProperties expected_reconcile_direction_properties; - reconcile_direction_state.FromJson(json, - &expected_reconcile_direction_properties); - EXPECT_EQ(expected_reconcile_direction_properties, - reconcile_direction_properties); -} - -TEST(ReconcileDirectionStateTest, FromJsonDeserialization) { - // Arrange - ReconcileDirectionProperties reconcile_direction_properties; - reconcile_direction_properties.publisher_key = "ViewingId"; - reconcile_direction_properties.amount_percent = - std::numeric_limits::max(); - - const std::string json = "{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"ViewingId\"}"; // NOLINT - - // Act - ReconcileDirectionProperties expected_reconcile_direction_properties; - const ReconcileDirectionState reconcile_direction_state; - reconcile_direction_state.FromJson(json, - &expected_reconcile_direction_properties); - - // Assert - EXPECT_EQ(expected_reconcile_direction_properties, - reconcile_direction_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.cc deleted file mode 100644 index 7fd220940546..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.cc +++ /dev/null @@ -1,116 +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/state/reconcile_request_state.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kAmountKey[] = "amount"; -const char kBodyKey[] = "body"; -const char kCurrencyKey[] = "currency"; -const char kDenominationKey[] = "denomination"; -const char kDestinationKey[] = "destination"; -const char kDigestKey[] = "digest"; -const char kHeadersKey[] = "headers"; -const char kOctetsKey[] = "octets"; -const char kRequestTypeKey[] = "requestType"; -const char kSignatureKey[] = "signature"; -const char kSignedTxKey[] = "signedTx"; -const char kSurveyorIdKey[] = "surveyorId"; -const char kViewingIdKey[] = "viewingId"; - -} // namespace - -ReconcileRequestState::ReconcileRequestState() = default; - -ReconcileRequestState::~ReconcileRequestState() = default; - -bool ReconcileRequestState::ToJson( - JsonWriter* writer, - const ReconcileRequestProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - if (!properties.type.empty()) { - writer->String(kRequestTypeKey); - writer->String(properties.type.c_str()); - } - - writer->String(kSignedTxKey); - writer->StartObject(); - - writer->String(kHeadersKey); - writer->StartObject(); - - writer->String(kDigestKey); - writer->String(properties.signed_tx_headers_digest.c_str()); - - writer->String(kSignatureKey); - writer->String(properties.signed_tx_headers_signature.c_str()); - - writer->EndObject(); - - writer->String(kBodyKey); - writer->StartObject(); - - writer->String(kDenominationKey); - writer->StartObject(); - - writer->String(kAmountKey); - writer->String(properties.signed_tx_body.amount.c_str()); - - writer->String(kCurrencyKey); - writer->String(properties.signed_tx_body.currency.c_str()); - - writer->EndObject(); - - writer->String(kDestinationKey); - writer->String(properties.signed_tx_body.destination.c_str()); - - writer->EndObject(); - - writer->String(kOctetsKey); - writer->String(properties.signed_tx_octets.c_str()); - - writer->EndObject(); - - if (!properties.surveyor_id.empty()) { - writer->String(kSurveyorIdKey); - writer->String(properties.surveyor_id.c_str()); - } - - if (!properties.viewing_id.empty()) { - writer->String(kViewingIdKey); - writer->String(properties.viewing_id.c_str()); - } - - writer->EndObject(); - - return true; -} - -std::string ReconcileRequestState::ToJson( - const ReconcileRequestProperties& 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/state/reconcile_request_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.h deleted file mode 100644 index 8f8067baad12..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.h +++ /dev/null @@ -1,35 +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_STATE_RECONCILE_REQUEST_STATE_H_ -#define BRAVELEDGER_STATE_RECONCILE_REQUEST_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/reconcile_request_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class ReconcileRequestState - : public state::Writer { - public: - ReconcileRequestState(); - ~ReconcileRequestState(); - - bool ToJson( - JsonWriter* writer, - const ReconcileRequestProperties& properties) const override; - - std::string ToJson( - const ReconcileRequestProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_RECONCILE_REQUEST_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc deleted file mode 100644 index f66bebabd27d..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc +++ /dev/null @@ -1,43 +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/state/reconcile_request_state.h" -#include "bat/ledger/internal/properties/unsigned_tx_properties.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=ReconcileRequestStateTest.* - -namespace ledger { - -TEST(ReconcileRequestStateTest, ToJsonSerialization) { - // Arrange - ReconcileRequestProperties reconcile_request_properties; - reconcile_request_properties.type = "RequestType"; - reconcile_request_properties.signed_tx_headers_digest = - "RequestSignedTxHeadersDigest"; - reconcile_request_properties.signed_tx_headers_signature = - "RequestSignedTxHeadersSignature"; - - UnsignedTxProperties unsigned_tx_properties; - unsigned_tx_properties.amount = "Amount"; - unsigned_tx_properties.currency = "Currency"; - unsigned_tx_properties.destination = "Destination"; - reconcile_request_properties.signed_tx_body = unsigned_tx_properties; - - reconcile_request_properties.signed_tx_octets = "RequestSignedTxOctets"; - reconcile_request_properties.viewing_id = "RequestViewingId"; - reconcile_request_properties.surveyor_id = "RequestSurveyorId"; - - // Act - const ReconcileRequestState reconcile_request_state; - const std::string json = - reconcile_request_state.ToJson(reconcile_request_properties); - - // Assert - const std::string expected_json = "{\"requestType\":\"RequestType\",\"signedTx\":{\"headers\":{\"digest\":\"RequestSignedTxHeadersDigest\",\"signature\":\"RequestSignedTxHeadersSignature\"},\"body\":{\"denomination\":{\"amount\":\"Amount\",\"currency\":\"Currency\"},\"destination\":\"Destination\"},\"octets\":\"RequestSignedTxOctets\"},\"surveyorId\":\"RequestSurveyorId\",\"viewingId\":\"RequestViewingId\"}"; // NOLINT - EXPECT_EQ(expected_json, json); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.cc deleted file mode 100644 index e02eb96469a5..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.cc +++ /dev/null @@ -1,156 +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/state/surveyor_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kRegistrarVkKey[] = "registrarVK"; -const char kSignatureKey[] = "signature"; -const char kSurveyorIdKey[] = "surveyorId"; -const char kSurveySkKey[] = "surveySK"; -const char kSurveyVkKey[] = "surveyVK"; - -} // namespace - -SurveyorState::SurveyorState() = default; - -SurveyorState::~SurveyorState() = default; - -bool SurveyorState::FromJson( - const std::string& json, - SurveyorProperties* 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 SurveyorState::FromDict( - const base::DictionaryValue* dictionary, - SurveyorProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - SurveyorProperties surveyor_properties; - - // Signature - const auto* signature = dictionary->FindStringKey(kSignatureKey); - if (!signature) { - NOTREACHED(); - return false; - } - surveyor_properties.signature = *signature; - - // Surveyor Id - const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); - if (!surveyor_id) { - NOTREACHED(); - return false; - } - surveyor_properties.surveyor_id = *surveyor_id; - - // Survey VK - const auto* survey_vk = dictionary->FindStringKey(kSurveyVkKey); - if (!survey_vk) { - NOTREACHED(); - return false; - } - surveyor_properties.survey_vk = *survey_vk; - - // Registrar VK - const auto* registrar_vk = dictionary->FindStringKey(kRegistrarVkKey); - if (!registrar_vk) { - NOTREACHED(); - return false; - } - surveyor_properties.registrar_vk = *registrar_vk; - - // Survey SK - const auto* survey_sk = dictionary->FindStringKey(kSurveySkKey); - if (survey_sk) { - surveyor_properties.survey_sk = *survey_sk; - } - - *properties = surveyor_properties; - - return true; -} - -bool SurveyorState::ToJson( - JsonWriter* writer, - const SurveyorProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kRegistrarVkKey); - writer->String(properties.registrar_vk.c_str()); - - writer->String(kSignatureKey); - writer->String(properties.signature.c_str()); - - writer->String(kSurveyorIdKey); - writer->String(properties.surveyor_id.c_str()); - - writer->String(kSurveySkKey); - writer->String(properties.survey_sk.c_str()); - - writer->String(kSurveyVkKey); - writer->String(properties.survey_vk.c_str()); - - writer->EndObject(); - - return true; -} - -std::string SurveyorState::ToJson( - const SurveyorProperties& 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/state/surveyor_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.h deleted file mode 100644 index 63e84692669b..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.h +++ /dev/null @@ -1,45 +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_STATE_SURVEYOR_STATE_H_ -#define BRAVELEDGER_STATE_SURVEYOR_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/surveyor_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class SurveyorState - : public state::Reader, - public state::Writer { - public: - SurveyorState(); - ~SurveyorState(); - - bool FromJson( - const std::string& json, - SurveyorProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - SurveyorProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const SurveyorProperties& properties) const override; - - std::string ToJson( - const SurveyorProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_SURVEYOR_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc deleted file mode 100644 index 3b2e97315f1f..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc +++ /dev/null @@ -1,52 +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/state/surveyor_state.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=SurveyorStateTest.* - -namespace ledger { - -TEST(SurveyorStateTest, ToJsonSerialization) { - // Arrange - SurveyorProperties surveyor_properties; - surveyor_properties.signature = "Signature"; - surveyor_properties.surveyor_id = "SurveyorId"; - surveyor_properties.survey_vk = "SurveyVk"; - surveyor_properties.registrar_vk = "RegistrarVk"; - surveyor_properties.survey_sk = "SurveySk"; - - // Act - const SurveyorState surveyor_state; - const std::string json = surveyor_state.ToJson(surveyor_properties); - - // Assert - SurveyorProperties expected_surveyor_properties; - surveyor_state.FromJson(json, &expected_surveyor_properties); - EXPECT_EQ(expected_surveyor_properties, surveyor_properties); -} - -TEST(SurveyorStateTest, FromJsonDeserialization) { - // Arrange - SurveyorProperties surveyor_properties; - surveyor_properties.signature = "Signature"; - surveyor_properties.surveyor_id = "SurveyorId"; - surveyor_properties.survey_vk = "SurveyVk"; - surveyor_properties.registrar_vk = "RegistrarVk"; - surveyor_properties.survey_sk = "SurveySk"; - - const std::string json = "{\"registrarVK\":\"RegistrarVk\",\"signature\":\"Signature\",\"surveyorId\":\"SurveyorId\",\"surveySK\":\"SurveySk\",\"surveyVK\":\"SurveyVk\"}"; // NOLINT - - // Act - SurveyorProperties expected_surveyor_properties; - const SurveyorState surveyor_state; - surveyor_state.FromJson(json, &expected_surveyor_properties); - - // Assert - EXPECT_EQ(expected_surveyor_properties, surveyor_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.cc deleted file mode 100644 index 35d7536cd645..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.cc +++ /dev/null @@ -1,124 +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/state/transaction_ballot_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kOffsetKey[] = "offset"; -const char kPublisherKey[] = "publisher"; - -} // namespace - -TransactionBallotState::TransactionBallotState() = default; - -TransactionBallotState::~TransactionBallotState() = default; - -bool TransactionBallotState::FromJson( - const std::string& json, - TransactionBallotProperties* 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 TransactionBallotState::FromDict( - const base::DictionaryValue* dictionary, - TransactionBallotProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - TransactionBallotProperties transaction_ballot_properties; - - // Publisher - const auto* publisher = dictionary->FindStringKey(kPublisherKey); - if (!publisher) { - NOTREACHED(); - return false; - } - transaction_ballot_properties.publisher = *publisher; - - // Offset (There is no support for unsigned int. Writing JSON with such types - // violates the spec. As we need an unsigned int, we need to a double and cast - // to an unsigned int) - const auto count = dictionary->FindDoubleKey(kOffsetKey); - if (!count) { - NOTREACHED(); - return false; - } - transaction_ballot_properties.count = static_cast(*count); - - *properties = transaction_ballot_properties; - - return true; -} - -bool TransactionBallotState::ToJson( - JsonWriter* writer, - const TransactionBallotProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kPublisherKey); - writer->String(properties.publisher.c_str()); - - writer->String(kOffsetKey); - writer->Uint(properties.count); - - writer->EndObject(); - - return true; -} - -std::string TransactionBallotState::ToJson( - const TransactionBallotProperties& 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/state/transaction_ballot_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.h deleted file mode 100644 index 7ee76de03df1..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.h +++ /dev/null @@ -1,45 +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_STATE_TRANSACTION_BALLOT_STATE_H_ -#define BRAVELEDGER_STATE_TRANSACTION_BALLOT_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/transaction_ballot_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class TransactionBallotState - : public state::Reader, - public state::Writer { - public: - TransactionBallotState(); - ~TransactionBallotState(); - - bool FromJson( - const std::string& json, - TransactionBallotProperties* properties) const override; - - bool FromDict( - const base::DictionaryValue* dictionary, - TransactionBallotProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const TransactionBallotProperties& properties) const override; - - std::string ToJson( - const TransactionBallotProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_TRANSACTION_BALLOT_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc deleted file mode 100644 index 25a77d938113..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc +++ /dev/null @@ -1,55 +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 - -#include "bat/ledger/internal/state/transaction_ballot_state.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=TransactionBallotStateTest.* - -namespace ledger { - -TEST(TransactionBallotStateTest, ToJsonSerialization) { - // Arrange - TransactionBallotProperties transaction_ballot_properties; - transaction_ballot_properties.publisher = "Publisher"; - transaction_ballot_properties.count = - std::numeric_limits::max(); - - // Act - const TransactionBallotState transaction_ballot_state; - const std::string json = - transaction_ballot_state.ToJson(transaction_ballot_properties); - - // Assert - TransactionBallotProperties expected_transaction_ballot_properties; - transaction_ballot_state.FromJson(json, - &expected_transaction_ballot_properties); - EXPECT_EQ(expected_transaction_ballot_properties, - transaction_ballot_properties); -} - -TEST(TransactionBallotStateTest, FromJsonDeserialization) { - // Arrange - TransactionBallotProperties transaction_ballot_properties; - transaction_ballot_properties.publisher = "Publisher"; - transaction_ballot_properties.count = - std::numeric_limits::max(); - - const std::string json = "{\"publisher\":\"Publisher\",\"offset\":4294967295}"; // NOLINT - - // Act - TransactionBallotProperties expected_transaction_ballot_properties; - const TransactionBallotState transaction_ballot_state; - transaction_ballot_state.FromJson(json, - &expected_transaction_ballot_properties); - - // Assert - EXPECT_EQ(expected_transaction_ballot_properties, - transaction_ballot_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.cc deleted file mode 100644 index 02bb7b00a6e6..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.cc +++ /dev/null @@ -1,341 +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/state/transaction_ballot_state.h" -#include "bat/ledger/internal/state/transaction_state.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace ledger { - -namespace { - -// Do not change these values as they are required to transition legacy state -const char kAnonizeViewingIdKey[] = "anonizeViewingId"; -const char kBallotsKey[] = "ballots"; -const char kContributionProbiKey[] = "contribution_probi"; -const char kContributionRatesKey[] = "rates"; -const char kMasterUserTokenKey[] = "masterUserToken"; -const char kRegistrarVkKey[] = "registrarVK"; -const char kSubmissionTimestampKey[] = "submissionStamp"; -const char kSurveyorIdKey[] = "surveyorId"; -const char kSurveyorIdsKey[] = "surveyorIds"; -const char kViewingIdKey[] = "viewingId"; -const char kVoteCountKey[] = "votes"; -const char kProbiKey[] = "probi"; -const char kPaymentTimestampKey[] = "paymentStamp"; - -} // namespace - -TransactionState::TransactionState() = default; - -TransactionState::~TransactionState() = default; - -bool TransactionState::FromJson( - const std::string& json, - TransactionProperties* 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; - } - - return FromDict(dictionary, properties); -} - -bool TransactionState::FromJsonResponse( - const std::string& json, - TransactionProperties* 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; - } - - TransactionProperties transaction_properties; - - // Contribution Probi - const auto* contribution_probi = - dictionary->FindStringKey(kProbiKey); - if (!contribution_probi) { - NOTREACHED(); - return false; - } - transaction_properties.contribution_probi = *contribution_probi; - - // Submission Timestamp - const auto submission_timestamp = - dictionary->FindDoubleKey(kPaymentTimestampKey); - if (!submission_timestamp) { - NOTREACHED(); - return false; - } - transaction_properties.submission_timestamp = - std::to_string(static_cast(*submission_timestamp)); - - *properties = transaction_properties; - - return true; -} - -bool TransactionState::FromDict( - const base::DictionaryValue* dictionary, - TransactionProperties* properties) const { - DCHECK(dictionary); - if (!dictionary) { - NOTREACHED(); - return false; - } - - DCHECK(properties); - if (!properties) { - NOTREACHED(); - return false; - } - - TransactionProperties transaction; - - // Viewing Id - const auto* viewing_id = dictionary->FindStringKey(kViewingIdKey); - if (!viewing_id) { - NOTREACHED(); - return false; - } - transaction.viewing_id = *viewing_id; - - // Surveyor Id - const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); - if (!surveyor_id) { - NOTREACHED(); - return false; - } - transaction.surveyor_id = *surveyor_id; - - // Contribution Rates - const auto* contributions_rates = - dictionary->FindDictKey(kContributionRatesKey); - if (!contributions_rates) { - NOTREACHED(); - return false; - } - - for (const auto& contribution_rate : contributions_rates->DictItems()) { - const std::string currency_code = contribution_rate.first; - - const auto& exchange_rate_value = contribution_rate.second; - const double exchange_rate = exchange_rate_value.GetDouble(); - - transaction.contribution_rates.insert( - {currency_code, exchange_rate}); - } - - // Contribution Probi - const auto* contribution_probi = - dictionary->FindStringKey(kContributionProbiKey); - if (!contribution_probi) { - NOTREACHED(); - return false; - } - transaction.contribution_probi = *contribution_probi; - - // Submission Timestamp - const auto* submission_timestamp = - dictionary->FindStringKey(kSubmissionTimestampKey); - if (!submission_timestamp) { - NOTREACHED(); - return false; - } - transaction.submission_timestamp = *submission_timestamp; - - // Anonize Viewing Id - const auto* anonize_viewing_id = - dictionary->FindStringKey(kAnonizeViewingIdKey); - if (!anonize_viewing_id) { - NOTREACHED(); - return false; - } - transaction.anonize_viewing_id = *anonize_viewing_id; - - // Registrar VK - const auto* registrar_vk = dictionary->FindStringKey(kRegistrarVkKey); - if (!registrar_vk) { - NOTREACHED(); - return false; - } - transaction.registrar_vk = *registrar_vk; - - // Master user token - const auto* master_user_token = - dictionary->FindStringKey(kMasterUserTokenKey); - if (!master_user_token) { - NOTREACHED(); - return false; - } - transaction.master_user_token = *master_user_token; - - // Surveyor Ids - const auto* surveyor_ids_list = dictionary->FindListKey(kSurveyorIdsKey); - if (!surveyor_ids_list) { - NOTREACHED(); - return false; - } - - for (const auto& surveyor_id_value : surveyor_ids_list->GetList()) { - if (!surveyor_id_value.is_string()) { - NOTREACHED(); - continue; - } - - const std::string surveyor_id = surveyor_id_value.GetString(); - - transaction.surveyor_ids.push_back(surveyor_id); - } - - // Votes (There is no support for unsigned int. Writing JSON with such types - // violates the spec. As we need an unsigned int, we need to a double and cast - // to an unsigned int) - const auto vote_count = dictionary->FindDoubleKey(kVoteCountKey); - if (!vote_count) { - NOTREACHED(); - return false; - } - transaction.vote_count = static_cast(*vote_count); - - // Ballots - const auto* ballots_list = dictionary->FindListKey(kBallotsKey); - if (!ballots_list) { - NOTREACHED(); - return false; - } - - const TransactionBallotState transaction_ballance_state; - for (const auto& ballot_value : ballots_list->GetList()) { - if (!ballot_value.is_dict()) { - NOTREACHED(); - continue; - } - - const base::DictionaryValue* ballot_dictionary = nullptr; - ballot_value.GetAsDictionary(&ballot_dictionary); - if (!ballot_dictionary) { - NOTREACHED(); - continue; - } - - TransactionBallotProperties transaction_ballot; - if (!transaction_ballance_state.FromDict(ballot_dictionary, - &transaction_ballot)) { - continue; - } - - transaction.transaction_ballots.push_back(transaction_ballot); - } - - *properties = transaction; - - return true; -} - -bool TransactionState::ToJson( - JsonWriter* writer, - const TransactionProperties& properties) const { - DCHECK(writer); - if (!writer) { - NOTREACHED(); - return false; - } - - writer->StartObject(); - - writer->String(kViewingIdKey); - writer->String(properties.viewing_id.c_str()); - - writer->String(kSurveyorIdKey); - writer->String(properties.surveyor_id.c_str()); - - writer->String(kContributionRatesKey); - writer->StartObject(); - for (const auto& contribution_rate : properties.contribution_rates) { - writer->String(contribution_rate.first.c_str()); - writer->Double(contribution_rate.second); - } - writer->EndObject(); - - writer->String(kContributionProbiKey); - writer->String(properties.contribution_probi.c_str()); - - writer->String(kSubmissionTimestampKey); - writer->String(properties.submission_timestamp.c_str()); - - writer->String(kAnonizeViewingIdKey); - writer->String(properties.anonize_viewing_id.c_str()); - - writer->String(kRegistrarVkKey); - writer->String(properties.registrar_vk.c_str()); - - writer->String(kMasterUserTokenKey); - writer->String(properties.master_user_token.c_str()); - - writer->String(kSurveyorIdsKey); - writer->StartArray(); - for (const auto& surveyor_id : properties.surveyor_ids) { - writer->String(surveyor_id.c_str()); - } - writer->EndArray(); - - writer->String(kVoteCountKey); - writer->Uint(properties.vote_count); - - writer->String(kBallotsKey); - writer->StartArray(); - const TransactionBallotState transaction_ballot_state; - for (const auto& ballot : properties.transaction_ballots) { - transaction_ballot_state.ToJson(writer, ballot); - } - writer->EndArray(); - - writer->EndObject(); - - return true; -} - -std::string TransactionState::ToJson( - const TransactionProperties& 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/state/transaction_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.h deleted file mode 100644 index 1e150e0358c2..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_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_STATE_TRANSACTION_STATE_H_ -#define BRAVELEDGER_STATE_TRANSACTION_STATE_H_ - -#include - -#include "bat/ledger/internal/state/state_reader.h" -#include "bat/ledger/internal/state/state_writer.h" -#include "bat/ledger/internal/properties/transaction_properties.h" -#include "rapidjson/writer.h" - -namespace ledger { - -using JsonWriter = rapidjson::Writer; - -class TransactionState - : public state::Reader, - public state::Writer { - public: - TransactionState(); - ~TransactionState(); - - bool FromJson( - const std::string& json, - TransactionProperties* properties) const override; - - bool FromJsonResponse( - const std::string& json, - TransactionProperties* properties) const; - - bool FromDict( - const base::DictionaryValue* dictionary, - TransactionProperties* properties) const override; - - bool ToJson( - JsonWriter* writer, - const TransactionProperties& properties) const override; - - std::string ToJson( - const TransactionProperties& properties) const override; -}; - -} // namespace ledger - -#endif // BRAVELEDGER_STATE_TRANSACTION_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc deleted file mode 100644 index 16aded03da2a..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc +++ /dev/null @@ -1,149 +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 - -#include "bat/ledger/internal/state/transaction_state.h" -#include "bat/ledger/internal/properties/transaction_ballot_properties.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=TransactionPropertiesTest.* - -namespace ledger { - -TEST(TransactionStateTest, ToJsonSerialization) { - // Arrange - TransactionProperties transaction_properties; - transaction_properties.viewing_id = "ViewingId"; - transaction_properties.surveyor_id = "SurveyorId"; - transaction_properties.contribution_probi = "ContributionProbi"; - transaction_properties.submission_timestamp = "SubmissionTimestamp"; - transaction_properties.anonize_viewing_id = "AnonizeViewingId"; - transaction_properties.registrar_vk = "RegistrarVk"; - transaction_properties.master_user_token = "MasterUserToken"; - transaction_properties.surveyor_ids = { "SurveyorId" }; - transaction_properties.vote_count = std::numeric_limits::max(); - transaction_properties.contribution_rates = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 } - }; - - TransactionBallotProperties transaction_ballot_properties; - transaction_ballot_properties.publisher = "Publisher"; - transaction_ballot_properties.count = - std::numeric_limits::max(); - transaction_properties.transaction_ballots.push_back( - transaction_ballot_properties); - - // Act - const TransactionState transaction_state; - const std::string json = transaction_state.ToJson(transaction_properties); - - // Assert - TransactionProperties expected_transaction_properties; - transaction_state.FromJson(json, &expected_transaction_properties); - EXPECT_EQ(expected_transaction_properties, transaction_properties); -} - -TEST(TransactionStateTest, FromJsonDeserialization) { - // Arrange - TransactionProperties transaction_properties; - transaction_properties.viewing_id = "ViewingId"; - transaction_properties.surveyor_id = "SurveyorId"; - transaction_properties.contribution_probi = "ContributionProbi"; - transaction_properties.submission_timestamp = "SubmissionTimestamp"; - transaction_properties.anonize_viewing_id = "AnonizeViewingId"; - transaction_properties.registrar_vk = "RegistrarVk"; - transaction_properties.master_user_token = "MasterUserToken"; - transaction_properties.surveyor_ids = { "SurveyorId" }; - transaction_properties.vote_count = std::numeric_limits::max(); - transaction_properties.contribution_rates = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 } - }; - - TransactionBallotProperties transaction_ballot_properties; - transaction_ballot_properties.publisher = "Publisher"; - transaction_ballot_properties.count = - std::numeric_limits::max(); - transaction_properties.transaction_ballots.push_back( - transaction_ballot_properties); - - const std::string json = "{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"contribution_probi\":\"ContributionProbi\",\"submissionStamp\":\"SubmissionTimestamp\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"surveyorIds\":[\"SurveyorId\"],\"votes\":4294967295,\"ballots\":[{\"publisher\":\"Publisher\",\"offset\":4294967295}]}"; // NOLINT - - // Act - TransactionProperties expected_transaction_properties; - const TransactionState transaction_state; - transaction_state.FromJson(json, &expected_transaction_properties); - - // Assert - EXPECT_EQ(expected_transaction_properties, transaction_properties); -} - -TEST(TransactionStateTest, FromJsonResponseDeserialization) { - // Arrange - TransactionProperties transaction_properties; - transaction_properties.contribution_probi = "Probi"; - transaction_properties.submission_timestamp = "1579627546681"; - - const std::string json = "{\"probi\":\"Probi\",\"paymentStamp\":1579627546681}"; // NOLINT - - // Act - TransactionProperties expected_transaction_properties; - const TransactionState transaction_state; - transaction_state.FromJsonResponse(json, &expected_transaction_properties); - - // Assert - EXPECT_EQ(expected_transaction_properties, transaction_properties); -} - -TEST(TransactionStateTest, FromInvalidJsonResponseDeserialization) { - // Arrange - TransactionProperties transaction_properties; - transaction_properties.viewing_id = "ViewingId"; - transaction_properties.surveyor_id = "SurveyorId"; - transaction_properties.contribution_probi = "ContributionProbi"; - transaction_properties.submission_timestamp = "SubmissionTimestamp"; - transaction_properties.anonize_viewing_id = "AnonizeViewingId"; - transaction_properties.registrar_vk = "RegistrarVk"; - transaction_properties.master_user_token = "MasterUserToken"; - transaction_properties.surveyor_ids = { "SurveyorId" }; - transaction_properties.vote_count = std::numeric_limits::max(); - transaction_properties.contribution_rates = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 } - }; - - TransactionBallotProperties transaction_ballot_properties; - transaction_ballot_properties.publisher = "Publisher"; - transaction_ballot_properties.count = - std::numeric_limits::max(); - transaction_properties.transaction_ballots.push_back( - transaction_ballot_properties); - - const std::string json = "FOOBAR"; - - // Act - TransactionProperties expected_transaction_properties; - const TransactionState transaction_state; - transaction_state.FromJsonResponse(json, &expected_transaction_properties); - - // Assert - EXPECT_NE(expected_transaction_properties, transaction_properties); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.cc index a8d137729323..df8ea5964ddc 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.cc @@ -12,7 +12,6 @@ namespace ledger { namespace { // Do not change these values as they are required to transition legacy state -const char kFeeAmountKey[] = "fee_amount"; const char kParametersKey[] = "parameters"; const char kAdFreeKey[] = "adFree"; const char kFeeKey[] = "fee"; @@ -125,9 +124,6 @@ bool WalletState::ToJson( writer->StartObject(); - writer->String(kFeeAmountKey); - writer->Double(properties.fee_amount); - writer->String(kParametersKey); writer->StartObject(); writer->String(kAdFreeKey); 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 491cf1c4555d..58febe983f13 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 @@ -45,22 +45,21 @@ #define PROMOTION_DEVELOPMENT_SERVER \ "https://grant.rewards.brave.software" +#define PAYMENTS_STAGING_SERVER \ +"http://payment.rewards.bravesoftware.com" +#define PAYMENTS_PRODUCTION_SERVER \ +"http://payment.rewards.brave.com" +#define PAYMENTS_DEVELOPMENT_SERVER \ +"https://payment.rewards.brave.software" + #define PREFIX_V1 "/v1" #define PREFIX_V2 "/v2" #define PREFIX_V3 "/v3" #define PREFIX_V4 "/v4" #define PREFIX_V5 "/v5" #define REGISTER_PERSONA "/registrar/persona" -#define REGISTER_VIEWING "/registrar/viewing" #define WALLET_PROPERTIES "/wallet/" #define WALLET_PROPERTIES_END "/balance" -#define RECONCILE_CONTRIBUTION "/surveyor/contribution/current/" -#define SURVEYOR_VOTING "/surveyor/voting/" -#define SURVEYOR_BATCH_VOTING "/batch/surveyor/voting" -#define UPDATE_RULES_V1 \ -"/v1/publisher/ruleset?consequential=true" -#define UPDATE_RULES_V2 \ -"/v2/publisher/ruleset?limit=512&excludedOnly=false" #define RECOVER_WALLET_PUBLIC_KEY "/wallet?publicKey=" #define GET_PROMOTION_CAPTCHA "/captchas/" #define GET_PUBLISHERS_LIST "/api/v3/public/channels" @@ -75,8 +74,6 @@ #define SIGNATURE_ALGORITHM "ed25519" -#define AD_FREE_SETTINGS "adFree" - #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" @@ -154,6 +151,8 @@ static const std::vector _add_funds_limited_countries = { "JP" }; +static const double _vote_price = 0.25; + } // namespace braveledger_ledger #endif // BRAVELEDGER_STATIC_VALUES_H_ 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 dea87172003f..690554d176c7 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 @@ -65,7 +65,7 @@ void Uphold::StartContribution( if (!info) { ContributionCompleted( ledger::Result::LEDGER_ERROR, - false, + "", contribution_id, amount, "", @@ -94,7 +94,7 @@ void Uphold::StartContribution( void Uphold::ContributionCompleted( const ledger::Result result, - const bool created, + const std::string& transaction_id, const std::string& contribution_id, const double fee, const std::string& publisher_key, @@ -113,7 +113,8 @@ void Uphold::ContributionCompleted( ledger_->UpdateContributionInfoContributedAmount( contribution_id, publisher_key, - [](const ledger::Result){}); + callback); + return; } } @@ -196,10 +197,11 @@ void Uphold::OnFetchBalance( callback(ledger::Result::LEDGER_ERROR, 0.0); } -void Uphold::TransferFunds(double amount, - const std::string& address, - ledger::ExternalWalletPtr wallet, - TransactionCallback callback) { +void Uphold::TransferFunds( + const double amount, + const std::string& address, + ledger::ExternalWalletPtr wallet, + ledger::TransactionCallback callback) { Transaction transaction; transaction.address = address; transaction.amount = amount; @@ -310,7 +312,7 @@ void Uphold::SaveTransferFee(ledger::TransferFeePtr transfer_fee) { void Uphold::OnTransferFeeCompleted( const ledger::Result result, - const bool created, + const std::string& transaction_id, const ledger::TransferFee& transfer_fee) { if (result == ledger::Result::LEDGER_OK) { ledger_->RemoveTransferFee(ledger::kWalletUphold, transfer_fee.id); 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 09bdf0b7f4d8..959dd1c3f34b 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 @@ -32,7 +32,6 @@ class UpholdCard; class UpholdAuthorization; class UpholdWallet; -using TransactionCallback = std::function; using FetchBalanceCallback = std::function; using CreateCardCallback = std::function; @@ -57,10 +56,11 @@ class Uphold { void FetchBalance(std::map wallets, FetchBalanceCallback callback); - void TransferFunds(double amount, - const std::string& address, - ledger::ExternalWalletPtr wallet, - TransactionCallback callback); + void TransferFunds( + const double amount, + const std::string& address, + ledger::ExternalWalletPtr wallet, + ledger::TransactionCallback callback); void WalletAuthorization( const std::map& args, @@ -94,16 +94,12 @@ class Uphold { private: void ContributionCompleted( const ledger::Result result, - const bool created, + const std::string& transaction_id, const std::string& contribution_id, const double fee, const std::string& publisher_key, ledger::ResultCallback callback); - void OnFeeCompleted(ledger::Result result, - bool created, - const std::string &viewing_id); - void OnFetchBalance( FetchBalanceCallback callback, int response_status_code, @@ -123,7 +119,7 @@ class Uphold { void OnTransferFeeCompleted( const ledger::Result result, - const bool created, + const std::string& transaction_id, const ledger::TransferFee& transfer_fee); void TransferFee( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.cc index 7b500685607c..3f875d2ab318 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.cc @@ -29,9 +29,9 @@ UpholdTransfer::~UpholdTransfer() { void UpholdTransfer::Start( const Transaction& transaction, ledger::ExternalWalletPtr wallet, - TransactionCallback callback) { + ledger::TransactionCallback callback) { if (!wallet) { - callback(ledger::Result::LEDGER_ERROR, false); + callback(ledger::Result::LEDGER_ERROR, ""); return; } @@ -41,7 +41,7 @@ void UpholdTransfer::Start( void UpholdTransfer::CreateTransaction( const Transaction& transaction, ledger::ExternalWalletPtr wallet, - TransactionCallback callback) { + ledger::TransactionCallback callback) { auto headers = RequestAuthorization(wallet->token); const std::string path = base::StringPrintf( @@ -79,36 +79,36 @@ void UpholdTransfer::OnCreateTransaction( const std::string& response, const std::map& headers, const ledger::ExternalWallet& wallet, - TransactionCallback callback) { + ledger::TransactionCallback callback) { ledger_->LogResponse(__func__, response_status_code, response, headers); if (response_status_code == net::HTTP_UNAUTHORIZED) { - callback(ledger::Result::EXPIRED_TOKEN, false); + callback(ledger::Result::EXPIRED_TOKEN, ""); uphold_->DisconnectWallet(); return; } if (response_status_code != net::HTTP_ACCEPTED) { // TODO(nejczdovc): add retry logic to all errors in this function - callback(ledger::Result::LEDGER_ERROR, false); + callback(ledger::Result::LEDGER_ERROR, ""); return; } base::Optional value = base::JSONReader::Read(response); if (!value || !value->is_dict()) { - callback(ledger::Result::LEDGER_ERROR, false); + callback(ledger::Result::LEDGER_ERROR, ""); return; } base::DictionaryValue* dictionary = nullptr; if (!value->GetAsDictionary(&dictionary)) { - callback(ledger::Result::LEDGER_ERROR, false); + callback(ledger::Result::LEDGER_ERROR, ""); return; } const auto* id = dictionary->FindStringKey("id"); if (!id) { - callback(ledger::Result::LEDGER_ERROR, false); + callback(ledger::Result::LEDGER_ERROR, ""); return; } @@ -117,7 +117,7 @@ void UpholdTransfer::OnCreateTransaction( void UpholdTransfer::CommitTransaction(const std::string& transaction_id, const ledger::ExternalWallet& wallet, - TransactionCallback callback) { + ledger::TransactionCallback callback) { auto headers = RequestAuthorization(wallet.token); const std::string path = base::StringPrintf( @@ -130,6 +130,7 @@ void UpholdTransfer::CommitTransaction(const std::string& transaction_id, _1, _2, _3, + transaction_id, callback); ledger_->LoadURL( GetAPIUrl(path), @@ -144,21 +145,22 @@ void UpholdTransfer::OnCommitTransaction( int response_status_code, const std::string& response, const std::map& headers, - TransactionCallback callback) { + const std::string& transaction_id, + ledger::TransactionCallback callback) { ledger_->LogResponse(__func__, response_status_code, response, headers); if (response_status_code == net::HTTP_UNAUTHORIZED) { - callback(ledger::Result::EXPIRED_TOKEN, true); + callback(ledger::Result::EXPIRED_TOKEN, ""); uphold_->DisconnectWallet(); return; } if (response_status_code != net::HTTP_OK) { - callback(ledger::Result::LEDGER_ERROR, true); + callback(ledger::Result::LEDGER_ERROR, ""); return; } - callback(ledger::Result::LEDGER_OK, true); + callback(ledger::Result::LEDGER_OK, transaction_id); } } // namespace braveledger_uphold diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.h b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.h index 2868eda9f03b..57577366af2d 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_transfer.h @@ -27,31 +27,32 @@ class UpholdTransfer { void Start( const Transaction& transaction, ledger::ExternalWalletPtr wallet, - TransactionCallback callback); + ledger::TransactionCallback callback); private: void CreateTransaction( const Transaction& transaction, ledger::ExternalWalletPtr wallet, - TransactionCallback callback); + ledger::TransactionCallback callback); void OnCreateTransaction( int response_status_code, const std::string& response, const std::map& headers, const ledger::ExternalWallet& wallet, - TransactionCallback callback); + ledger::TransactionCallback callback); void CommitTransaction( const std::string& transaction_id, const ledger::ExternalWallet& wallet, - TransactionCallback callback); + ledger::TransactionCallback callback); void OnCommitTransaction( int response_status_code, const std::string& response, const std::map& headers, - TransactionCallback callback); + const std::string& transaction_id, + ledger::TransactionCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED Uphold* uphold_; // NOT OWNED diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.cc index 039f9546a354..6256a49faeff 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.cc @@ -49,6 +49,13 @@ std::string GetFeeAddress() { : kFeeAddressStaging; } + +std::string GetACAddress() { + return ledger::_environment == ledger::Environment::PRODUCTION + ? kACAddressProduction + : kACAddressStaging; +} + std::string GetVerifyUrl(const std::string& state) { const std::string id = GetClientId(); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.h index 1ab5b2387e69..3853c9523c97 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util.h @@ -25,6 +25,8 @@ const char kClientSecretProduction[] = "de1aa4196c8d4aa50c6bc1371734e3f57f781f72"; const char kFeeAddressStaging[] = "1b2b466f-5c15-49bf-995e-c91777d3da93"; const char kFeeAddressProduction[] = "b01e8c55-5004-4761-9e4b-01ec13e25c92"; +const char kACAddressStaging[] = "1b2b466f-5c15-49bf-995e-c91777d3da93"; +const char kACAddressProduction[] = "b01e8c55-5004-4761-9e4b-01ec13e25c92"; std::string GetClientId(); @@ -36,6 +38,8 @@ std::string GetAPIUrl(const std::string& path); std::string GetFeeAddress(); +std::string GetACAddress(); + std::string GetVerifyUrl(const std::string& state); std::string GetAddUrl(const std::string& address); 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 d9d73e282098..5c78f710ccf1 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 @@ -43,6 +43,8 @@ void UpholdWallet::Generate( } } + wallet->type = ledger::kWalletUphold; + if (wallet->one_time_string.empty()) { wallet->one_time_string = GenerateRandomString(ledger::is_testing); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc index 505d6ff6a581..070c67456af5 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc @@ -115,7 +115,9 @@ void Balance::GetUnBlindedTokens( *balance, callback, _1); - ledger_->GetAllUnblindedTokens(tokens_callback); + ledger_->GetUnblindedTokensByBatchTypes( + {ledger::CredsBatchType::PROMOTION}, + tokens_callback); } void Balance::OnGetUnBlindedTokens( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc index ceda55786381..ea2338d388c3 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc @@ -235,7 +235,6 @@ void Create::RegisterPersonaCallback( ledger_->GetRegistrarVK().c_str()); if (masterUserToken != nullptr) { - ledger_->SetMasterUserToken(masterUserToken); // should fix in // https://github.com/brave-intl/bat-native-anonize/issues/11 free((void*)masterUserToken); // NOLINT @@ -246,22 +245,16 @@ void Create::RegisterPersonaCallback( } ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); - unsigned int days; double fee_amount = .0; - std::string currency; if (!braveledger_bat_helper::getJSONWalletInfo(response, &wallet_info, - ¤cy, - &fee_amount, - &days)) { + &fee_amount)) { callback(ledger::Result::BAD_REGISTRATION_RESPONSE); return; } ledger_->SetWalletInfo(wallet_info); - ledger_->SetCurrency(currency); ledger_->SetContributionAmount(fee_amount); - ledger_->SetDays(days); ledger_->SetBootStamp(braveledger_time_util::GetCurrentTimeStamp()); ledger_->ResetReconcileStamp(); callback(ledger::Result::WALLET_CREATED); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc index 7a6bf74a9985..c2c372d4aec1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc @@ -183,24 +183,18 @@ void Recover::RecoverWalletCallback( ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); ledger::WalletProperties properties = ledger_->GetWalletProperties(); - unsigned int days; double fee_amount = .0; double balance = .0; - std::string currency; braveledger_bat_helper::getJSONWalletInfo( response, &wallet_info, - ¤cy, - &fee_amount, - &days); + &fee_amount); braveledger_bat_helper::getJSONRecoverWallet( response, &balance); - ledger_->SetCurrency(currency); if (!ledger_->GetUserChangedContribution()) { ledger_->SetContributionAmount(fee_amount); } - ledger_->SetDays(days); ledger_->SetWalletProperties(&properties); wallet_info.payment_id = recoveryId; diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.h b/vendor/brave-ios/Ledger/BATBraveLedger.h index 3c7100761797..4ea08e314d77 100644 --- a/vendor/brave-ios/Ledger/BATBraveLedger.h +++ b/vendor/brave-ios/Ledger/BATBraveLedger.h @@ -175,6 +175,11 @@ NS_SWIFT_NAME(BraveLedger) - (void)refreshPublisherWithId:(NSString *)publisherId completion:(void (^)(BATPublisherStatus status))completion; +#pragma mark - SKUs + +- (void)processSKUItems:(NSArray *)items + completion:(void (^)(BATResult result, NSString *orderID))completion; + #pragma mark - Tips /// Get a list of publishers who the user has recurring tips on diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.mm b/vendor/brave-ios/Ledger/BATBraveLedger.mm index 8d19a8a07b92..feb4a5b85a74 100644 --- a/vendor/brave-ios/Ledger/BATBraveLedger.mm +++ b/vendor/brave-ios/Ledger/BATBraveLedger.mm @@ -4,6 +4,7 @@ #import #import "bat/ledger/ledger.h" +#import "bat/ledger/global_constants.h" #import "bat/ledger/option_keys.h" #import "Records+Private.h" @@ -787,6 +788,21 @@ - (void)refreshPublisherWithId:(NSString *)publisherId completion:(void (^)(BATP }); } +#pragma mark - SKUs + +- (void)processSKUItems:(NSArray *)items + completion:(void (^)(BATResult result, NSString *orderID))completion +{ + auto wallet = ledger::ExternalWallet::New(); + wallet->type = ledger::kWalletUnBlinded; + + ledger->ProcessSKU(VectorFromNSArray(items, ^ledger::SKUOrderItem(BATSKUOrderItem *item) { + return *item.cppObjPtr; + }), std::move(wallet), ^(const ledger::Result result, const std::string& order_id) { + completion(static_cast(result), [NSString stringWithUTF8String:order_id.c_str()]); + }); +} + #pragma mark - Tips - (void)listRecurringTips:(void (^)(NSArray *))completion