diff --git a/components/brave_rewards/browser/android_util.cc b/components/brave_rewards/browser/android_util.cc index b9dde3cbd726..651c4563cb11 100644 --- a/components/brave_rewards/browser/android_util.cc +++ b/components/brave_rewards/browser/android_util.cc @@ -15,23 +15,4 @@ ledger::ClientInfoPtr GetAndroidClientInfo() { return info; } -std::string ParseClaimPromotionResponse(const std::string& response) { - base::Optional value = base::JSONReader::Read(response); - if (!value || !value->is_dict()) { - return ""; - } - - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - return ""; - } - - auto* nonce = dictionary->FindKey("nonce"); - if (!nonce || !nonce->is_string()) { - return ""; - } - - return nonce->GetString(); -} - } // namespace android_util diff --git a/components/brave_rewards/browser/android_util.h b/components/brave_rewards/browser/android_util.h index 1438bbc8c632..befda9c1e32d 100644 --- a/components/brave_rewards/browser/android_util.h +++ b/components/brave_rewards/browser/android_util.h @@ -14,8 +14,6 @@ namespace android_util { ledger::ClientInfoPtr GetAndroidClientInfo(); -std::string ParseClaimPromotionResponse(const std::string& response); - } // namespace android_util #endif // BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_ANDROID_UTIL_H_ diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index b6d211b40420..708d52337216 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -1257,13 +1257,12 @@ void RewardsServiceImpl::AttestationAndroid( const std::string& promotion_id, AttestPromotionCallback callback, const ledger::Result result, - const std::string& response) { + const std::string& nonce) { if (result != ledger::Result::LEDGER_OK) { std::move(callback).Run(static_cast(result), nullptr); return; } - const std::string nonce = android_util::ParseClaimPromotionResponse(response); if (nonce.empty()) { std::move(callback).Run( static_cast(ledger::Result::LEDGER_ERROR), diff --git a/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc b/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc index 8c75427d6a14..f5fc29a6c8e6 100644 --- a/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc +++ b/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc @@ -230,11 +230,7 @@ void RewardsBrowserTestResponse::Get( return; } - if (URLMatches( - url, - "/wallet/uphold", - PREFIX_V3, - ServerTypes::kPromotion)) { + if (url.find("/v3/wallet/uphold") != std::string::npos) { if (user_funds_balance_) { *response = user_funds_balance_resp_; } else { @@ -248,11 +244,7 @@ void RewardsBrowserTestResponse::Get( return; } - if (URLMatches( - url, - "/promotions?", - PREFIX_V1, - ServerTypes::kPromotion)) { + if (url.find("v1/promotions?") != std::string::npos) { if (empty_promotion_key_) { *response = promotion_empty_key_; } else { @@ -261,11 +253,7 @@ void RewardsBrowserTestResponse::Get( return; } - if (URLMatches( - url, - "/promotions/", - PREFIX_V1, - ServerTypes::kPromotion)) { + if (url.find("/v1/promotions") != std::string::npos) { if (url.find("claims") != std::string::npos) { *response = creds_tokens_; } else { @@ -274,11 +262,7 @@ void RewardsBrowserTestResponse::Get( return; } - if (URLMatches( - url, - "/captchas", - PREFIX_V1, - ServerTypes::kPromotion)) { + if (url.find("/v1/captchas") != std::string::npos) { *response = captcha_; } diff --git a/components/brave_rewards/test/BUILD.gn b/components/brave_rewards/test/BUILD.gn index 19a064d780ba..ab64a6fd89af 100644 --- a/components/brave_rewards/test/BUILD.gn +++ b/components/brave_rewards/test/BUILD.gn @@ -49,6 +49,25 @@ source_set("brave_rewards_unit_tests") { "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_util_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold_util_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc", diff --git a/vendor/bat-native-ledger/BUILD.gn b/vendor/bat-native-ledger/BUILD.gn index aea6bbc0a0a9..41cdbb9e454f 100644 --- a/vendor/bat-native-ledger/BUILD.gn +++ b/vendor/bat-native-ledger/BUILD.gn @@ -300,36 +300,66 @@ source_set("ledger") { "src/bat/ledger/internal/recovery/recovery_empty_balance.h", "src/bat/ledger/internal/report/report.cc", "src/bat/ledger/internal/report/report.h", - "src/bat/ledger/internal/request/request_attestation.cc", - "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_publisher.cc", "src/bat/ledger/internal/request/request_publisher.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/response/response_attestation.cc", - "src/bat/ledger/internal/response/response_attestation.h", "src/bat/ledger/internal/response/response_credentials.cc", "src/bat/ledger/internal/response/response_credentials.h", - "src/bat/ledger/internal/response/response_promotion.cc", - "src/bat/ledger/internal/response/response_promotion.h", "src/bat/ledger/internal/response/response_publisher.cc", "src/bat/ledger/internal/response/response_publisher.h", "src/bat/ledger/internal/response/response_sku.cc", "src/bat/ledger/internal/response/response_sku.h", "src/bat/ledger/internal/response/response_uphold.cc", "src/bat/ledger/internal/response/response_uphold.h", - "src/bat/ledger/internal/response/response_wallet.cc", - "src/bat/ledger/internal/response/response_wallet.h", "src/bat/ledger/internal/endpoint/api/api_server.cc", "src/bat/ledger/internal/endpoint/api/api_server.h", "src/bat/ledger/internal/endpoint/api/api_util.cc", "src/bat/ledger/internal/endpoint/api/api_util.h", "src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters.cc", "src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters.h", + "src/bat/ledger/internal/endpoint/promotion/get_available/get_available.cc", + "src/bat/ledger/internal/endpoint/promotion/get_available/get_available.h", + "src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.cc", + "src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.h", + "src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.cc", + "src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.h", + "src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.cc", + "src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.h", + "src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.cc", + "src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.h", + "src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.cc", + "src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.h", + "src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.cc", + "src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.h", + "src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.cc", + "src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.h", + "src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.cc", + "src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.h", + "src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.cc", + "src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.h", + "src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.cc", + "src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.h", + "src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.cc", + "src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.h", + "src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.cc", + "src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.h", + "src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.cc", + "src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.h", + "src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.cc", + "src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.h", + "src/bat/ledger/internal/endpoint/promotion/promotion_server.cc", + "src/bat/ledger/internal/endpoint/promotion/promotion_server.h", + "src/bat/ledger/internal/endpoint/promotion/promotions_util.cc", + "src/bat/ledger/internal/endpoint/promotion/promotions_util.h", + "src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.cc", + "src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.h", + "src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.cc", + "src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.h", + "src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.cc", + "src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.h", "src/bat/ledger/internal/sku/sku.h", "src/bat/ledger/internal/sku/sku_brave.cc", "src/bat/ledger/internal/sku/sku_brave.h", diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.cc index f8fb9deea128..611e37534f76 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.cc @@ -6,11 +6,13 @@ #include "bat/ledger/internal/attestation/attestation.h" #include "bat/ledger/internal/ledger_impl.h" -namespace braveledger_attestation { +namespace ledger { +namespace attestation { Attestation::Attestation(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { } Attestation::~Attestation() = default; -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.h b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.h index fab7628cda58..87c98edb9a07 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation.h @@ -15,7 +15,8 @@ namespace bat_ledger { class LedgerImpl; } -namespace braveledger_attestation { +namespace ledger { +namespace attestation { using StartCallback = std::function; @@ -38,5 +39,6 @@ class Attestation { bat_ledger::LedgerImpl* ledger_; // NOT OWNED }; -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger #endif // BRAVELEDGER_ATTESTATION_ATTESTATION_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.cc index afa9f851f014..94497ac44fd2 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.cc @@ -10,24 +10,27 @@ #include "base/json/json_writer.h" #include "bat/ledger/internal/attestation/attestation_androidx.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_attestation.h" -#include "bat/ledger/internal/response/response_attestation.h" using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; -namespace braveledger_attestation { +namespace ledger { +namespace attestation { AttestationAndroid::AttestationAndroid(bat_ledger::LedgerImpl* ledger) : - Attestation(ledger) { + Attestation(ledger), + promotion_server_(new endpoint::PromotionServer(ledger)) { } AttestationAndroid::~AttestationAndroid() = default; void AttestationAndroid::ParseClaimSolution( const std::string& response, - base::Value* result) { + std::string* token, + std::string* nonce) { + DCHECK(token && nonce); + base::Optional value = base::JSONReader::Read(response); if (!value || !value->is_dict()) { BLOG(0, "Parsing of solution failed"); @@ -40,20 +43,20 @@ void AttestationAndroid::ParseClaimSolution( return; } - const auto* nonce = dictionary->FindStringKey("nonce"); - if (!nonce) { + const auto* nonce_string = dictionary->FindStringKey("nonce"); + if (!nonce_string) { BLOG(0, "Nonce is missing"); return; } - const auto* token = dictionary->FindStringKey("token"); - if (!token) { + const auto* token_string = dictionary->FindStringKey("token"); + if (!token_string) { BLOG(0, "Token is missing"); return; } - result->SetStringKey("nonce", *nonce); - result->SetStringKey("token", *token); + *nonce = *nonce_string; + *token = *token_string; } void AttestationAndroid::Start( @@ -62,88 +65,42 @@ void AttestationAndroid::Start( auto url_callback = std::bind(&AttestationAndroid::OnStart, this, _1, + _2, callback); - - const std::string url = - braveledger_request_util::GetStartAttestationAndroidUrl(); - - auto payment_id = base::Value(ledger_->state()->GetPaymentId()); - base::Value payment_ids(base::Value::Type::LIST); - payment_ids.Append(std::move(payment_id)); - - base::Value body(base::Value::Type::DICTIONARY); - body.SetKey("paymentIds", std::move(payment_ids)); - - std::string json; - base::JSONWriter::Write(body, &json); - - ledger_->LoadURL( - url, - {}, - json, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - url_callback); + promotion_server_->post_safetynet()->Request(url_callback); } void AttestationAndroid::OnStart( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& nonce, StartCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckStartAttestation(response); if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Failed to start attestation"); callback(ledger::Result::LEDGER_ERROR, ""); return; } - callback(ledger::Result::LEDGER_OK, response.body); + callback(ledger::Result::LEDGER_OK, nonce); } void AttestationAndroid::Confirm( const std::string& solution, ConfirmCallback callback) { - base::Value parsed_solution(base::Value::Type::DICTIONARY); - ParseClaimSolution(solution, &parsed_solution); - - if (parsed_solution.DictSize() != 2) { - BLOG(0, "Solution is wrong: " << solution); - callback(ledger::Result::LEDGER_ERROR); - return; - } - - base::Value dictionary(base::Value::Type::DICTIONARY); - dictionary.SetStringKey("token", *parsed_solution.FindStringKey("token")); - std::string payload; - base::JSONWriter::Write(dictionary, &payload); - - const std::string nonce = *parsed_solution.FindStringKey("nonce"); - const std::string url = - braveledger_request_util::GetConfirmAttestationAndroidUrl(nonce); + std::string token; + std::string nonce; + ParseClaimSolution(solution, &token, &nonce); auto url_callback = std::bind(&AttestationAndroid::OnConfirm, this, _1, callback); - ledger_->LoadURL( - url, - {}, - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::PUT, - url_callback); + promotion_server_->put_safetynet()->Request(token, nonce, url_callback); } void AttestationAndroid::OnConfirm( - const ledger::UrlResponse& response, + const ledger::Result result, ConfirmCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckConfirmAttestation(response); if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Failed to confirm attestation"); callback(result); @@ -153,4 +110,5 @@ void AttestationAndroid::OnConfirm( callback(ledger::Result::LEDGER_OK); } -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.h b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.h index 17d8a2a56a3a..1cc5c9ae8d2e 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_androidx.h @@ -6,17 +6,19 @@ #ifndef BRAVELEDGER_ATTESTATION_ATTESTATION_ANDROID_H_ #define BRAVELEDGER_ATTESTATION_ATTESTATION_ANDROID_H_ -#include +#include #include #include "base/values.h" #include "bat/ledger/internal/attestation/attestation.h" +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_attestation { +namespace ledger { +namespace attestation { class AttestationAndroid : public Attestation { public: @@ -32,16 +34,21 @@ class AttestationAndroid : public Attestation { private: void ParseClaimSolution( const std::string& response, - base::Value* result); + std::string* token, + std::string* nonce); void OnStart( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& confirmation, StartCallback callback); void OnConfirm( - const ledger::UrlResponse& response, + const ledger::Result result, ConfirmCallback callback); + + std::unique_ptr promotion_server_; }; -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger #endif // BRAVELEDGER_ATTESTATION_ATTESTATION_ANDROID_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc index c93a42061e34..0b5bf8f0967f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.cc @@ -3,161 +3,117 @@ * 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 "base/json/json_reader.h" #include "base/json/json_writer.h" #include "bat/ledger/internal/attestation/attestation_desktop.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_attestation.h" -#include "bat/ledger/internal/response/response_attestation.h" using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; -namespace braveledger_attestation { +namespace ledger { +namespace attestation { AttestationDesktop::AttestationDesktop(bat_ledger::LedgerImpl* ledger) : - Attestation(ledger) { + Attestation(ledger), + promotion_server_(new endpoint::PromotionServer(ledger)) { } AttestationDesktop::~AttestationDesktop() = default; -void AttestationDesktop::ParseClaimSolution( +ledger::Result AttestationDesktop::ParseClaimSolution( const std::string& response, - base::Value* result) { + int* x, + int* y, + std::string* captcha_id) { + DCHECK(x && y && captcha_id); + base::Optional value = base::JSONReader::Read(response); if (!value || !value->is_dict()) { - return; + return ledger::Result::LEDGER_ERROR; } base::DictionaryValue* dictionary = nullptr; if (!value->GetAsDictionary(&dictionary)) { - return; + return ledger::Result::LEDGER_ERROR; } - const auto* captcha_id = dictionary->FindStringKey("captchaId"); - if (!captcha_id) { + const auto* id = dictionary->FindStringKey("captchaId"); + if (!id) { BLOG(0, "Captcha id is wrong"); - return; + return ledger::Result::LEDGER_ERROR; } - const auto x = dictionary->FindIntKey("x"); - if (!x) { + const auto x_parse = dictionary->FindIntKey("x"); + if (!x_parse) { BLOG(0, "X is wrong"); - return; + return ledger::Result::LEDGER_ERROR; } - const auto y = dictionary->FindIntKey("y"); - if (!y) { + const auto y_parse = dictionary->FindIntKey("y"); + if (!y_parse) { BLOG(0, "Y is wrong"); - return; + return ledger::Result::LEDGER_ERROR; } - result->SetIntKey("x", *x); - result->SetIntKey("y", *y); - result->SetStringKey("captchaId", *captcha_id); + *x = *x_parse; + *y = *y_parse; + *captcha_id = *id; + return ledger::Result::LEDGER_OK; } void AttestationDesktop::Start( const std::string& payload, StartCallback callback) { - auto url_callback = std::bind(&AttestationDesktop::OnStart, + auto url_callback = std::bind(&AttestationDesktop::DownloadCaptchaImage, this, _1, + _2, + _3, callback); - const std::string url = - braveledger_request_util::GetStartAttestationDesktopUrl(); - - base::Value body(base::Value::Type::DICTIONARY); - body.SetStringKey( - "paymentId", - ledger_->state()->GetPaymentId()); - - std::string json; - base::JSONWriter::Write(body, &json); - - ledger_->LoadURL( - url, - {}, - json, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - url_callback); -} - -void AttestationDesktop::OnStart( - const ledger::UrlResponse& response, - StartCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - DownloadCaptchaImage(response, callback); + promotion_server_->post_captcha()->Request(url_callback); } void AttestationDesktop::DownloadCaptchaImage( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& hint, + const std::string& captcha_id, StartCallback callback) { - base::Value dictionary(base::Value::Type::DICTIONARY); - const ledger::Result result = - braveledger_response_util::ParseCaptcha(response, &dictionary); - if (result != ledger::Result::LEDGER_OK) { callback(ledger::Result::LEDGER_ERROR, ""); return; } - if (dictionary.DictEmpty()) { - BLOG(0, "Captcha response is empty"); - callback(ledger::Result::LEDGER_ERROR, ""); - return; - } - - const auto* id = dictionary.FindStringKey("captchaId"); - if (!id) { - BLOG(0, "Captcha id is wrong"); - callback(ledger::Result::LEDGER_ERROR, ""); - return; - } - - const std::string url = braveledger_request_util::GetCaptchaUrl(*id); auto url_callback = std::bind(&AttestationDesktop::OnDownloadCaptchaImage, this, _1, - response, + _2, + hint, + captcha_id, callback); - ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, url_callback); + promotion_server_->get_captcha()->Request(captcha_id, url_callback); } void AttestationDesktop::OnDownloadCaptchaImage( - const ledger::UrlResponse& response, - const ledger::UrlResponse& captcha_response, + const ledger::Result result, + const std::string& image, + const std::string& hint, + const std::string& captcha_id, StartCallback callback) { - BLOG(7, ledger::UrlResponseToString(__func__, response)); - - base::Value dictionary(base::Value::Type::DICTIONARY); - const ledger::Result result = braveledger_response_util::ParseCaptcha( - captcha_response, - &dictionary); - if (result != ledger::Result::LEDGER_OK) { callback(ledger::Result::LEDGER_ERROR, ""); return; } - if (dictionary.DictEmpty()) { - BLOG(0, "Captcha response is empty"); - callback(ledger::Result::LEDGER_ERROR, ""); - return; - } - - std::string encoded_image; - braveledger_response_util::ParseCaptchaImage(response, &encoded_image); - dictionary.SetStringKey("captchaImage", encoded_image); + base::Value dictionary(base::Value::Type::DICTIONARY); + dictionary.SetStringKey("hint", hint); + dictionary.SetStringKey("captchaId", captcha_id); + dictionary.SetStringKey("captchaImage", image); std::string json; base::JSONWriter::Write(dictionary, &json); @@ -167,53 +123,33 @@ void AttestationDesktop::OnDownloadCaptchaImage( void AttestationDesktop::Confirm( const std::string& solution, ConfirmCallback callback) { - base::Value parsed_solution(base::Value::Type::DICTIONARY); - ParseClaimSolution(solution, &parsed_solution); - - if (parsed_solution.DictSize() != 3) { - BLOG(0, "Solution is wrong: " << solution); - callback(ledger::Result::LEDGER_ERROR); - return; - } + int x; + int y; + std::string captcha_id; + const ledger::Result result = + ParseClaimSolution(solution, &x, &y, &captcha_id); - base::Value dictionary(base::Value::Type::DICTIONARY); - base::Value solution_dict(base::Value::Type::DICTIONARY); - solution_dict.SetIntKey("x", *parsed_solution.FindIntKey("x")); - solution_dict.SetIntKey("y", *parsed_solution.FindIntKey("y")); - dictionary.SetKey("solution", std::move(solution_dict)); - std::string payload; - base::JSONWriter::Write(dictionary, &payload); - - const auto* id = parsed_solution.FindStringKey("captchaId"); - if (!id) { - BLOG(0, "Captcha id is wrong"); - callback(ledger::Result::LEDGER_ERROR); + if (result != ledger::Result::LEDGER_OK) { + BLOG(0, "Failed to parse solution"); + callback(result); return; } - const std::string url = - braveledger_request_util::GetClaimAttestationDesktopUrl(*id); auto url_callback = std::bind(&AttestationDesktop::OnConfirm, this, _1, callback); - ledger_->LoadURL( - url, - {}, - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::PUT, + promotion_server_->put_captcha()->Request( + x, + y, + captcha_id, url_callback); } void AttestationDesktop::OnConfirm( - const ledger::UrlResponse& response, + const ledger::Result result, ConfirmCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckConfirmAttestation(response); if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Failed to confirm attestation"); callback(result); @@ -223,4 +159,5 @@ void AttestationDesktop::OnConfirm( callback(ledger::Result::LEDGER_OK); } -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.h b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.h index ada905c0054c..7ea9b137ff1d 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_desktop.h @@ -6,17 +6,19 @@ #ifndef BRAVELEDGER_ATTESTATION_ATTESTATION_DESKTOP_H_ #define BRAVELEDGER_ATTESTATION_ATTESTATION_DESKTOP_H_ -#include +#include #include #include "base/values.h" #include "bat/ledger/internal/attestation/attestation.h" +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_attestation { +namespace ledger { +namespace attestation { class AttestationDesktop : public Attestation { public: @@ -30,27 +32,32 @@ class AttestationDesktop : public Attestation { ConfirmCallback callback) override; private: - void ParseClaimSolution( + ledger::Result ParseClaimSolution( const std::string& response, - base::Value* result); - - void OnStart( - const ledger::UrlResponse& response, - StartCallback callback); + int* x, + int* y, + std::string* captcha_id); void DownloadCaptchaImage( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& hint, + const std::string& captcha_id, StartCallback callback); void OnDownloadCaptchaImage( - const ledger::UrlResponse& response, - const ledger::UrlResponse& captcha_response, + const ledger::Result result, + const std::string& image, + const std::string& hint, + const std::string& captcha_id, StartCallback callback); void OnConfirm( - const ledger::UrlResponse& response, + const ledger::Result result, ConfirmCallback callback); + + std::unique_ptr promotion_server_; }; -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger #endif // BRAVELEDGER_ATTESTATION_ATTESTATION_DESKTOP_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.cc index 4cdf41477261..e3cb79289300 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.cc @@ -13,7 +13,8 @@ #include "bat/ledger/internal/attestation/attestation_iosx.h" #include "net/http/http_status_code.h" -namespace braveledger_attestation { +namespace ledger { +namespace attestation { AttestationImpl::AttestationImpl(bat_ledger::LedgerImpl* ledger) : Attestation(ledger) { @@ -40,4 +41,5 @@ void AttestationImpl::Confirm( platform_instance_->Confirm(solution, callback); } -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.h b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.h index 641f4546c6a2..933da492fbd4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_impl.h @@ -15,7 +15,8 @@ namespace bat_ledger { class LedgerImpl; } -namespace braveledger_attestation { +namespace ledger { +namespace attestation { class AttestationDesktop; class AttestationAndroid; @@ -36,5 +37,6 @@ class AttestationImpl : public Attestation { std::unique_ptr platform_instance_; }; -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger #endif // BRAVELEDGER_ATTESTATION_ATTESTATION_IMPL_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc index 840a2682793f..cbbfe82ed856 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.cc @@ -10,17 +10,17 @@ #include "base/json/json_writer.h" #include "bat/ledger/internal/attestation/attestation_iosx.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_attestation.h" -#include "bat/ledger/internal/response/response_attestation.h" using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; -namespace braveledger_attestation { +namespace ledger { +namespace attestation { AttestationIOS::AttestationIOS(bat_ledger::LedgerImpl* ledger) : - Attestation(ledger) { + Attestation(ledger), + promotion_server_(new endpoint::PromotionServer(ledger)) { } AttestationIOS::~AttestationIOS() = default; @@ -46,40 +46,43 @@ std::string AttestationIOS::ParseStartPayload( return *key; } -void AttestationIOS::ParseClaimSolution( +ledger::Result AttestationIOS::ParseClaimSolution( const std::string& response, - base::Value* result) { + std::string* nonce, + std::string* blob, + std::string* signature) { base::Optional value = base::JSONReader::Read(response); if (!value || !value->is_dict()) { - return; + return ledger::Result::LEDGER_ERROR; } base::DictionaryValue* dictionary = nullptr; if (!value->GetAsDictionary(&dictionary)) { - return; + return ledger::Result::LEDGER_ERROR; } - const auto* nonce = dictionary->FindStringKey("nonce"); - if (!nonce) { + const auto* nonce_parsed = dictionary->FindStringKey("nonce"); + if (!nonce_parsed) { BLOG(0, "Nonce is wrong"); - return; + return ledger::Result::LEDGER_ERROR; } - const auto* blob = dictionary->FindStringKey("blob"); - if (!blob) { + const auto* blob_parsed = dictionary->FindStringKey("blob"); + if (!blob_parsed) { BLOG(0, "Blob is wrong"); - return; + return ledger::Result::LEDGER_ERROR; } - const auto* signature = dictionary->FindStringKey("signature"); - if (!signature) { + const auto* signature_parsed = dictionary->FindStringKey("signature"); + if (!signature_parsed) { BLOG(0, "Signature is wrong"); - return; + return ledger::Result::LEDGER_ERROR; } - result->SetStringKey("nonce", *nonce); - result->SetStringKey("blob", *blob); - result->SetStringKey("signature", *signature); + *nonce = *nonce_parsed; + *blob = *blob_parsed; + *signature = *signature_parsed; + return ledger::Result::LEDGER_OK; } void AttestationIOS::Start( @@ -93,90 +96,58 @@ void AttestationIOS::Start( callback(ledger::Result::LEDGER_ERROR, ""); return; } - - base::Value dictionary(base::Value::Type::DICTIONARY); - dictionary.SetStringKey("publicKeyHash", key); - dictionary.SetStringKey("paymentId", payment_id); - std::string json; - base::JSONWriter::Write(dictionary, &json); - auto url_callback = std::bind(&AttestationIOS::OnStart, this, _1, + _2, callback); - const std::string url = braveledger_request_util::GetStartAttestationIOSUrl(); - - ledger_->LoadURL( - url, - {}, - json, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - url_callback); + promotion_server_->post_devicecheck()->Request(key, url_callback); } void AttestationIOS::OnStart( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& nonce, StartCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckStartAttestation(response); if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Failed to start attestation"); callback(ledger::Result::LEDGER_ERROR, ""); return; } - callback(ledger::Result::LEDGER_OK, response.body); + callback(ledger::Result::LEDGER_OK, nonce); } void AttestationIOS::Confirm( const std::string& solution, ConfirmCallback callback) { - base::Value parsed_solution(base::Value::Type::DICTIONARY); - ParseClaimSolution(solution, &parsed_solution); + std::string nonce; + std::string blob; + std::string signature; + const ledger::Result result = + ParseClaimSolution(solution, &nonce, &blob, &signature); - if (parsed_solution.DictSize() != 3) { - BLOG(0, "Solution is wrong: " << solution); + if (result != ledger::Result::LEDGER_OK) { + BLOG(0, "Failed to parse solution"); callback(ledger::Result::LEDGER_ERROR); return; } - base::Value dictionary(base::Value::Type::DICTIONARY); - dictionary.SetStringKey("attestationBlob", - *parsed_solution.FindStringKey("blob")); - dictionary.SetStringKey("signature", - *parsed_solution.FindStringKey("signature")); - std::string payload; - base::JSONWriter::Write(dictionary, &payload); - - const std::string nonce = *parsed_solution.FindStringKey("nonce"); - const std::string url = - braveledger_request_util::GetConfirmAttestationIOSUrl(nonce); - auto url_callback = std::bind(&AttestationIOS::OnConfirm, this, _1, callback); - ledger_->LoadURL( - url, - {}, - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::PUT, + promotion_server_->put_devicecheck()->Request( + blob, + signature, + nonce, url_callback); } void AttestationIOS::OnConfirm( - const ledger::UrlResponse& response, + const ledger::Result result, ConfirmCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckConfirmAttestation(response); if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Failed to confirm attestation"); callback(ledger::Result::LEDGER_ERROR); @@ -186,4 +157,5 @@ void AttestationIOS::OnConfirm( callback(ledger::Result::LEDGER_OK); } -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.h b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.h index 4c3a05cd219a..686692a02315 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/attestation/attestation_iosx.h @@ -6,17 +6,19 @@ #ifndef BRAVELEDGER_ATTESTATION_ATTESTATION_IOS_H_ #define BRAVELEDGER_ATTESTATION_ATTESTATION_IOS_H_ -#include +#include #include #include "base/values.h" #include "bat/ledger/internal/attestation/attestation.h" +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_attestation { +namespace ledger { +namespace attestation { class AttestationIOS : public Attestation { public: @@ -33,18 +35,24 @@ class AttestationIOS : public Attestation { std::string ParseStartPayload( const std::string& response); - void ParseClaimSolution( + ledger::Result ParseClaimSolution( const std::string& response, - base::Value* result); + std::string* nonce, + std::string* blob, + std::string* signature); void OnStart( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& nonce, StartCallback callback); void OnConfirm( - const ledger::UrlResponse& response, + const ledger::Result result, ConfirmCallback callback); + + std::unique_ptr promotion_server_; }; -} // namespace braveledger_attestation +} // namespace attestation +} // namespace ledger #endif // BRAVELEDGER_ATTESTATION_ATTESTATION_IOS_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 6743888d7bb9..3bbf701f3df0 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 @@ -324,7 +324,7 @@ void Contribution::CreateNewEntry( } const double wallet_balance = - braveledger_wallet::WalletBalance::GetPerWalletBalance( + ledger::wallet::WalletBalance::GetPerWalletBalance( wallet_type, balance->wallets); if (wallet_balance == 0) { 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 825922358408..a05270a16862 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 @@ -13,7 +13,6 @@ #include "bat/ledger/internal/contribution/contribution_unblinded.h" #include "bat/ledger/internal/contribution/contribution_util.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_promotion.h" #include "brave_base/random.h" using std::placeholders::_1; 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 fc0ccafa3531..d925de35d471 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 @@ -12,9 +12,6 @@ #include "bat/ledger/internal/credentials/credentials_promotion.h" #include "bat/ledger/internal/credentials/credentials_util.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_promotion.h" -#include "bat/ledger/internal/request/request_util.h" -#include "bat/ledger/internal/response/response_promotion.h" using std::placeholders::_1; using std::placeholders::_2; @@ -24,7 +21,9 @@ namespace braveledger_credentials { CredentialsPromotion::CredentialsPromotion(bat_ledger::LedgerImpl* ledger) : ledger_(ledger), - common_(std::make_unique(ledger)) { + common_(std::make_unique(ledger)), + promotion_server_( + std::make_unique(ledger)) { DCHECK(ledger_ && common_); } @@ -163,46 +162,24 @@ void CredentialsPromotion::Claim( return; } - const std::string payment_id = ledger_->state()->GetPaymentId(); - base::Value body(base::Value::Type::DICTIONARY); - body.SetStringKey("paymentId", payment_id); - body.SetKey("blindedCreds", base::Value(std::move(*blinded_creds))); - - std::string json; - base::JSONWriter::Write(body, &json); - - const auto headers = braveledger_request_util::BuildSignHeaders( - "post /v1/promotions/" + trigger.id, - json, - payment_id, - ledger_->state()->GetRecoverySeed()); - - const std::string url = braveledger_request_util::ClaimCredsUrl(trigger.id); auto url_callback = std::bind(&CredentialsPromotion::OnClaim, this, _1, + _2, trigger, callback); - ledger_->LoadURL( - url, - headers, - json, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, + promotion_server_->post_creds()->Request( + trigger.id, + std::move(blinded_creds), url_callback); } void CredentialsPromotion::OnClaim( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& claim_id, const CredentialsTrigger& trigger, ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - std::string claim_id; - const ledger::Result result = - braveledger_response_util::ParseClaimCreds(response, &claim_id); - if (result != ledger::Result::LEDGER_OK) { callback(result); return; @@ -300,44 +277,54 @@ void CredentialsPromotion::FetchSignedCreds( return; } - const std::string url = braveledger_request_util::FetchSignedCredsUrl( - trigger.id, - promotion->claim_id); auto url_callback = std::bind(&CredentialsPromotion::OnFetchSignedCreds, this, _1, + _2, trigger, callback); - ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, url_callback); + promotion_server_->get_signed_creds()->Request( + trigger.id, + promotion->claim_id, + url_callback); } void CredentialsPromotion::OnFetchSignedCreds( - const ledger::UrlResponse& response, + const ledger::Result result, + ledger::CredsBatchPtr batch, const CredentialsTrigger& trigger, ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); + // Note: Translate ledger::Result::RETRY_SHORT into + // ledger::Result::RETRY, as promotion only supports the standard + // retry + if (result == ledger::Result::RETRY_SHORT) { + callback(ledger::Result::RETRY); + return; + } - auto get_callback = std::bind(&CredentialsPromotion::SignedCredsSaved, + if (result != ledger::Result::LEDGER_OK || !batch) { + BLOG(0, "Problem parsing response"); + callback(ledger::Result::LEDGER_ERROR); + return; + } + + batch->trigger_id = trigger.id; + batch->trigger_type = trigger.type; + + auto save_callback = std::bind(&CredentialsPromotion::SignedCredsSaved, this, _1, trigger, callback); - common_->GetSignedCredsFromResponse(trigger, response, get_callback); + + ledger_->database()->SaveSignedCreds(std::move(batch), save_callback); } void CredentialsPromotion::SignedCredsSaved( const ledger::Result result, const CredentialsTrigger& trigger, ledger::ResultCallback callback) { - // Note: Translate ledger::Result::RETRY_SHORT into - // ledger::Result::RETRY, as promotion only supports the standard - // retry - if (result == ledger::Result::RETRY_SHORT) { - callback(ledger::Result::RETRY); - return; - } - if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Signed creds were not saved"); callback(ledger::Result::LEDGER_ERROR); @@ -479,19 +466,8 @@ void CredentialsPromotion::RedeemTokens( redeem, callback); - std::string payload; - std::string url; - std::vector headers; if (redeem.type == ledger::RewardsType::TRANSFER) { - payload = GenerateTransferTokensPayload( - redeem, - ledger_->state()->GetPaymentId()); - url = braveledger_request_util::GetTransferTokens(); - headers = braveledger_request_util::BuildSignHeaders( - "post /v1/suggestions/claim", - payload, - ledger_->state()->GetPaymentId(), - ledger_->state()->GetRecoverySeed()); + promotion_server_->post_suggestions_claim()->Request(redeem, url_callback); } else { if (redeem.publisher_key.empty()) { BLOG(0, "Publisher key is empty"); @@ -499,28 +475,15 @@ void CredentialsPromotion::RedeemTokens( return; } - payload = GenerateRedeemTokensPayload(redeem); - url = braveledger_request_util::GetRedeemTokensUrl(); + promotion_server_->post_suggestions()->Request(redeem, url_callback); } - - ledger_->LoadURL( - url, - headers, - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - url_callback); } void CredentialsPromotion::OnRedeemTokens( - const ledger::UrlResponse& response, + const ledger::Result result, const std::vector& token_id_list, const CredentialsRedeem& redeem, ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckRedeemTokens(response); if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Failed to parse redeem tokens response"); callback(ledger::Result::LEDGER_ERROR); 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 52fb25de6272..0fb1f2cfcbb3 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 @@ -12,6 +12,7 @@ #include #include "bat/ledger/internal/credentials/credentials_common.h" +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" namespace braveledger_credentials { @@ -49,7 +50,8 @@ class CredentialsPromotion : public Credentials { ledger::ResultCallback callback) override; void OnClaim( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& claim_id, const CredentialsTrigger& trigger, ledger::ResultCallback callback); @@ -73,7 +75,8 @@ class CredentialsPromotion : public Credentials { ledger::ResultCallback callback); void OnFetchSignedCreds( - const ledger::UrlResponse& response, + const ledger::Result result, + ledger::CredsBatchPtr batch, const CredentialsTrigger& trigger, ledger::ResultCallback callback); @@ -106,13 +109,14 @@ class CredentialsPromotion : public Credentials { ledger::ResultCallback callback) override; void OnRedeemTokens( - const ledger::UrlResponse& response, + const ledger::Result result, const std::vector& token_id_list, const CredentialsRedeem& redeem, ledger::ResultCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED std::unique_ptr common_; + std::unique_ptr promotion_server_; }; } // namespace braveledger_credentials 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 658752902fc7..522ba554d664 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 @@ -304,19 +304,4 @@ std::string GenerateRedeemTokensPayload(const CredentialsRedeem& redeem) { 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 5bd01867e34d..a0fb9410cc70 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 @@ -62,10 +62,6 @@ namespace braveledger_credentials { std::string GenerateRedeemTokensPayload(const CredentialsRedeem& redeem); - std::string GenerateTransferTokensPayload( - const CredentialsRedeem& redeem, - const std::string& payment_id); - } // namespace braveledger_credentials #endif // BRAVELEDGER_CREDENTIALS_CREDENTIALS_UTIL_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_server.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_server.cc index 59eb6c3b4f36..2e79536f3cd6 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_server.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_server.cc @@ -2,9 +2,9 @@ * 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/endpoint/api/api_server.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/endpoint/api/api_server.h" namespace ledger { namespace endpoint { diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_util.cc index 9f3c3ce16a0c..474f49466b3f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/api_util.cc @@ -2,8 +2,8 @@ * 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/endpoint/api/api_util.h" + #include "bat/ledger/ledger.h" namespace ledger { diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters.cc index c01458991454..1e8549ace02b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters.cc @@ -2,12 +2,12 @@ * 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/endpoint/api/get_parameters/get_parameters.h" #include "base/json/json_reader.h" #include "base/strings/stringprintf.h" -#include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/endpoint/api/api_util.h" -#include "bat/ledger/internal/endpoint/api/get_parameters/get_parameters.h" +#include "bat/ledger/internal/ledger_impl.h" #include "net/http/http_status_code.h" using std::placeholders::_1; @@ -15,7 +15,7 @@ using std::placeholders::_1; // GET /v1/parameters // GET /v1/parameters?currency={currency} // -// Success: +// Success code: // HTTP_OK (200) // // Error codes: diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters_unittest.cc index 08b8f9950435..fade7b95d0ae 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/api/get_parameters/get_parameters_unittest.cc @@ -83,21 +83,14 @@ TEST_F(GetParametersTest, ServerOK) { parameters_->Request([]( const ledger::Result result, const ledger::RewardsParameters& parameters) { + ledger::RewardsParameters expected_parameters; + expected_parameters.rate = 0.2476573499489187; + expected_parameters.auto_contribute_choice = 20; + expected_parameters.auto_contribute_choices = {5, 10, 15}; + expected_parameters.tip_choices = {1, 10, 100}; + expected_parameters.monthly_tip_choices = {5, 10, 15}; EXPECT_EQ(result, ledger::Result::LEDGER_OK); - EXPECT_EQ(parameters.rate, 0.2476573499489187); - EXPECT_EQ(parameters.auto_contribute_choice, 20); - EXPECT_EQ(parameters.auto_contribute_choices.size(), 3ul); - EXPECT_EQ(parameters.auto_contribute_choices[0], 5); - EXPECT_EQ(parameters.auto_contribute_choices[1], 10); - EXPECT_EQ(parameters.auto_contribute_choices[2], 15); - EXPECT_EQ(parameters.tip_choices.size(), 3ul); - EXPECT_EQ(parameters.tip_choices[0], 1); - EXPECT_EQ(parameters.tip_choices[1], 10); - EXPECT_EQ(parameters.tip_choices[2], 100); - EXPECT_EQ(parameters.monthly_tip_choices.size(), 3ul); - EXPECT_EQ(parameters.monthly_tip_choices[0], 5); - EXPECT_EQ(parameters.monthly_tip_choices[1], 10); - EXPECT_EQ(parameters.monthly_tip_choices[2], 15); + EXPECT_TRUE(expected_parameters.Equals(parameters)); }); } @@ -219,12 +212,11 @@ TEST_F(GetParametersTest, WrongListValues) { parameters_->Request([]( const ledger::Result result, const ledger::RewardsParameters& parameters) { + ledger::RewardsParameters expected_parameters; EXPECT_EQ(result, ledger::Result::LEDGER_OK); - EXPECT_EQ(parameters.rate, 0.2476573499489187); - EXPECT_EQ(parameters.auto_contribute_choice, 20); - EXPECT_TRUE(parameters.auto_contribute_choices.empty()); - EXPECT_TRUE(parameters.tip_choices.empty()); - EXPECT_TRUE(parameters.monthly_tip_choices.empty()); + expected_parameters.rate = 0.2476573499489187; + expected_parameters.auto_contribute_choice = 20; + EXPECT_TRUE(expected_parameters.Equals(parameters)); }); } @@ -270,18 +262,14 @@ TEST_F(GetParametersTest, DoubleListValues) { parameters_->Request([]( const ledger::Result result, const ledger::RewardsParameters& parameters) { + ledger::RewardsParameters expected_parameters; + expected_parameters.rate = 0.2476573499489187; + expected_parameters.auto_contribute_choice = 20; + expected_parameters.auto_contribute_choices = {5, 10.5, 15}; + expected_parameters.tip_choices = {1, 10.5, 100}; + expected_parameters.monthly_tip_choices = {5, 10.5, 15}; EXPECT_EQ(result, ledger::Result::LEDGER_OK); - EXPECT_EQ(parameters.rate, 0.2476573499489187); - EXPECT_EQ(parameters.auto_contribute_choice, 20); - EXPECT_EQ(parameters.auto_contribute_choices[0], 5); - EXPECT_EQ(parameters.auto_contribute_choices[1], 10.5); - EXPECT_EQ(parameters.auto_contribute_choices[2], 15); - EXPECT_EQ(parameters.tip_choices[0], 1); - EXPECT_EQ(parameters.tip_choices[1], 10.5); - EXPECT_EQ(parameters.tip_choices[2], 100); - EXPECT_EQ(parameters.monthly_tip_choices[0], 5); - EXPECT_EQ(parameters.monthly_tip_choices[1], 10.5); - EXPECT_EQ(parameters.monthly_tip_choices[2], 15); + EXPECT_TRUE(expected_parameters.Equals(parameters)); }); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_promotion.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available.cc similarity index 55% rename from vendor/bat-native-ledger/src/bat/ledger/internal/response/response_promotion.cc rename to vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available.cc index d51c7a39454c..c818870f8d5c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_promotion.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available.cc @@ -2,100 +2,32 @@ * 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/response/response_promotion.h" +#include "bat/ledger/internal/endpoint/promotion/get_available/get_available.h" #include #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/strings/string_number_conversions.h" -#include "bat/ledger/internal/logging.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/promotion/promotion_util.h" #include "net/http/http_status_code.h" -namespace braveledger_response_util { - -// Request Url: -// POST /v1/promotions/{promotion_id} -// -// Success: -// OK (200) -// -// Response Format: -// { -// "claimId": "53714048-9675-419e-baa3-369d85a2facb" -// } - -ledger::Result ParseClaimCreds( - const ledger::UrlResponse& response, - std::string* claim_id) { - DCHECK(claim_id); - - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } - - // Forbidden (403) - if (response.status_code == net::HTTP_FORBIDDEN) { - BLOG(0, "Signature validation failed"); - return ledger::Result::LEDGER_ERROR; - } - - // Conflict (409) - if (response.status_code == net::HTTP_CONFLICT) { - BLOG(0, "Incorrect blinded credentials"); - return ledger::Result::LEDGER_ERROR; - } - - // Gone (410) - if (response.status_code == net::HTTP_GONE) { - BLOG(0, "Promotion is gone"); - return ledger::Result::NOT_FOUND; - } - - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - base::Optional value = base::JSONReader::Read(response.body); - if (!value || !value->is_dict()) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - auto* id = dictionary->FindStringKey("claimId"); - if (!id || id->empty()) { - BLOG(0, "Claim id is missing"); - return ledger::Result::LEDGER_ERROR; - } - - *claim_id = *id; - - return ledger::Result::LEDGER_OK; -} +using std::placeholders::_1; -// Request Url: // GET /v1/promotions?migrate=true&paymentId={payment_id}&platform={platform} // -// Success: -// OK (200) +// Success code: +// HTTP_OK (200) // -// Response Format: +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_NOT_FOUND (404) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body: // { // "promotions": [ // { @@ -116,39 +48,61 @@ ledger::Result ParseClaimCreds( // ] // } -ledger::Result CheckFetchPromotions(const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { +namespace ledger { +namespace endpoint { +namespace promotion { + +GetAvailable::GetAvailable(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +GetAvailable::~GetAvailable() = default; + +std::string GetAvailable::GetUrl(const std::string& platform) { + const std::string payment_id = ledger_->state()->GetPaymentId(); + const std::string& arguments = base::StringPrintf( + "migrate=true&paymentId=%s&platform=%s", + payment_id.c_str(), + platform.c_str()); + + const std::string& path = base::StringPrintf( + "/v1/promotions?%s", + arguments.c_str()); + + return GetServerUrl(path); +} + +ledger::Result GetAvailable::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { BLOG(0, "Invalid paymentId or platform in request"); return ledger::Result::LEDGER_ERROR; } - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { + if (status_code == net::HTTP_NOT_FOUND) { BLOG(0, "Unrecognized paymentId/promotion combination"); return ledger::Result::NOT_FOUND; } - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { BLOG(0, "Internal server error"); return ledger::Result::LEDGER_ERROR; } - if (response.status_code != net::HTTP_OK) { + if (status_code != net::HTTP_OK) { return ledger::Result::LEDGER_ERROR; } return ledger::Result::LEDGER_OK; } -ledger::Result ParseFetchPromotions( - const ledger::UrlResponse& response, +ledger::Result GetAvailable::ParseBody( + const std::string& body, ledger::PromotionList* list, std::vector* corrupted_promotions) { DCHECK(list && corrupted_promotions); - base::Optional value = base::JSONReader::Read(response.body); + base::Optional value = base::JSONReader::Read(body); if (!value || !value->is_dict()) { BLOG(0, "Invalid JSON"); return ledger::Result::LEDGER_ERROR; @@ -256,62 +210,40 @@ ledger::Result ParseFetchPromotions( return ledger::Result::LEDGER_OK; } -// Request Url: -// POST /v1/promotions/reportclobberedclaims -// -// Success: -// OK (200) -// -// Response Format: -// {Empty body} - -ledger::Result CheckCorruptedPromotions(const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } - - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - return ledger::Result::LEDGER_OK; +void GetAvailable::Request( + const std::string& platform, + GetAvailableCallback callback) { + auto url_callback = std::bind(&GetAvailable::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(platform), + {}, + "", + "", + ledger::UrlMethod::GET, + url_callback); } -// Request Url: -// POST /v1/suggestions -// -// Success: -// OK (200) -// -// Response Format: -// {Empty body} - -ledger::Result CheckRedeemTokens(const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } +void GetAvailable::OnRequest( + const ledger::UrlResponse& response, + GetAvailableCallback callback) { + ledger::LogUrlResponse(__func__, response); - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; - } + ledger::PromotionList list; + std::vector corrupted_promotions; + ledger::Result result = CheckStatusCode(response.status_code); - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; + if (result != ledger::Result::LEDGER_OK) { + callback(result, std::move(list), corrupted_promotions); + return; } - return ledger::Result::LEDGER_OK; + result = ParseBody(response.body, &list, &corrupted_promotions); + callback(result, std::move(list), corrupted_promotions); } -} // namespace braveledger_response_util +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available.h new file mode 100644 index 000000000000..88de45ace0a0 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available.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_ENDPOINT_PROMOTION_GET_AVAILABLE_GET_AVAILABLE_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_GET_AVAILABLE_GET_AVAILABLE_H_ + +#include +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using GetAvailableCallback = std::function& corrupted_promotions)>; + +class GetAvailable { + public: + explicit GetAvailable(bat_ledger::LedgerImpl* ledger); + ~GetAvailable(); + + void Request( + const std::string& platform, + GetAvailableCallback callback); + + private: + std::string GetUrl(const std::string& platform); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + ledger::PromotionList* list, + std::vector* corrupted_promotions); + + void OnRequest( + const ledger::UrlResponse& response, + GetAvailableCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_GET_AVAILABLE_GET_AVAILABLE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available_unittest.cc new file mode 100644 index 000000000000..26540ad61270 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_available/get_available_unittest.cc @@ -0,0 +1,256 @@ +/* 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/endpoint/promotion/get_available/get_available.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=GetAvailableTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class GetAvailableTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr available_; + + GetAvailableTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + available_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(GetAvailableTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "promotions": [ + { + "id": "83b3b77b-e7c3-455b-adda-e476fa0656d2", + "createdAt": "2020-06-08T15:04:45.352584Z", + "expiresAt": "2020-10-08T15:04:45.352584Z", + "version": 5, + "suggestionsPerGrant": 120, + "approximateValue": "30", + "type": "ugp", + "available": true, + "platform": "desktop", + "publicKeys": [ + "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I=" + ], + "legacyClaimed": false + } + ] + })"; + callback(response); + })); + + available_->Request( + "macos", + []( + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions) { + ledger::Promotion expected_promotion; + expected_promotion.id = "83b3b77b-e7c3-455b-adda-e476fa0656d2"; + expected_promotion.expires_at = 1602169485; + expected_promotion.version = 5; + expected_promotion.suggestions = 120; + expected_promotion.approximate_value = 30.0; + expected_promotion.type = ledger::PromotionType::UGP; + expected_promotion.public_keys = + "[\"dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I=\"]"; + expected_promotion.legacy_claimed = false; + + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_TRUE(corrupted_promotions.empty()); + EXPECT_EQ(list.size(), 1ul); + EXPECT_TRUE(expected_promotion.Equals(*list[0])); + }); +} + +TEST_F(GetAvailableTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + available_->Request( + "macos", + []( + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(list.empty()); + EXPECT_TRUE(corrupted_promotions.empty()); + }); +} + +TEST_F(GetAvailableTest, ServerError404) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 404; + response.url = url; + response.body = ""; + callback(response); + })); + + available_->Request( + "macos", + []( + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions) { + EXPECT_EQ(result, ledger::Result::NOT_FOUND); + EXPECT_TRUE(list.empty()); + EXPECT_TRUE(corrupted_promotions.empty()); + }); +} + +TEST_F(GetAvailableTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + available_->Request( + "macos", + []( + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(list.empty()); + EXPECT_TRUE(corrupted_promotions.empty()); + }); +} + +TEST_F(GetAvailableTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + available_->Request( + "macos", + []( + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(list.empty()); + EXPECT_TRUE(corrupted_promotions.empty()); + }); +} + +TEST_F(GetAvailableTest, ServerWrongResponse) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "promotions": [ + { + "foo": 0 + } + ] + })"; + callback(response); + })); + + available_->Request( + "macos", + []( + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions) { + EXPECT_EQ(result, ledger::Result::CORRUPTED_DATA); + EXPECT_TRUE(list.empty()); + EXPECT_TRUE(corrupted_promotions.empty()); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.cc new file mode 100644 index 000000000000..9b95e73cba15 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.cc @@ -0,0 +1,120 @@ +/* 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/endpoint/promotion/get_captcha/get_captcha.h" + +#include + +#include "base/base64.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// GET /v1/captchas/{captcha_id}.png +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_NOT_FOUND (404) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body: +// {PNG data} + +namespace ledger { +namespace endpoint { +namespace promotion { + +GetCaptcha::GetCaptcha(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +GetCaptcha::~GetCaptcha() = default; + +std::string GetCaptcha::GetUrl(const std::string& captcha_id) { + const std::string path = base::StringPrintf( + "/v1/captchas/%s.png", + captcha_id.c_str()); + + return GetServerUrl(path); +} + +ledger::Result GetCaptcha::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid captcha id"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_NOT_FOUND) { + BLOG(0, "Unrecognized captcha id"); + return ledger::Result::NOT_FOUND; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Failed to generate the captcha image"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result GetCaptcha::ParseBody( + const std::string& body, + std::string* image) { + DCHECK(image); + + std::string encoded_image; + base::Base64Encode(body, &encoded_image); + *image = + base::StringPrintf("data:image/jpeg;base64,%s", encoded_image.c_str()); + + return ledger::Result::LEDGER_OK; +} + +void GetCaptcha::Request( + const std::string& captcha_id, + GetCaptchaCallback callback) { + auto url_callback = std::bind(&GetCaptcha::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(captcha_id), + {}, + "", + "", + ledger::UrlMethod::GET, + url_callback); +} + +void GetCaptcha::OnRequest( + const ledger::UrlResponse& response, + GetCaptchaCallback callback) { + ledger::LogUrlResponse(__func__, response, true); + + std::string image; + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, image); + return; + } + + result = ParseBody(response.body, &image); + callback(result, image); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.h new file mode 100644 index 000000000000..fba3c9fbb5ac --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.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_ENDPOINT_PROMOTION_GET_CAPTCHA_GET_CAPTCHA_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_GET_CAPTCHA_GET_CAPTCHA_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using GetCaptchaCallback = std::function; + +class GetCaptcha { + public: + explicit GetCaptcha(bat_ledger::LedgerImpl* ledger); + ~GetCaptcha(); + + void Request( + const std::string& captcha_id, + GetCaptchaCallback callback); + + private: + std::string GetUrl(const std::string& captcha_id); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* image); + + void OnRequest( + const ledger::UrlResponse& response, + GetCaptchaCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_GET_CAPTCHA_GET_CAPTCHA_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha_unittest.cc new file mode 100644 index 000000000000..e0190940ff6f --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha_unittest.cc @@ -0,0 +1,174 @@ +/* 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/endpoint/promotion/get_captcha/get_captcha.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=GetCaptchaTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class GetCaptchaTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr captcha_; + + GetCaptchaTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + captcha_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(GetCaptchaTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = + R"(aWphaXNqZGZvaWFzamZvc2FpamZvc2lhZGpmb2lkc2pmbw==)"; + callback(response); + })); + + captcha_->Request( + "d155d2d2-2627-425b-9be8-44ae9f541762", + [](const ledger::Result result, const std::string& image) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_EQ( + image, + "data:image/jpeg;base64,YVdwaGFYTnFaR1p2YVdGemFtWnZjMkZwYW" + "1admMybGhaR3BtYjJsa2MycG1idz09"); + }); +} + +TEST_F(GetCaptchaTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + "d155d2d2-2627-425b-9be8-44ae9f541762", + [](const ledger::Result result, const std::string& image) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(GetCaptchaTest, ServerError404) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 404; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + "d155d2d2-2627-425b-9be8-44ae9f541762", + [](const ledger::Result result, const std::string& image) { + EXPECT_EQ(result, ledger::Result::NOT_FOUND); + EXPECT_EQ(image, ""); + }); +} + +TEST_F(GetCaptchaTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + "d155d2d2-2627-425b-9be8-44ae9f541762", + [](const ledger::Result result, const std::string& image) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(image, ""); + }); +} + +TEST_F(GetCaptchaTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + "d155d2d2-2627-425b-9be8-44ae9f541762", + [](const ledger::Result result, const std::string& image) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(image, ""); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.cc new file mode 100644 index 000000000000..c23f64dd53f5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.cc @@ -0,0 +1,134 @@ +/* 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/endpoint/promotion/get_recover_wallet/get_recover_wallet.h" + +#include "base/json/json_reader.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// GET /v3/wallet/recover/{public_key} +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_NOT_FOUND (404) +// +// Response body: +// { +// "paymentId": "d59d4b69-f66e-4ee8-9c88-1c522e02ffd3", +// "walletProvider": { +// "id": "a9d12d76-2b6d-4f8b-99df-bb801bff9407", +// "name": "uphold" +// }, +// "altcurrency": "BAT", +// "publicKey": "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745" +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +GetRecoverWallet::GetRecoverWallet(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +GetRecoverWallet::~GetRecoverWallet() = default; + +std::string GetRecoverWallet::GetUrl(const std::string& public_key_hex) { + const std::string& path = base::StringPrintf( + "/v3/wallet/recover/%s", + public_key_hex.c_str()); + + return GetServerUrl(path); +} + +ledger::Result GetRecoverWallet::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_NOT_FOUND) { + BLOG(0, "Not found"); + return ledger::Result::NOT_FOUND; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result GetRecoverWallet::ParseBody( + const std::string& body, + std::string* payment_id) { + DCHECK(payment_id); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + const auto* payment_id_string = dictionary->FindStringKey("paymentId"); + if (!payment_id_string || payment_id_string->empty()) { + BLOG(0, "Payment id is missing"); + return ledger::Result::LEDGER_ERROR; + } + + *payment_id = *payment_id_string; + return ledger::Result::LEDGER_OK; +} + +void GetRecoverWallet::Request( + const std::string& public_key_hex, + GetRecoverWalletCallback callback) { + auto url_callback = std::bind(&GetRecoverWallet::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(public_key_hex), + {}, + "", + "application/json; charset=utf-8", + ledger::UrlMethod::GET, + url_callback); +} + +void GetRecoverWallet::OnRequest( + const ledger::UrlResponse& response, + GetRecoverWalletCallback callback) { + ledger::LogUrlResponse(__func__, response); + + std::string payment_id; + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, payment_id); + return; + } + + result = ParseBody(response.body, &payment_id); + callback(result, payment_id); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.h new file mode 100644 index 000000000000..eca59540b714 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.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_ENDPOINT_PROMOTION_GET_RECOVER_WALLET_GET_RECOVER_\ +WALLET_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_GET_RECOVER_WALLET_GET_RECOVER_\ +WALLET_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using GetRecoverWalletCallback = std::function; + +class GetRecoverWallet { + public: + explicit GetRecoverWallet(bat_ledger::LedgerImpl* ledger); + ~GetRecoverWallet(); + + void Request( + const std::string& public_key_hex, + GetRecoverWalletCallback callback); + + private: + std::string GetUrl(const std::string& public_key_hex); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* payment_id); + + void OnRequest( + const ledger::UrlResponse& response, + GetRecoverWalletCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_GET_RECOVER_WALLET_GET_RECOVER_\ +// WALLET_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet_unittest.cc new file mode 100644 index 000000000000..254b5354d5c6 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet_unittest.cc @@ -0,0 +1,154 @@ +/* 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/endpoint/promotion/get_recover_wallet/get_recover_wallet.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=GetRecoverWalletTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class GetRecoverWalletTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr wallet_; + + GetRecoverWalletTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + wallet_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(GetRecoverWalletTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "paymentId": "d59d4b69-f66e-4ee8-9c88-1c522e02ffd3", + "walletProvider": { + "id": "a9d12d76-2b6d-4f8b-99df-bb801bff9407", + "name": "uphold" + }, + "altcurrency": "BAT", + "publicKey": "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745" + })"; + callback(response); + })); + + wallet_->Request( + "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745", + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_EQ(payment_id, "d59d4b69-f66e-4ee8-9c88-1c522e02ffd3"); + }); +} + +TEST_F(GetRecoverWalletTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + wallet_->Request( + "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745", + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(payment_id, ""); + }); +} + +TEST_F(GetRecoverWalletTest, ServerError404) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 404; + response.url = url; + response.body = ""; + callback(response); + })); + + wallet_->Request( + "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745", + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::NOT_FOUND); + EXPECT_EQ(payment_id, ""); + }); +} + +TEST_F(GetRecoverWalletTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + wallet_->Request( + "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745", + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(payment_id, ""); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.cc new file mode 100644 index 000000000000..a4056f5af711 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.cc @@ -0,0 +1,178 @@ +/* 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/endpoint/promotion/get_signed_creds/get_signed_creds.h" + +#include + +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// GET /v1/promotions/{promotion_id}/claims/{claim_id} +// +// Success code: +// HTTP_OK (200) +// +// Error Codes: +// HTTP_ACCEPTED (202) +// HTTP_BAD_REQUEST (400) +// HTTP_NOT_FOUND (404) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body (success): +// { +// "id": "9c9aed7f-b349-452e-80a8-95faf2b1600d", +// "orderId": "f2e6494e-fb21-44d1-90e9-b5408799acd8", +// "issuerId": "138bf9ca-69fe-4540-9ac4-bc65baddc4a0", +// "signedCreds": [ +// "ijSZoLLG+EnRN916RUQcjiV6c4Wb6ItbnxXBFhz81EQ=", +// "dj6glCJ2roHYcTFcXF21IrKx1uT/ptM7SJEdiEE1fG8=", +// "nCF9a4KuASICVC0zrx2wGnllgIUxBMnylpu5SA+oBjI=", +// ], +// "batchProof": "zx0cdJhaB/OdYcUtnyXdi+lsoniN2vRTZ1w0U4D7Mgeu1I7RwB+tYKNgFU", +// "publicKey": "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I=" +// } +// +// Response body (error): +// { +// "message": "Claim has been accepted but is not ready", +// "code": 202, +// "data": {} +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +GetSignedCreds::GetSignedCreds(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +GetSignedCreds::~GetSignedCreds() = default; + +std::string GetSignedCreds::GetUrl( + const std::string& promotion_id, + const std::string& claim_id) { + const std::string& path = base::StringPrintf( + "/v1/promotions/%s/claims/%s", + promotion_id.c_str(), + claim_id.c_str()); + + return GetServerUrl(path); +} + +ledger::Result GetSignedCreds::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_ACCEPTED) { + return ledger::Result::RETRY_SHORT; + } + + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_NOT_FOUND) { + BLOG(0, "Unrecognized claim id"); + return ledger::Result::NOT_FOUND; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Internal server error"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result GetSignedCreds::ParseBody( + const std::string& body, + ledger::CredsBatch* batch) { + DCHECK(batch); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + auto* batch_proof = dictionary->FindStringKey("batchProof"); + if (!batch_proof) { + BLOG(0, "Missing batch proof"); + return ledger::Result::LEDGER_ERROR; + } + + auto* signed_creds = dictionary->FindListKey("signedCreds"); + if (!signed_creds) { + BLOG(0, "Missing signed creds"); + return ledger::Result::LEDGER_ERROR; + } + + auto* public_key = dictionary->FindStringKey("publicKey"); + if (!public_key) { + BLOG(0, "Missing public key"); + return ledger::Result::LEDGER_ERROR; + } + + base::JSONWriter::Write(*signed_creds, &batch->signed_creds); + batch->public_key = *public_key; + batch->batch_proof = *batch_proof; + + return ledger::Result::LEDGER_OK; +} + +void GetSignedCreds::Request( + const std::string& promotion_id, + const std::string& claim_id, + GetSignedCredsCallback callback) { + auto url_callback = std::bind(&GetSignedCreds::OnRequest, + this, + _1, + callback); + + ledger_->LoadURL( + GetUrl(promotion_id, claim_id), + {}, + "", + "", + ledger::UrlMethod::GET, + url_callback); +} + +void GetSignedCreds::OnRequest( + const ledger::UrlResponse& response, + GetSignedCredsCallback callback) { + ledger::LogUrlResponse(__func__, response); + + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, nullptr); + return; + } + + ledger::CredsBatch batch; + result = ParseBody(response.body, &batch); + callback(result, ledger::CredsBatch::New(batch)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.h new file mode 100644 index 000000000000..19140e97dec8 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.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_ENDPOINT_PROMOTION_GET_SIGNED_CREDS_GET_SIGNED_CREDS_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_GET_SIGNED_CREDS_GET_SIGNED_CREDS_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using GetSignedCredsCallback = std::function; + +class GetSignedCreds { + public: + explicit GetSignedCreds(bat_ledger::LedgerImpl* ledger); + ~GetSignedCreds(); + + void Request( + const std::string& promotion_id, + const std::string& claim_id, + GetSignedCredsCallback callback); + + private: + std::string GetUrl( + const std::string& promotion_id, + const std::string& claim_id); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + ledger::CredsBatch* batch); + + void OnRequest( + const ledger::UrlResponse& response, + GetSignedCredsCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_GET_SIGNED_CREDS_GET_SIGNED_CREDS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds_unittest.cc new file mode 100644 index 000000000000..88b112002698 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds_unittest.cc @@ -0,0 +1,220 @@ +/* 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/endpoint/promotion/get_signed_creds/get_signed_creds.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=GetSignedCredsTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class GetSignedCredsTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr creds_; + + GetSignedCredsTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + creds_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(GetSignedCredsTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "id": "9c9aed7f-b349-452e-80a8-95faf2b1600d", + "orderId": "f2e6494e-fb21-44d1-90e9-b5408799acd8", + "issuerId": "138bf9ca-69fe-4540-9ac4-bc65baddc4a0", + "signedCreds": [ + "ijSZoLLG+EnRN916RUQcjiV6c4Wb6ItbnxXBFhz81EQ=", + "dj6glCJ2roHYcTFcXF21IrKx1uT/ptM7SJEdiEE1fG8=", + "nCF9a4KuASICVC0zrx2wGnllgIUxBMnylpu5SA+oBjI=" + ], + "batchProof": "zx0cdJhaB/OdYcUtnyXdi+lsoniN2KNgFU", + "publicKey": "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I=" + })"; + callback(response); + })); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + "848d-995e186901a1", + [](const ledger::Result result, ledger::CredsBatchPtr batch) { + ledger::CredsBatch expected_batch; + expected_batch.batch_proof = "zx0cdJhaB/OdYcUtnyXdi+lsoniN2KNgFU"; + expected_batch.public_key = + "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I="; + expected_batch.signed_creds = + R"(["ijSZoLLG+EnRN916RUQcjiV6c4Wb6ItbnxXBFhz81EQ=","dj6glCJ2roHYcTFcXF21IrKx1uT/ptM7SJEdiEE1fG8=","nCF9a4KuASICVC0zrx2wGnllgIUxBMnylpu5SA+oBjI="])"; // NOLINT + + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_TRUE(expected_batch.Equals(*batch)); + }); +} + +TEST_F(GetSignedCredsTest, ServerError202) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 202; + response.url = url; + response.body = ""; + callback(response); + })); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + "848d-995e186901a1", + [](const ledger::Result result, ledger::CredsBatchPtr batch) { + EXPECT_EQ(result, ledger::Result::RETRY_SHORT); + EXPECT_TRUE(!batch); + }); +} + +TEST_F(GetSignedCredsTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + "848d-995e186901a1", + [](const ledger::Result result, ledger::CredsBatchPtr batch) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(!batch); + }); +} + +TEST_F(GetSignedCredsTest, ServerError404) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 404; + response.url = url; + response.body = ""; + callback(response); + })); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + "848d-995e186901a1", + [](const ledger::Result result, ledger::CredsBatchPtr batch) { + EXPECT_EQ(result, ledger::Result::NOT_FOUND); + EXPECT_TRUE(!batch); + }); +} + +TEST_F(GetSignedCredsTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + "848d-995e186901a1", + [](const ledger::Result result, ledger::CredsBatchPtr batch) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(!batch); + }); +} + +TEST_F(GetSignedCredsTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + "848d-995e186901a1", + [](const ledger::Result result, ledger::CredsBatchPtr batch) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(!batch); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.cc new file mode 100644 index 000000000000..f12473f4896f --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.cc @@ -0,0 +1,141 @@ +/* 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/endpoint/promotion/get_wallet_balance/get_wallet_balance.h" + +#include + +#include "base/json/json_reader.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/global_constants.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// GET /v3/wallet/uphold/{payment_id} +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_NOT_FOUND (404) +// HTTP_SERVICE_UNAVAILABLE (503) +// +// Response body: +// { +// "total": 0.0 +// "spendable": 0.0 +// "confirmed": 0.0 +// "unconfirmed": 0.0 +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +GetWalletBalance::GetWalletBalance(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +GetWalletBalance::~GetWalletBalance() = default; + +std::string GetWalletBalance::GetUrl() { + const std::string payment_id = ledger_->state()->GetPaymentId(); + const std::string path = base::StringPrintf( + "/v3/wallet/uphold/%s", + payment_id.c_str()); + + return GetServerUrl(path); +} + +ledger::Result GetWalletBalance::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid payment id"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_NOT_FOUND) { + BLOG(0, "Unrecognized payment id"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_SERVICE_UNAVAILABLE) { + BLOG(0, "No conversion rate yet in ratios service"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result GetWalletBalance::ParseBody( + const std::string& body, + ledger::Balance* balance) { + DCHECK(balance); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + const auto confirmed = dictionary->FindDoubleKey("confirmed"); + if (confirmed) { + balance->total = *confirmed; + } + + balance->user_funds = balance->total; + balance->wallets.insert( + std::make_pair(ledger::kWalletAnonymous, balance->total)); + + return ledger::Result::LEDGER_OK; +} + +void GetWalletBalance::Request(GetWalletBalanceCallback callback) { + auto url_callback = std::bind(&GetWalletBalance::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(), + {}, + "", + "", + ledger::UrlMethod::GET, + url_callback); +} + +void GetWalletBalance::OnRequest( + const ledger::UrlResponse& response, + GetWalletBalanceCallback callback) { + ledger::LogUrlResponse(__func__, response); + + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, nullptr); + return; + } + + ledger::Balance balance; + result = ParseBody(response.body, &balance); + callback(result, ledger::Balance::New(balance)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.h new file mode 100644 index 000000000000..884caf7cdafb --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.h @@ -0,0 +1,53 @@ +/* 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_ENDPOINT_PROMOTION_GET_WALLET_BALANCE_GET_WALLET_BALANCE_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_GET_WALLET_BALANCE_GET_WALLET_BALANCE_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using GetWalletBalanceCallback = std::function; + +class GetWalletBalance { + public: + explicit GetWalletBalance(bat_ledger::LedgerImpl* ledger); + ~GetWalletBalance(); + + void Request(GetWalletBalanceCallback callback); + + private: + std::string GetUrl(); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + ledger::Balance* balance); + + void OnRequest( + const ledger::UrlResponse& response, + GetWalletBalanceCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_GET_WALLET_BALANCE_GET_WALLET_\ +// BALANCE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance_unittest.cc new file mode 100644 index 000000000000..e476132e5cfa --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance_unittest.cc @@ -0,0 +1,177 @@ +/* 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/endpoint/promotion/get_wallet_balance/get_wallet_balance.h" + +#include +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/global_constants.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=GetWalletBalanceTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class GetWalletBalanceTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr balance_; + + GetWalletBalanceTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + balance_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(GetWalletBalanceTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "total": 5.0, + "spendable": 0.0, + "confirmed": 5.0, + "unconfirmed": 0.0 + })"; + callback(response); + })); + + balance_->Request( + [](const ledger::Result result, ledger::BalancePtr balance) { + ledger::Balance expected_balance; + expected_balance.total = 5; + expected_balance.user_funds = 5; + expected_balance.wallets = {{ledger::kWalletAnonymous, 5}}; + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_TRUE(expected_balance.Equals(*balance)); + }); +} + +TEST_F(GetWalletBalanceTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + balance_->Request( + [](const ledger::Result result, ledger::BalancePtr balance) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(!balance); + }); +} + +TEST_F(GetWalletBalanceTest, ServerError404) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 404; + response.url = url; + response.body = ""; + callback(response); + })); + + balance_->Request( + [](const ledger::Result result, ledger::BalancePtr balance) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(!balance); + }); +} + +TEST_F(GetWalletBalanceTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + balance_->Request( + [](const ledger::Result result, ledger::BalancePtr balance) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(!balance); + }); +} + +TEST_F(GetWalletBalanceTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + balance_->Request( + [](const ledger::Result result, ledger::BalancePtr balance) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_TRUE(!balance); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.cc new file mode 100644 index 000000000000..d675638cb3a7 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.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 "bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.h" + +#include + +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v1/wallets/{payment_id}/events/batloss/{version} +// +// Request body: +// { +// "amount": 20.5 +// } +// +// Success code: +// HTTP_OK (200) +// +// Error Codes: +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body: +// {Empty} + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostBatLoss::PostBatLoss(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostBatLoss::~PostBatLoss() = default; + +std::string PostBatLoss::GetUrl(const int32_t version) { + const std::string payment_id = ledger_->state()->GetPaymentId(); + const std::string& path = base::StringPrintf( + "/v1/wallets/%s/events/batloss/%d", + payment_id.c_str(), + version); + + return GetServerUrl(path); +} + +std::string PostBatLoss::GeneratePayload(const double amount) { + return base::StringPrintf(R"({"amount": %f})", amount); +} + +ledger::Result PostBatLoss::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Internal server error"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PostBatLoss::Request( + const double amount, + const int32_t version, + PostBatLossCallback callback) { + const std::string payment_id = ledger_->state()->GetPaymentId(); + const std::string payload = GeneratePayload(amount); + + const std::string header_url = base::StringPrintf( + "post /v1/wallets/%s/events/batloss/%d", + payment_id.c_str(), + version); + + const auto headers = braveledger_request_util::BuildSignHeaders( + header_url, + payload, + payment_id, + ledger_->state()->GetRecoverySeed()); + + auto url_callback = std::bind(&PostBatLoss::OnRequest, + this, + _1, + callback); + + ledger_->LoadURL( + GetUrl(version), + headers, + payload, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostBatLoss::OnRequest( + const ledger::UrlResponse& response, + PostBatLossCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.h new file mode 100644 index 000000000000..c600e15828dd --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.h @@ -0,0 +1,51 @@ +/* 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_ENDPOINT_PROMOTION_POST_BAT_LOSS_POST_BAT_LOSS_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_BAT_LOSS_POST_BAT_LOSS_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostBatLossCallback = std::function; + +class PostBatLoss { + public: + explicit PostBatLoss(bat_ledger::LedgerImpl* ledger); + ~PostBatLoss(); + + void Request( + const double amount, + const int32_t version, + PostBatLossCallback callback); + + private: + std::string GetUrl(const int32_t version); + + std::string GeneratePayload(const double amount); + + ledger::Result CheckStatusCode(const int status_code); + + void OnRequest( + const ledger::UrlResponse& response, + PostBatLossCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_BAT_LOSS_POST_BAT_LOSS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss_unittest.cc new file mode 100644 index 000000000000..d03e41af9574 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss_unittest.cc @@ -0,0 +1,133 @@ +/* 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/endpoint/promotion/post_bat_loss/post_bat_loss.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/internal/state/state_keys.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostBatLossTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostBatLossTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr loss_; + + PostBatLossTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + loss_ = std::make_unique(mock_ledger_impl_.get()); + } + + void SetUp() override { + const std::string payment_id = "this_is_id"; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStatePaymentId)) + .WillByDefault(testing::Return(payment_id)); + + const std::string wallet_passphrase = + "AN6DLuI2iZzzDxpzywf+IKmK1nzFRarNswbaIDI3pQg="; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStateRecoverySeed)) + .WillByDefault(testing::Return(wallet_passphrase)); + } +}; + +TEST_F(PostBatLossTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + loss_->Request( + 30.0, + 1, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PostBatLossTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + loss_->Request( + 30.0, + 1, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostBatLossTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + loss_->Request( + 30.0, + 1, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.cc new file mode 100644 index 000000000000..8b96d1f58a21 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.cc @@ -0,0 +1,147 @@ +/* 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/endpoint/promotion/post_captcha/post_captcha.h" + +#include + +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v1/captchas +// +// Request body: +// { +// "paymentId": "83b3b77b-e7c3-455b-adda-e476fa0656d2" +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// +// Response body: +// { +// "hint": "circle", +// "captchaId": "d155d2d2-2627-425b-9be8-44ae9f541762" +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostCaptcha::PostCaptcha(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostCaptcha::~PostCaptcha() = default; + +std::string PostCaptcha::GetUrl() { + return GetServerUrl("/v1/captchas"); +} + +std::string PostCaptcha::GeneratePayload() { + base::Value body(base::Value::Type::DICTIONARY); + body.SetStringKey( + "paymentId", + ledger_->state()->GetPaymentId()); + + std::string json; + base::JSONWriter::Write(body, &json); + + return json; +} + +ledger::Result PostCaptcha::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result PostCaptcha::ParseBody( + const std::string& body, + std::string* hint, + std::string* captcha_id) { + DCHECK(hint && captcha_id); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + const auto* captcha_id_parse = dictionary->FindStringKey("captchaId"); + if (!captcha_id_parse) { + BLOG(0, "Captcha id is wrong"); + return ledger::Result::LEDGER_ERROR; + } + + const auto* hint_parse = dictionary->FindStringKey("hint"); + if (!hint_parse) { + BLOG(0, "Hint is wrong"); + return ledger::Result::LEDGER_ERROR; + } + + *captcha_id = *captcha_id_parse; + *hint = *hint_parse; + + return ledger::Result::LEDGER_OK; +} + +void PostCaptcha::Request(PostCaptchaCallback callback) { + auto url_callback = std::bind(&PostCaptcha::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(), + {}, + GeneratePayload(), + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostCaptcha::OnRequest( + const ledger::UrlResponse& response, + PostCaptchaCallback callback) { + ledger::LogUrlResponse(__func__, response); + + std::string hint; + std::string captcha_id; + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, hint, captcha_id); + return; + } + + result = ParseBody(response.body, &hint, &captcha_id); + callback(result, hint, captcha_id); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.h new file mode 100644 index 000000000000..6f9be5f7a9e3 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.h @@ -0,0 +1,56 @@ +/* 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_ENDPOINT_PROMOTION_POST_CAPTCHA_POST_CAPTCHA_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_CAPTCHA_POST_CAPTCHA_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostCaptchaCallback = std::function; + +class PostCaptcha { + public: + explicit PostCaptcha(bat_ledger::LedgerImpl* ledger); + ~PostCaptcha(); + + void Request(PostCaptchaCallback callback); + + private: + std::string GetUrl(); + + std::string GeneratePayload(); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* hint, + std::string* captcha_id); + + void OnRequest( + const ledger::UrlResponse& response, + PostCaptchaCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_CAPTCHA_POST_CAPTCHA_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha_unittest.cc new file mode 100644 index 000000000000..894cb41c6636 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha_unittest.cc @@ -0,0 +1,130 @@ +/* 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/endpoint/promotion/post_captcha/post_captcha.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostCaptchaTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostCaptchaTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr captcha_; + + PostCaptchaTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + captcha_ = + std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PostCaptchaTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "hint": "circle", + "captchaId": "d155d2d2-2627-425b-9be8-44ae9f541762" + })"; + callback(response); + })); + + captcha_->Request( + []( + const ledger::Result result, + const std::string& hint, + const std::string& captcha_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_EQ(hint, "circle"); + EXPECT_EQ(captcha_id, "d155d2d2-2627-425b-9be8-44ae9f541762"); + }); +} + +TEST_F(PostCaptchaTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + []( + const ledger::Result result, + const std::string& hint, + const std::string& captcha_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostCaptchaTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + []( + const ledger::Result result, + const std::string& hint, + const std::string& captcha_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.cc new file mode 100644 index 000000000000..07141fb07a18 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.cc @@ -0,0 +1,177 @@ +/* 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/endpoint/promotion/post_claim_uphold/post_claim_uphold.h" + +#include +#include +#include + +#include "base/base64.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/common/security_helper.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/uphold/uphold_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v3/wallet/uphold/{payment_id}/claim +// +// Request body: +// { +// "signedLinkingRequest": "......", +// "anonymousAddress": "asfeq4gerg34gl3g34lg34g" +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_FORBIDDEN (403) +// HTTP_NOT_FOUND (404) +// HTTP_CONFLICT (409) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body: +// {Empty} + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostClaimUphold::PostClaimUphold(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostClaimUphold::~PostClaimUphold() = default; + +std::string PostClaimUphold::GetUrl() { + const std::string payment_id = ledger_->state()->GetPaymentId(); + const std::string& path = base::StringPrintf( + "/v3/wallet/uphold/%s/claim", + payment_id.c_str()); + + return GetServerUrl(path); +} + +std::string PostClaimUphold::GeneratePayload(const std::string& user_funds) { + auto wallets = ledger_->ledger_client()->GetExternalWallets(); + auto wallet_ptr = braveledger_uphold::GetWallet(std::move(wallets)); + if (!wallet_ptr) { + BLOG(0, "Wallet is null"); + return ""; + } + + const std::string amount = user_funds.empty() ? "0" : user_funds; + + base::Value denomination(base::Value::Type::DICTIONARY); + denomination.SetStringKey("amount", amount); + denomination.SetStringKey("currency", "BAT"); + + base::Value octets(base::Value::Type::DICTIONARY); + octets.SetKey("denomination", std::move(denomination)); + octets.SetStringKey("destination", wallet_ptr->address); + std::string octets_json; + base::JSONWriter::Write(octets, &octets_json); + + const std::string header_digest = + braveledger_helper::Security::DigestValue(octets_json); + + std::vector> headers; + headers.push_back({{"digest", header_digest}}); + + const std::string header_signature = braveledger_helper::Security::Sign( + headers, + "primary", + ledger_->state()->GetRecoverySeed()); + + base::Value signed_reqeust(base::Value::Type::DICTIONARY); + signed_reqeust.SetStringKey("octets", octets_json); + signed_reqeust.SetKey("body", std::move(octets)); + + base::Value headers_dict(base::Value::Type::DICTIONARY); + headers_dict.SetStringKey("digest", header_digest); + headers_dict.SetStringKey("signature", header_signature); + signed_reqeust.SetKey("headers", std::move(headers_dict)); + + std::string signed_request_json; + base::JSONWriter::Write(signed_reqeust, &signed_request_json); + + std::string signed_request_base64; + base::Base64Encode(signed_request_json, &signed_request_base64); + + base::Value payload(base::Value::Type::DICTIONARY); + payload.SetStringKey("signedLinkingRequest", signed_request_base64); + std::string json; + base::JSONWriter::Write(payload, &json); + + return json; +} + +ledger::Result PostClaimUphold::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_FORBIDDEN) { + BLOG(0, "Forbidden"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_NOT_FOUND) { + BLOG(0, "Not found"); + return ledger::Result::NOT_FOUND; + } + + if (status_code == net::HTTP_CONFLICT) { + BLOG(0, "Not found"); + return ledger::Result::ALREADY_EXISTS; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Internal server error"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PostClaimUphold::Request( + const std::string& user_funds, + PostClaimUpholdCallback callback) { + auto url_callback = std::bind(&PostClaimUphold::OnRequest, + this, + _1, + callback); + const std::string& payload = GeneratePayload(user_funds); + + ledger_->LoadURL( + GetUrl(), + {}, + payload, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostClaimUphold::OnRequest( + const ledger::UrlResponse& response, + PostClaimUpholdCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.h new file mode 100644 index 000000000000..1d7947f75c26 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.h @@ -0,0 +1,55 @@ +/* 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_ENDPOINT_PROMOTION_POST_CLAIM_UPHOLD_POST_CLAIM_UPHOLD_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_CLAIM_UPHOLD_POST_CLAIM_UPHOLD_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostClaimUpholdCallback = std::function; + +class PostClaimUphold { + public: + explicit PostClaimUphold(bat_ledger::LedgerImpl* ledger); + ~PostClaimUphold(); + + void Request( + const std::string& user_funds, + PostClaimUpholdCallback callback); + + private: + std::string GetUrl(); + + std::string GeneratePayload(const std::string& user_funds); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* payment_id); + + void OnRequest( + const ledger::UrlResponse& response, + PostClaimUpholdCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_CLAIM_UPHOLD_POST_CLAIM_UPHOLD_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold_unittest.cc new file mode 100644 index 000000000000..2fd95f7d8f99 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold_unittest.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 "bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostClaimUpholdTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostClaimUpholdTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr claim_; + + PostClaimUpholdTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + claim_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PostClaimUpholdTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + claim_->Request( + "30.0", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PostClaimUpholdTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + claim_->Request( + "30.0", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostClaimUpholdTest, ServerError403) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 403; + response.url = url; + response.body = ""; + callback(response); + })); + + claim_->Request( + "30.0", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostClaimUpholdTest, ServerError404) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 404; + response.url = url; + response.body = ""; + callback(response); + })); + + claim_->Request( + "30.0", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::NOT_FOUND); + }); +} + +TEST_F(PostClaimUpholdTest, ServerError409) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 409; + response.url = url; + response.body = ""; + callback(response); + })); + + claim_->Request( + "30.0", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::ALREADY_EXISTS); + }); +} + +TEST_F(PostClaimUpholdTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + claim_->Request( + "30.0", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostClaimUpholdTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + claim_->Request( + "30.0", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.cc new file mode 100644 index 000000000000..79724c8f5636 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.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 "bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.h" + +#include + +#include "base/json/json_writer.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v1/promotions/reportclobberedclaims +// +// Request body: +// { +// "claimIds": ["asfeq4gerg34gl3g34lg34g"] +// } +// +// Success code: +// HTTP_OK (200) +// +// Error Codes: +// HTTP_BAD_REQUEST (400) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body: +// {Empty} + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostClobberedClaims::PostClobberedClaims(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostClobberedClaims::~PostClobberedClaims() = default; + +std::string PostClobberedClaims::GetUrl() { + return GetServerUrl("/v2//promotions/reportclobberedclaims"); +} + +std::string PostClobberedClaims::GeneratePayload(base::Value corrupted_claims) { + base::Value body(base::Value::Type::DICTIONARY); + body.SetKey("claimIds", std::move(corrupted_claims)); + + std::string json; + base::JSONWriter::Write(body, &json); + + return json; +} + +ledger::Result PostClobberedClaims::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Internal server error"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PostClobberedClaims::Request( + base::Value corrupted_claims, + PostClobberedClaimsCallback callback) { + auto url_callback = std::bind(&PostClobberedClaims::OnRequest, + this, + _1, + callback); + + ledger_->LoadURL( + GetUrl(), + {}, + GeneratePayload(std::move(corrupted_claims)), + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostClobberedClaims::OnRequest( + const ledger::UrlResponse& response, + PostClobberedClaimsCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.h new file mode 100644 index 000000000000..7ed30c54ef28 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.h @@ -0,0 +1,55 @@ +/* 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_ENDPOINT_PROMOTION_POST_CLOBBERED_\ +CLAIMS_POST_CLOBBERED_CLAIMS_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_CLOBBERED_\ +CLAIMS_POST_CLOBBERED_CLAIMS_H_ + +#include + +#include "base/values.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostClobberedClaimsCallback = std::function; + +class PostClobberedClaims { + public: + explicit PostClobberedClaims(bat_ledger::LedgerImpl* ledger); + ~PostClobberedClaims(); + + void Request( + base::Value corrupted_claims, + PostClobberedClaimsCallback callback); + + private: + std::string GetUrl(); + + std::string GeneratePayload(base::Value corrupted_claims); + + ledger::Result CheckStatusCode(const int status_code); + + void OnRequest( + const ledger::UrlResponse& response, + PostClobberedClaimsCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_CLOBBERED_\ +// CLAIMS_POST_CLOBBERED_CLAIMS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims_unittest.cc new file mode 100644 index 000000000000..fb76be83805e --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims_unittest.cc @@ -0,0 +1,155 @@ +/* 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/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.h" + +#include +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostClobberedClaimsTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostClobberedClaimsTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr claims_; + + PostClobberedClaimsTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + claims_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PostClobberedClaimsTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + base::Value corrupted_claims(base::Value::Type::LIST); + corrupted_claims.Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + claims_->Request( + std::move(corrupted_claims), + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PostClobberedClaimsTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + base::Value corrupted_claims(base::Value::Type::LIST); + corrupted_claims.Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + claims_->Request( + std::move(corrupted_claims), + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostClobberedClaimsTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + base::Value corrupted_claims(base::Value::Type::LIST); + corrupted_claims.Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + claims_->Request( + std::move(corrupted_claims), + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostClobberedClaimsTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + base::Value corrupted_claims(base::Value::Type::LIST); + corrupted_claims.Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + claims_->Request( + std::move(corrupted_claims), + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.cc new file mode 100644 index 000000000000..e9e5f70a6569 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.cc @@ -0,0 +1,187 @@ +/* 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/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/post_creds/post_creds.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v1/promotions/{promotion_id} +// +// Request body: +// { +// "paymentId": "ff50981d-47de-4210-848d-995e186901a1", +// "blindedCreds": [ +// "wqto9FnferrKUM0lcp2B0lecMQwArvUq3hWGCYlXiQo=", +// "ZiSXpF61aZ/tL2MxkKzI5Vnw2aLJE2ln2FMHAtKc9Co=" +// ] +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_FORBIDDEN (403) +// HTTP_CONFLICT (409) +// HTTP_GONE (410) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body: +// { +// "claimId": "53714048-9675-419e-baa3-369d85a2facb" +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostCreds::PostCreds(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostCreds::~PostCreds() = default; + +std::string PostCreds::GetUrl(const std::string& promotion_id) { + const std::string& path = base::StringPrintf( + "/v1/promotions/%s", + promotion_id.c_str()); + + return GetServerUrl(path); +} + +std::string PostCreds::GeneratePayload( + std::unique_ptr blinded_creds) { + base::Value body(base::Value::Type::DICTIONARY); + body.SetStringKey("paymentId", ledger_->state()->GetPaymentId()); + body.SetKey("blindedCreds", base::Value(std::move(*blinded_creds))); + + std::string json; + base::JSONWriter::Write(body, &json); + + return json; +} + +ledger::Result PostCreds::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_FORBIDDEN) { + BLOG(0, "Signature validation failed"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_CONFLICT) { + BLOG(0, "Incorrect blinded credentials"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_GONE) { + BLOG(0, "Promotion is gone"); + return ledger::Result::NOT_FOUND; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Internal server error"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result PostCreds::ParseBody( + const std::string& body, + std::string* claim_id) { + DCHECK(claim_id); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + auto* id = dictionary->FindStringKey("claimId"); + if (!id || id->empty()) { + BLOG(0, "Claim id is missing"); + return ledger::Result::LEDGER_ERROR; + } + + *claim_id = *id; + + return ledger::Result::LEDGER_OK; +} + +void PostCreds::Request( + const std::string& promotion_id, + std::unique_ptr blinded_creds, + PostCredsCallback callback) { + if (!blinded_creds) { + BLOG(0, "Blinded creds are null"); + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + const std::string& payload = GeneratePayload(std::move(blinded_creds)); + + const auto headers = braveledger_request_util::BuildSignHeaders( + "post /v1/promotions/" + promotion_id, + payload, + ledger_->state()->GetPaymentId(), + ledger_->state()->GetRecoverySeed()); + + auto url_callback = std::bind(&PostCreds::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(promotion_id), + headers, + payload, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostCreds::OnRequest( + const ledger::UrlResponse& response, + PostCredsCallback callback) { + ledger::LogUrlResponse(__func__, response); + + std::string claim_id; + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, claim_id); + return; + } + + result = ParseBody(response.body, &claim_id); + callback(result, claim_id); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.h new file mode 100644 index 000000000000..b69a224fc807 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds.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_ENDPOINT_PROMOTION_POST_CREDS_POST_CREDS_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_CREDS_POST_CREDS_H_ + +#include +#include + +#include "base/values.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostCredsCallback = std::function; + +class PostCreds { + public: + explicit PostCreds(bat_ledger::LedgerImpl* ledger); + ~PostCreds(); + + void Request( + const std::string& promotion_id, + std::unique_ptr blinded_creds, + PostCredsCallback callback); + + private: + std::string GetUrl(const std::string& promotion_id); + + std::string GeneratePayload(std::unique_ptr blinded_creds); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* claim_id); + + void OnRequest( + const ledger::UrlResponse& response, + PostCredsCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_CREDS_POST_CREDS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds_unittest.cc new file mode 100644 index 000000000000..38de1dc5e985 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_creds/post_creds_unittest.cc @@ -0,0 +1,258 @@ +/* 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/endpoint/promotion/post_creds/post_creds.h" + +#include +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/internal/state/state_keys.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostCredsTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostCredsTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr creds_; + + PostCredsTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + creds_ = std::make_unique(mock_ledger_impl_.get()); + } + + void SetUp() override { + const std::string payment_id = "this_is_id"; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStatePaymentId)) + .WillByDefault(testing::Return(payment_id)); + + const std::string wallet_passphrase = + "AN6DLuI2iZzzDxpzywf+IKmK1nzFRarNswbaIDI3pQg="; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStateRecoverySeed)) + .WillByDefault(testing::Return(wallet_passphrase)); + } +}; + +TEST_F(PostCredsTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "claimId": "53714048-9675-419e-baa3-369d85a2facb" + })"; + callback(response); + })); + + auto creds = std::make_unique(); + creds->Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + std::move(creds), + [](const ledger::Result result, const std::string& claim_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_EQ(claim_id, "53714048-9675-419e-baa3-369d85a2facb"); + }); +} + +TEST_F(PostCredsTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + auto creds = std::make_unique(); + creds->Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + std::move(creds), + [](const ledger::Result result, const std::string& claim_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostCredsTest, ServerError403) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 403; + response.url = url; + response.body = ""; + callback(response); + })); + + auto creds = std::make_unique(); + creds->Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + std::move(creds), + [](const ledger::Result result, const std::string& claim_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostCredsTest, ServerError409) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 409; + response.url = url; + response.body = ""; + callback(response); + })); + + auto creds = std::make_unique(); + creds->Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + std::move(creds), + [](const ledger::Result result, const std::string& claim_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostCredsTest, ServerError410) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 410; + response.url = url; + response.body = ""; + callback(response); + })); + + auto creds = std::make_unique(); + creds->Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + std::move(creds), + [](const ledger::Result result, const std::string& claim_id) { + EXPECT_EQ(result, ledger::Result::NOT_FOUND); + }); +} + +TEST_F(PostCredsTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + auto creds = std::make_unique(); + creds->Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + std::move(creds), + [](const ledger::Result result, const std::string& claim_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostCredsTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + auto creds = std::make_unique(); + creds->Append(base::Value("asfeq4gerg34gl3g34lg34g")); + + creds_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + std::move(creds), + [](const ledger::Result result, const std::string& claim_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.cc new file mode 100644 index 000000000000..6aeb16da4e26 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.cc @@ -0,0 +1,144 @@ +/* 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/endpoint/promotion/post_devicecheck/post_devicecheck.h" + +#include + +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v1/devicecheck/attestations +// +// Request body: +// { +// "paymentId": "83b3b77b-e7c3-455b-adda-e476fa0656d2" +// "publicKeyHash": "f3f2f3ffqdwfqwfwqfd" +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_UNAUTHORIZED (401) +// +// Response body: +// { +// "nonce": "c4645786-052f-402f-8593-56af2f7a21ce" +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostDevicecheck::PostDevicecheck(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostDevicecheck::~PostDevicecheck() = default; + +std::string PostDevicecheck::GetUrl() { + return GetServerUrl("/v1/devicecheck/attestations"); +} + +std::string PostDevicecheck::GeneratePayload(const std::string& key) { + const std::string payment_id = ledger_->state()->GetPaymentId(); + base::Value dictionary(base::Value::Type::DICTIONARY); + dictionary.SetStringKey("publicKeyHash", key); + dictionary.SetStringKey("paymentId", payment_id); + std::string json; + base::JSONWriter::Write(dictionary, &json); + + return json; +} + +ledger::Result PostDevicecheck::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_UNAUTHORIZED) { + BLOG(0, "Invalid token"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result PostDevicecheck::ParseBody( + const std::string& body, + std::string* nonce) { + DCHECK(nonce); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + auto* nonce_string = dictionary->FindStringKey("nonce"); + if (!nonce_string) { + BLOG(0, "Nonce is wrong"); + return ledger::Result::LEDGER_ERROR; + } + + *nonce = *nonce_string; + return ledger::Result::LEDGER_OK; +} + +void PostDevicecheck::Request( + const std::string& key, + PostDevicecheckCallback callback) { + auto url_callback = std::bind(&PostDevicecheck::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(), + {}, + GeneratePayload(key), + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostDevicecheck::OnRequest( + const ledger::UrlResponse& response, + PostDevicecheckCallback callback) { + ledger::LogUrlResponse(__func__, response); + + std::string nonce; + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, nonce); + return; + } + + result = ParseBody(response.body, &nonce); + callback(result, nonce); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.h new file mode 100644 index 000000000000..282e0bec4c34 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.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_ENDPOINT_PROMOTION_POST_DEVICECEHCK_POST_DEVICECEHCK_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_DEVICECEHCK_POST_DEVICECEHCK_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostDevicecheckCallback = std::function; + +class PostDevicecheck { + public: + explicit PostDevicecheck(bat_ledger::LedgerImpl* ledger); + ~PostDevicecheck(); + + void Request(const std::string& key, PostDevicecheckCallback callback); + + private: + std::string GetUrl(); + + std::string GeneratePayload(const std::string& key); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* nonce); + + void OnRequest( + const ledger::UrlResponse& response, + PostDevicecheckCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_DEVICECEHCK_POST_DEVICECEHCK_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck_unittest.cc new file mode 100644 index 000000000000..b8267d0987fb --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck_unittest.cc @@ -0,0 +1,149 @@ +/* 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/endpoint/promotion/post_devicecheck/post_devicecheck.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostDevicecheckTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostDevicecheckTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr devicecheck_; + + PostDevicecheckTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + devicecheck_ = + std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PostDevicecheckTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "nonce": "c4645786-052f-402f-8593-56af2f7a21ce" + })"; + callback(response); + })); + + devicecheck_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + [](const ledger::Result result, const std::string& nonce) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_EQ(nonce, "c4645786-052f-402f-8593-56af2f7a21ce"); + }); +} + +TEST_F(PostDevicecheckTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + devicecheck_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + [](const ledger::Result result, const std::string& nonce) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(nonce, ""); + }); +} + +TEST_F(PostDevicecheckTest, ServerError401) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 401; + response.url = url; + response.body = ""; + callback(response); + })); + + devicecheck_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + [](const ledger::Result result, const std::string& nonce) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(nonce, ""); + }); +} + +TEST_F(PostDevicecheckTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + devicecheck_->Request( + "ff50981d-47de-4210-848d-995e186901a1", + [](const ledger::Result result, const std::string& nonce) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(nonce, ""); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.cc new file mode 100644 index 000000000000..abb0a1179515 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.cc @@ -0,0 +1,146 @@ +/* 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/endpoint/promotion/post_safetynet/post_safetynet.h" + +#include + +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v2/attestations/safetynet +// +// Request body: +// { +// "paymentIds": [ +// "83b3b77b-e7c3-455b-adda-e476fa0656d2" +// ] +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_UNAUTHORIZED (401) +// +// Response body: +// { +// "nonce": "c4645786-052f-402f-8593-56af2f7a21ce" +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostSafetynet::PostSafetynet(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostSafetynet::~PostSafetynet() = default; + +std::string PostSafetynet::GetUrl() { + return GetServerUrl("/v2/attestations/safetynet"); +} + +std::string PostSafetynet::GeneratePayload() { + auto payment_id = base::Value(ledger_->state()->GetPaymentId()); + base::Value payment_ids(base::Value::Type::LIST); + payment_ids.Append(std::move(payment_id)); + + base::Value body(base::Value::Type::DICTIONARY); + body.SetKey("paymentIds", std::move(payment_ids)); + + std::string json; + base::JSONWriter::Write(body, &json); + + return json; +} + +ledger::Result PostSafetynet::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_UNAUTHORIZED) { + BLOG(0, "Invalid token"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result PostSafetynet::ParseBody( + const std::string& body, + std::string* nonce) { + DCHECK(nonce); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + auto* nonce_string = dictionary->FindStringKey("nonce"); + if (!nonce_string) { + BLOG(0, "Nonce is wrong"); + return ledger::Result::LEDGER_ERROR; + } + + *nonce = *nonce_string; + return ledger::Result::LEDGER_OK; +} + +void PostSafetynet::Request(PostSafetynetCallback callback) { + auto url_callback = std::bind(&PostSafetynet::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(), + {}, + GeneratePayload(), + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostSafetynet::OnRequest( + const ledger::UrlResponse& response, + PostSafetynetCallback callback) { + ledger::LogUrlResponse(__func__, response); + + std::string nonce; + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, nonce); + return; + } + + result = ParseBody(response.body, &nonce); + callback(result, nonce); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.h new file mode 100644 index 000000000000..e22fc23b99fe --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.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_ENDPOINT_PROMOTION_POST_SAFETYNET_POST_SAFETYNET_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_SAFETYNET_POST_SAFETYNET_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostSafetynetCallback = std::function; + +class PostSafetynet { + public: + explicit PostSafetynet(bat_ledger::LedgerImpl* ledger); + ~PostSafetynet(); + + void Request(PostSafetynetCallback callback); + + private: + std::string GetUrl(); + + std::string GeneratePayload(); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* nonce); + + void OnRequest( + const ledger::UrlResponse& response, + PostSafetynetCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_SAFETYNET_POST_SAFETYNET_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet_unittest.cc new file mode 100644 index 000000000000..68867245b8c8 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet_unittest.cc @@ -0,0 +1,121 @@ +/* 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/endpoint/promotion/post_safetynet/post_safetynet.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostSafetynetTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostSafetynetTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr safetynet_; + + PostSafetynetTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + safetynet_ = + std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PostSafetynetTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({ + "nonce": "c4645786-052f-402f-8593-56af2f7a21ce" + })"; + callback(response); + })); + + safetynet_->Request( + [](const ledger::Result result, const std::string& nonce) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_EQ(nonce, "c4645786-052f-402f-8593-56af2f7a21ce"); + }); +} + +TEST_F(PostSafetynetTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + safetynet_->Request( + [](const ledger::Result result, const std::string& nonce) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(nonce, ""); + }); +} + +TEST_F(PostSafetynetTest, ServerError401) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 401; + response.url = url; + response.body = ""; + callback(response); + })); + + safetynet_->Request( + [](const ledger::Result result, const std::string& nonce) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(nonce, ""); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.cc new file mode 100644 index 000000000000..83979b1787b2 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.cc @@ -0,0 +1,138 @@ +/* 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/endpoint/promotion/post_suggestions/post_suggestions.h" + +#include + +#include "base/base64.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/credentials/credentials_util.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v1/suggestions +// +// Request body: +// { +// "credentials": credentials": [ +// { +// "t": "", +// "publicKey": "", +// "signature": "" +// } +// ], +// "suggestion": "base64_string" +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_SERVICE_UNAVAILABLE (503) +// +// Response body: +// {Empty} + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostSuggestions::PostSuggestions(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostSuggestions::~PostSuggestions() = default; + +std::string PostSuggestions::GetUrl() { + return GetServerUrl("/v1/suggestions"); +} + +std::string PostSuggestions::GeneratePayload( + const braveledger_credentials::CredentialsRedeem& redeem) { + base::Value data(base::Value::Type::DICTIONARY); + data.SetStringKey( + "type", + braveledger_credentials::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); + braveledger_credentials::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; +} + +ledger::Result PostSuggestions::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_SERVICE_UNAVAILABLE) { + BLOG(0, "No conversion rate yet in ratios service"); + return ledger::Result::BAD_REGISTRATION_RESPONSE; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PostSuggestions::Request( + const braveledger_credentials::CredentialsRedeem& redeem, + PostSuggestionsCallback callback) { + auto url_callback = std::bind(&PostSuggestions::OnRequest, + this, + _1, + callback); + + ledger_->LoadURL( + GetUrl(), + {}, + GeneratePayload(redeem), + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostSuggestions::OnRequest( + const ledger::UrlResponse& response, + PostSuggestionsCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.h new file mode 100644 index 000000000000..63648217002b --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.h @@ -0,0 +1,53 @@ +/* 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_ENDPOINT_PROMOTION_POST_SUGGESTIONS_POST_SUGGESTIONS_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_SUGGESTIONS_POST_SUGGESTIONS_H_ + +#include + +#include "bat/ledger/internal/credentials/credentials_redeem.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostSuggestionsCallback = std::function; + +class PostSuggestions { + public: + explicit PostSuggestions(bat_ledger::LedgerImpl* ledger); + ~PostSuggestions(); + + void Request( + const braveledger_credentials::CredentialsRedeem& redeem, + PostSuggestionsCallback callback); + + private: + std::string GetUrl(); + + std::string GeneratePayload( + const braveledger_credentials::CredentialsRedeem& redeem); + + ledger::Result CheckStatusCode(const int status_code); + + void OnRequest( + const ledger::UrlResponse& response, + PostSuggestionsCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_SUGGESTIONS_POST_SUGGESTIONS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions_unittest.cc new file mode 100644 index 000000000000..0a4773c45574 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions_unittest.cc @@ -0,0 +1,154 @@ +/* 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/endpoint/promotion/post_suggestions/post_suggestions.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostSuggestionsTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostSuggestionsTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr suggestions_; + + PostSuggestionsTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + suggestions_ = std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PostSuggestionsTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + ledger::UnblindedToken token; + token.token_value = "s1OrSZUvo/33u3Y866mQaG/b6d94TqMThLal4+DSX4UrR4jT+GtTErim+FtEyZ7nebNGRoUDxObiUni9u8BB0DIT2aya6rYWko64IrXJWpbf0SVHnQFVYNyX64NjW9R6"; // NOLINT + token.public_key = "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I="; + + braveledger_credentials::CredentialsRedeem redeem; + redeem.publisher_key = "brave.com"; + redeem.type = ledger::RewardsType::ONE_TIME_TIP; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = {token}; + redeem.order_id = "c4645786-052f-402f-8593-56af2f7a21ce"; + redeem.contribution_id = "83b3b77b-e7c3-455b-adda-e476fa0656d2"; + + suggestions_->Request( + redeem, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PostSuggestionsTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + ledger::UnblindedToken token; + token.token_value = "s1OrSZUvo/33u3Y866mQaG/b6d94TqMThLal4+DSX4UrR4jT+GtTErim+FtEyZ7nebNGRoUDxObiUni9u8BB0DIT2aya6rYWko64IrXJWpbf0SVHnQFVYNyX64NjW9R6"; // NOLINT + token.public_key = "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I="; + + braveledger_credentials::CredentialsRedeem redeem; + redeem.publisher_key = "brave.com"; + redeem.type = ledger::RewardsType::ONE_TIME_TIP; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = {token}; + redeem.order_id = "c4645786-052f-402f-8593-56af2f7a21ce"; + redeem.contribution_id = "83b3b77b-e7c3-455b-adda-e476fa0656d2"; + + suggestions_->Request( + redeem, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostSuggestionsTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + ledger::UnblindedToken token; + token.token_value = "s1OrSZUvo/33u3Y866mQaG/b6d94TqMThLal4+DSX4UrR4jT+GtTErim+FtEyZ7nebNGRoUDxObiUni9u8BB0DIT2aya6rYWko64IrXJWpbf0SVHnQFVYNyX64NjW9R6"; // NOLINT + token.public_key = "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I="; + + braveledger_credentials::CredentialsRedeem redeem; + redeem.publisher_key = "brave.com"; + redeem.type = ledger::RewardsType::ONE_TIME_TIP; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = {token}; + redeem.order_id = "c4645786-052f-402f-8593-56af2f7a21ce"; + redeem.contribution_id = "83b3b77b-e7c3-455b-adda-e476fa0656d2"; + + suggestions_->Request( + redeem, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.cc new file mode 100644 index 000000000000..180d49ad5e0a --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.cc @@ -0,0 +1,129 @@ +/* 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/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.h" + +#include + +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/common/security_helper.h" +#include "bat/ledger/internal/credentials/credentials_util.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v1/suggestions/claim +// +// Request body: +// { +// "credentials": credentials": [ +// { +// "t": "", +// "publicKey": "", +// "signature": "" +// } +// ], +// "paymentId": "83b3b77b-e7c3-455b-adda-e476fa0656d2" +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_SERVICE_UNAVAILABLE (503) +// +// Response body: +// {Empty} + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostSuggestionsClaim::PostSuggestionsClaim(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostSuggestionsClaim::~PostSuggestionsClaim() = default; + +std::string PostSuggestionsClaim::GetUrl() { + return GetServerUrl("/v1/suggestions/claim"); +} + +std::string PostSuggestionsClaim::GeneratePayload( + const braveledger_credentials::CredentialsRedeem& redeem) { + const std::string payment_id = ledger_->state()->GetPaymentId(); + base::Value credentials(base::Value::Type::LIST); + braveledger_credentials::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; +} + +ledger::Result PostSuggestionsClaim::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_SERVICE_UNAVAILABLE) { + BLOG(0, "No conversion rate yet in ratios service"); + return ledger::Result::BAD_REGISTRATION_RESPONSE; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PostSuggestionsClaim::Request( + const braveledger_credentials::CredentialsRedeem& redeem, + PostSuggestionsClaimCallback callback) { + auto url_callback = std::bind(&PostSuggestionsClaim::OnRequest, + this, + _1, + callback); + + const std::string payload = GeneratePayload(redeem); + + auto headers = braveledger_request_util::BuildSignHeaders( + "post /v1/suggestions/claim", + payload, + ledger_->state()->GetPaymentId(), + ledger_->state()->GetRecoverySeed()); + + ledger_->LoadURL( + GetUrl(), + headers, + payload, + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostSuggestionsClaim::OnRequest( + const ledger::UrlResponse& response, + PostSuggestionsClaimCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.h new file mode 100644 index 000000000000..ee17c7b1df2f --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.h @@ -0,0 +1,56 @@ +/* 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_ENDPOINT_PROMOTION_POST_SUGGESTIONS_CLAIM_\ +POST_SUGGESTIONS_CLAIM_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_SUGGESTIONS_CLAIM_\ +POST_SUGGESTIONS_CLAIM_H_ + +#include + +#include "bat/ledger/internal/credentials/credentials_redeem.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostSuggestionsClaimCallback = std::function; + +class PostSuggestionsClaim { + public: + explicit PostSuggestionsClaim(bat_ledger::LedgerImpl* ledger); + ~PostSuggestionsClaim(); + + void Request( + const braveledger_credentials::CredentialsRedeem& redeem, + PostSuggestionsClaimCallback callback); + + private: + std::string GetUrl(); + + std::string GeneratePayload( + const braveledger_credentials::CredentialsRedeem& redeem); + + ledger::Result CheckStatusCode(const int status_code); + + void OnRequest( + const ledger::UrlResponse& response, + PostSuggestionsClaimCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_SUGGESTIONS_CLAIM_\ +// POST_SUGGESTIONS_CLAIM_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim_unittest.cc new file mode 100644 index 000000000000..d212f6b3f8fd --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim_unittest.cc @@ -0,0 +1,166 @@ +/* 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/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/internal/state/state_keys.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostSuggestionsClaimTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostSuggestionsClaimTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr claim_; + + PostSuggestionsClaimTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + claim_ = std::make_unique(mock_ledger_impl_.get()); + } + + void SetUp() override { + const std::string payment_id = "this_is_id"; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStatePaymentId)) + .WillByDefault(testing::Return(payment_id)); + + const std::string wallet_passphrase = + "AN6DLuI2iZzzDxpzywf+IKmK1nzFRarNswbaIDI3pQg="; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStateRecoverySeed)) + .WillByDefault(testing::Return(wallet_passphrase)); + } +}; + +TEST_F(PostSuggestionsClaimTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + ledger::UnblindedToken token; + token.token_value = "s1OrSZUvo/33u3Y866mQaG/b6d94TqMThLal4+DSX4UrR4jT+GtTErim+FtEyZ7nebNGRoUDxObiUni9u8BB0DIT2aya6rYWko64IrXJWpbf0SVHnQFVYNyX64NjW9R6"; // NOLINT + token.public_key = "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I="; + + braveledger_credentials::CredentialsRedeem redeem; + redeem.publisher_key = "brave.com"; + redeem.type = ledger::RewardsType::ONE_TIME_TIP; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = {token}; + redeem.order_id = "c4645786-052f-402f-8593-56af2f7a21ce"; + redeem.contribution_id = "83b3b77b-e7c3-455b-adda-e476fa0656d2"; + + claim_->Request( + redeem, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PostSuggestionsClaimTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + ledger::UnblindedToken token; + token.token_value = "s1OrSZUvo/33u3Y866mQaG/b6d94TqMThLal4+DSX4UrR4jT+GtTErim+FtEyZ7nebNGRoUDxObiUni9u8BB0DIT2aya6rYWko64IrXJWpbf0SVHnQFVYNyX64NjW9R6"; // NOLINT + token.public_key = "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I="; + + braveledger_credentials::CredentialsRedeem redeem; + redeem.publisher_key = "brave.com"; + redeem.type = ledger::RewardsType::ONE_TIME_TIP; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = {token}; + redeem.order_id = "c4645786-052f-402f-8593-56af2f7a21ce"; + redeem.contribution_id = "83b3b77b-e7c3-455b-adda-e476fa0656d2"; + + claim_->Request( + redeem, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PostSuggestionsClaimTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + ledger::UnblindedToken token; + token.token_value = "s1OrSZUvo/33u3Y866mQaG/b6d94TqMThLal4+DSX4UrR4jT+GtTErim+FtEyZ7nebNGRoUDxObiUni9u8BB0DIT2aya6rYWko64IrXJWpbf0SVHnQFVYNyX64NjW9R6"; // NOLINT + token.public_key = "dvpysTSiJdZUPihius7pvGOfngRWfDiIbrowykgMi1I="; + + braveledger_credentials::CredentialsRedeem redeem; + redeem.publisher_key = "brave.com"; + redeem.type = ledger::RewardsType::ONE_TIME_TIP; + redeem.processor = ledger::ContributionProcessor::BRAVE_TOKENS; + redeem.token_list = {token}; + redeem.order_id = "c4645786-052f-402f-8593-56af2f7a21ce"; + redeem.contribution_id = "83b3b77b-e7c3-455b-adda-e476fa0656d2"; + + claim_->Request( + redeem, + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.cc new file mode 100644 index 000000000000..91743cfa9aaa --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.cc @@ -0,0 +1,139 @@ +/* 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/endpoint/promotion/post_wallet_brave/post_wallet_brave.h" + +#include + +#include "base/json/json_reader.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/common/security_helper.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/request/request_util.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// POST /v3/wallet/brave +// +// Request body: +// {Empty} +// +// Success code: +// HTTP_CREATED (201) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_SERVICE_UNAVAILABLE (503) +// +// Response body: +// { +// "paymentId": "37742974-3b80-461a-acfb-937e105e5af4" +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PostWalletBrave::PostWalletBrave(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PostWalletBrave::~PostWalletBrave() = default; + +std::string PostWalletBrave::GetUrl() { + return GetServerUrl("/v3/wallet/brave"); +} + +ledger::Result PostWalletBrave::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code == net::HTTP_SERVICE_UNAVAILABLE) { + BLOG(0, "No conversion rate yet in ratios service"); + return ledger::Result::BAD_REGISTRATION_RESPONSE; + } + + if (status_code != net::HTTP_CREATED) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +ledger::Result PostWalletBrave::ParseBody( + const std::string& body, + std::string* payment_id) { + DCHECK(payment_id); + + base::Optional value = base::JSONReader::Read(body); + if (!value || !value->is_dict()) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + base::DictionaryValue* dictionary = nullptr; + if (!value->GetAsDictionary(&dictionary)) { + BLOG(0, "Invalid JSON"); + return ledger::Result::LEDGER_ERROR; + } + + const auto* payment_id_string = dictionary->FindStringKey("paymentId"); + if (!payment_id_string || payment_id_string->empty()) { + BLOG(1, "Payment id is wrong"); + return ledger::Result::LEDGER_ERROR; + } + + *payment_id = *payment_id_string; + + return ledger::Result::LEDGER_OK; +} + +void PostWalletBrave::Request( + PostWalletBraveCallback callback) { + const auto seed = ledger_->state()->GetRecoverySeed(); + const auto headers = braveledger_request_util::BuildSignHeaders( + "post /v3/wallet/brave", + "", + braveledger_helper::Security::GetPublicKeyHexFromSeed(seed), + seed); + + auto url_callback = std::bind(&PostWalletBrave::OnRequest, + this, + _1, + callback); + + ledger_->LoadURL( + GetUrl(), + headers, + "", + "application/json; charset=utf-8", + ledger::UrlMethod::POST, + url_callback); +} + +void PostWalletBrave::OnRequest( + const ledger::UrlResponse& response, + PostWalletBraveCallback callback) { + ledger::LogUrlResponse(__func__, response); + + std::string payment_id; + ledger::Result result = CheckStatusCode(response.status_code); + + if (result != ledger::Result::LEDGER_OK) { + callback(result, payment_id); + return; + } + + result = ParseBody(response.body, &payment_id); + callback(result, payment_id); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.h new file mode 100644 index 000000000000..8fe4dffabe5a --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.h @@ -0,0 +1,52 @@ +/* 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_ENDPOINT_PROMOTION_POST_WALLET_BRAVE_POST_WALLET_BRAVE_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_POST_WALLET_BRAVE_POST_WALLET_BRAVE_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PostWalletBraveCallback = std::function; + +class PostWalletBrave { + public: + explicit PostWalletBrave(bat_ledger::LedgerImpl* ledger); + ~PostWalletBrave(); + + void Request(PostWalletBraveCallback callback); + + private: + std::string GetUrl(); + + ledger::Result CheckStatusCode(const int status_code); + + ledger::Result ParseBody( + const std::string& body, + std::string* payment_id); + + void OnRequest( + const ledger::UrlResponse& response, + PostWalletBraveCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_POST_WALLET_BRAVE_POST_WALLET_BRAVE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave_unittest.cc new file mode 100644 index 000000000000..0272859e8d25 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave_unittest.cc @@ -0,0 +1,156 @@ +/* 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/endpoint/promotion/post_wallet_brave/post_wallet_brave.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/internal/state/state_keys.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PostWalletBraveTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PostWalletBraveTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr wallet_; + + PostWalletBraveTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + wallet_ = std::make_unique(mock_ledger_impl_.get()); + } + + void SetUp() override { + const std::string payment_id = "this_is_id"; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStatePaymentId)) + .WillByDefault(testing::Return(payment_id)); + + const std::string wallet_passphrase = + "AN6DLuI2iZzzDxpzywf+IKmK1nzFRarNswbaIDI3pQg="; + ON_CALL(*mock_ledger_client_, GetStringState(ledger::kStateRecoverySeed)) + .WillByDefault(testing::Return(wallet_passphrase)); + } +}; + +TEST_F(PostWalletBraveTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 201; + response.url = url; + response.body = R"({ + "paymentId": "37742974-3b80-461a-acfb-937e105e5af4" + })"; + callback(response); + })); + + wallet_->Request( + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + EXPECT_EQ(payment_id, "37742974-3b80-461a-acfb-937e105e5af4"); + }); +} + +TEST_F(PostWalletBraveTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + wallet_->Request( + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(payment_id, ""); + }); +} + +TEST_F(PostWalletBraveTest, ServerError503) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 503; + response.url = url; + response.body = ""; + callback(response); + })); + + wallet_->Request( + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::BAD_REGISTRATION_RESPONSE); + EXPECT_EQ(payment_id, ""); + }); +} + +TEST_F(PostWalletBraveTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + wallet_->Request( + [](const ledger::Result result, const std::string& payment_id) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + EXPECT_EQ(payment_id, ""); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotion_server.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotion_server.cc new file mode 100644 index 000000000000..4e650ed549a0 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotion_server.cc @@ -0,0 +1,109 @@ +/* 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/endpoint/promotion/promotion_server.h" + +#include "bat/ledger/internal/ledger_impl.h" + +namespace ledger { +namespace endpoint { + +PromotionServer::PromotionServer(bat_ledger::LedgerImpl* ledger): + get_available_(new promotion::GetAvailable(ledger)), + post_creds_(new promotion::PostCreds(ledger)), + get_signed_creds_(new promotion::GetSignedCreds(ledger)), + post_clobbered_claims_(new promotion::PostClobberedClaims(ledger)), + post_bat_loss_(new promotion::PostBatLoss(ledger)), + post_wallet_brave_(new promotion::PostWalletBrave(ledger)), + get_recover_wallet_(new promotion::GetRecoverWallet(ledger)), + post_claim_uphold_(new promotion::PostClaimUphold(ledger)), + get_wallet_balance_(new promotion::GetWalletBalance(ledger)), + post_captcha_(new promotion::PostCaptcha(ledger)), + get_captcha_(new promotion::GetCaptcha(ledger)), + put_captcha_(new promotion::PutCaptcha(ledger)), + post_safetynet_(new promotion::PostSafetynet(ledger)), + put_safetynet_(new promotion::PutSafetynet(ledger)), + post_devicecheck_(new promotion::PostDevicecheck(ledger)), + put_devicecheck_(new promotion::PutDevicecheck(ledger)), + post_suggestions_(new promotion::PostSuggestions(ledger)), + post_suggestions_claim_(new promotion::PostSuggestionsClaim(ledger)) { +} + +PromotionServer::~PromotionServer() = default; + +promotion::GetAvailable* PromotionServer::get_available() const { + return get_available_.get(); +} + +promotion::PostCreds* PromotionServer::post_creds() const { + return post_creds_.get(); +} + +promotion::GetSignedCreds* PromotionServer::get_signed_creds() const { + return get_signed_creds_.get(); +} + +promotion::PostClobberedClaims* PromotionServer::post_clobbered_claims() const { + return post_clobbered_claims_.get(); +} + +promotion::PostBatLoss* PromotionServer::post_bat_loss() const { + return post_bat_loss_.get(); +} + +promotion::PostWalletBrave* PromotionServer::post_wallet_brave() const { + return post_wallet_brave_.get(); +} + +promotion::GetRecoverWallet* PromotionServer::get_recover_wallet() const { + return get_recover_wallet_.get(); +} + +promotion::PostClaimUphold* PromotionServer::post_claim_uphold() const { + return post_claim_uphold_.get(); +} + +promotion::GetWalletBalance* PromotionServer::get_wallet_balance() const { + return get_wallet_balance_.get(); +} + +promotion::PostCaptcha* PromotionServer::post_captcha() const { + return post_captcha_.get(); +} + +promotion::GetCaptcha* PromotionServer::get_captcha() const { + return get_captcha_.get(); +} + +promotion::PutCaptcha* PromotionServer::put_captcha() const { + return put_captcha_.get(); +} + +promotion::PostSafetynet* PromotionServer::post_safetynet() const { + return post_safetynet_.get(); +} + +promotion::PutSafetynet* PromotionServer::put_safetynet() const { + return put_safetynet_.get(); +} + +promotion::PostDevicecheck* PromotionServer::post_devicecheck() const { + return post_devicecheck_.get(); +} + +promotion::PutDevicecheck* PromotionServer::put_devicecheck() const { + return put_devicecheck_.get(); +} + +promotion::PostSuggestions* PromotionServer::post_suggestions() const { + return post_suggestions_.get(); +} + +promotion::PostSuggestionsClaim* +PromotionServer::post_suggestions_claim() const { + return post_suggestions_claim_.get(); +} + +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotion_server.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotion_server.h new file mode 100644 index 000000000000..23f44afa7988 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotion_server.h @@ -0,0 +1,103 @@ +/* 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_ENDPOINT_PROMOTION_PROMOTION_SERVER_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_PROMOTION_SERVER_H_ + +#include + +#include "bat/ledger/internal/endpoint/promotion/get_available/get_available.h" +#include "bat/ledger/internal/endpoint/promotion/get_captcha/get_captcha.h" +#include "bat/ledger/internal/endpoint/promotion/get_recover_wallet/get_recover_wallet.h" +#include "bat/ledger/internal/endpoint/promotion/get_signed_creds/get_signed_creds.h" +#include "bat/ledger/internal/endpoint/promotion/get_wallet_balance/get_wallet_balance.h" +#include "bat/ledger/internal/endpoint/promotion/post_bat_loss/post_bat_loss.h" +#include "bat/ledger/internal/endpoint/promotion/post_captcha/post_captcha.h" +#include "bat/ledger/internal/endpoint/promotion/post_claim_uphold/post_claim_uphold.h" +#include "bat/ledger/internal/endpoint/promotion/post_clobbered_claims/post_clobbered_claims.h" +#include "bat/ledger/internal/endpoint/promotion/post_creds/post_creds.h" +#include "bat/ledger/internal/endpoint/promotion/post_devicecheck/post_devicecheck.h" +#include "bat/ledger/internal/endpoint/promotion/post_safetynet/post_safetynet.h" +#include "bat/ledger/internal/endpoint/promotion/post_suggestions/post_suggestions.h" +#include "bat/ledger/internal/endpoint/promotion/post_suggestions_claim/post_suggestions_claim.h" +#include "bat/ledger/internal/endpoint/promotion/post_wallet_brave/post_wallet_brave.h" +#include "bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.h" +#include "bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.h" +#include "bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.h" +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { + +class PromotionServer { + public: + explicit PromotionServer(bat_ledger::LedgerImpl* ledger); + ~PromotionServer(); + + promotion::GetAvailable* get_available() const; + + promotion::PostCreds* post_creds() const; + + promotion::GetSignedCreds* get_signed_creds() const; + + promotion::PostClobberedClaims* post_clobbered_claims() const; + + promotion::PostBatLoss* post_bat_loss() const; + + promotion::PostWalletBrave* post_wallet_brave() const; + + promotion::GetRecoverWallet* get_recover_wallet() const; + + promotion::PostClaimUphold* post_claim_uphold() const; + + promotion::GetWalletBalance* get_wallet_balance() const; + + promotion::PostCaptcha* post_captcha() const; + + promotion::GetCaptcha* get_captcha() const; + + promotion::PutCaptcha* put_captcha() const; + + promotion::PostSafetynet* post_safetynet() const; + + promotion::PutSafetynet* put_safetynet() const; + + promotion::PostDevicecheck* post_devicecheck() const; + + promotion::PutDevicecheck* put_devicecheck() const; + + promotion::PostSuggestions* post_suggestions() const; + + promotion::PostSuggestionsClaim* post_suggestions_claim() const; + + private: + std::unique_ptr get_available_; + std::unique_ptr post_creds_; + std::unique_ptr get_signed_creds_; + std::unique_ptr post_clobbered_claims_; + std::unique_ptr post_bat_loss_; + std::unique_ptr post_wallet_brave_; + std::unique_ptr get_recover_wallet_; + std::unique_ptr post_claim_uphold_; + std::unique_ptr get_wallet_balance_; + std::unique_ptr post_captcha_; + std::unique_ptr get_captcha_; + std::unique_ptr put_captcha_; + std::unique_ptr post_safetynet_; + std::unique_ptr put_safetynet_; + std::unique_ptr post_devicecheck_; + std::unique_ptr put_devicecheck_; + std::unique_ptr post_suggestions_; + std::unique_ptr post_suggestions_claim_; +}; + +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_PROMOTION_SERVER_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util.cc new file mode 100644 index 000000000000..d44400c1a609 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util.cc @@ -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/. */ +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" + +#include "bat/ledger/ledger.h" + +namespace ledger { +namespace endpoint { +namespace promotion { + +const char kDevelopment[] = "https://grant.rewards.brave.software"; +const char kStaging[] = "https://grant.rewards.bravesoftware.com"; +const char kProduction[] = "https://grant.rewards.brave.com"; + +std::string GetServerUrl(const std::string& path) { + DCHECK(!path.empty()); + + std::string url; + switch (ledger::_environment) { + case ledger::Environment::DEVELOPMENT: + url = kDevelopment; + break; + case ledger::Environment::STAGING: + url = kStaging; + break; + case ledger::Environment::PRODUCTION: + url = kProduction; + break; + } + + return url + path; +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util.h new file mode 100644 index 000000000000..b005c9e981aa --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util.h @@ -0,0 +1,21 @@ +/* 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_ENDPOINT_PROMOTION_PROMOTION_UTIL_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_PROMOTION_UTIL_H_ + +#include + +namespace ledger { +namespace endpoint { +namespace promotion { + +std::string GetServerUrl(const std::string& path); + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_PROMOTION_UTIL_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util_unittest.cc new file mode 100644 index 000000000000..70fce9172d87 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/promotions_util_unittest.cc @@ -0,0 +1,41 @@ +/* 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/global_constants.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/ledger.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PromotionsUtilTest.* + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PromotionsUtilTest : public testing::Test { +}; + +TEST(PromotionsUtilTest, GetServerUrlDevelopment) { + ledger::_environment = ledger::Environment::DEVELOPMENT; + const std::string url = GetServerUrl("/test"); + const std::string expected_url = ""; + ASSERT_EQ(url, "https://grant.rewards.brave.software/test"); +} + +TEST(PromotionsUtilTest, GetServerUrlStaging) { + ledger::_environment = ledger::Environment::STAGING; + const std::string url = GetServerUrl("/test"); + ASSERT_EQ(url, "https://grant.rewards.bravesoftware.com/test"); +} + +TEST(PromotionsUtilTest, GetServerUrlProduction) { + ledger::_environment = ledger::Environment::PRODUCTION; + const std::string url = GetServerUrl("/test"); + ASSERT_EQ(url, "https://grant.rewards.brave.com/test"); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.cc new file mode 100644 index 000000000000..486191d7506b --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.cc @@ -0,0 +1,125 @@ +/* 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/endpoint/promotion/put_captcha/put_captcha.h" + +#include + +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// PUT /v1/captchas/{captcha_id} +// +// Request body: +// { +// "solution": { +// "x": 10, +// "y": 50 +// } +// } +// +// Success code: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_UNAUTHORIZED (401) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response Format (success): +// {Empty} +// +// Response Format (error): +// { +// "message": "Error solving captcha", +// "code": 401 +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PutCaptcha::PutCaptcha(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PutCaptcha::~PutCaptcha() = default; + +std::string PutCaptcha::GetUrl(const std::string& captcha_id) { + const std::string path = base::StringPrintf( + "/v1/captchas/%s", + captcha_id.c_str()); + + return GetServerUrl(path); +} + +std::string PutCaptcha::GeneratePayload(const int x, const int y) { + base::Value dictionary(base::Value::Type::DICTIONARY); + base::Value solution_dict(base::Value::Type::DICTIONARY); + solution_dict.SetIntKey("x", x); + solution_dict.SetIntKey("y", y); + dictionary.SetKey("solution", std::move(solution_dict)); + std::string payload; + base::JSONWriter::Write(dictionary, &payload); + + return payload; +} + +ledger::Result PutCaptcha::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::CAPTCHA_FAILED; + } + + if (status_code == net::HTTP_UNAUTHORIZED) { + BLOG(0, "Invalid solution"); + return ledger::Result::CAPTCHA_FAILED; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Failed to verify captcha solution"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PutCaptcha::Request( + const int x, + const int y, + const std::string& captcha_id, + PutCaptchaCallback callback) { + auto url_callback = std::bind(&PutCaptcha::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(captcha_id), + {}, + GeneratePayload(x, y), + "application/json; charset=utf-8", + ledger::UrlMethod::PUT, + url_callback); +} + +void PutCaptcha::OnRequest( + const ledger::UrlResponse& response, + PutCaptchaCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.h new file mode 100644 index 000000000000..1d8e3982b130 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha.h @@ -0,0 +1,52 @@ +/* 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_ENDPOINT_PROMOTION_PUT_CAPTCHA_PUT_CAPTCHA_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_PUT_CAPTCHA_PUT_CAPTCHA_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PutCaptchaCallback = std::function; + +class PutCaptcha { + public: + explicit PutCaptcha(bat_ledger::LedgerImpl* ledger); + ~PutCaptcha(); + + void Request( + const int x, + const int y, + const std::string& captcha_id, + PutCaptchaCallback callback); + + private: + std::string GetUrl(const std::string& captcha_id); + + std::string GeneratePayload(const int x, const int y); + + ledger::Result CheckStatusCode(const int status_code); + + void OnRequest( + const ledger::UrlResponse& response, + PutCaptchaCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_PUT_CAPTCHA_PUT_CAPTCHA_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha_unittest.cc new file mode 100644 index 000000000000..198e3d3584fc --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_captcha/put_captcha_unittest.cc @@ -0,0 +1,177 @@ +/* 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/endpoint/promotion/put_captcha/put_captcha.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PutCaptchaTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PutCaptchaTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr captcha_; + + PutCaptchaTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + captcha_ = + std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PutCaptchaTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + captcha_->Request( + 10, + 20, + "83b3b77b-e7c3-455b-adda-e476fa0656d2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PutCaptchaTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + 10, + 20, + "83b3b77b-e7c3-455b-adda-e476fa0656d2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::CAPTCHA_FAILED); + }); +} + +TEST_F(PutCaptchaTest, ServerError401) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 401; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + 10, + 20, + "83b3b77b-e7c3-455b-adda-e476fa0656d2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::CAPTCHA_FAILED); + }); +} + +TEST_F(PutCaptchaTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + 10, + 20, + "83b3b77b-e7c3-455b-adda-e476fa0656d2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +TEST_F(PutCaptchaTest, ServerErrorRandom) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 453; + response.url = url; + response.body = ""; + callback(response); + })); + + captcha_->Request( + 10, + 20, + "83b3b77b-e7c3-455b-adda-e476fa0656d2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.cc new file mode 100644 index 000000000000..12a7e39be71d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.cc @@ -0,0 +1,123 @@ +/* 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/endpoint/promotion/put_devicecheck/put_devicecheck.h" + +#include + +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// PUT /v1/devicecheck/attestations/{nonce} +// +// Request body: +// { +// "attestationBlob": "dfasdfasdpflsadfplf2r23re2", +// "signature": "435dfasdfaadff34f43sdpflsadfplf2r23re2" +// } +// +// Success: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_UNAUTHORIZED (401) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body (success): +// {Empty} +// +// Response body (error): +// { +// "message": "Error solving captcha", +// "code": 401 +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PutDevicecheck::PutDevicecheck(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PutDevicecheck::~PutDevicecheck() = default; + +std::string PutDevicecheck::GetUrl(const std::string& nonce) { + const std::string path = base::StringPrintf( + "/v1/devicecheck/attestations/%s", + nonce.c_str()); + + return GetServerUrl(path); +} + +std::string PutDevicecheck::GeneratePayload( + const std::string& blob, + const std::string& signature) { + base::Value dictionary(base::Value::Type::DICTIONARY); + dictionary.SetStringKey("attestationBlob", blob); + dictionary.SetStringKey("signature", signature); + std::string payload; + base::JSONWriter::Write(dictionary, &payload); + + return payload; +} + +ledger::Result PutDevicecheck::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::CAPTCHA_FAILED; + } + + if (status_code == net::HTTP_UNAUTHORIZED) { + BLOG(0, "Invalid solution"); + return ledger::Result::CAPTCHA_FAILED; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Failed to verify captcha solution"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PutDevicecheck::Request( + const std::string& blob, + const std::string& signature, + const std::string& nonce, + PutDevicecheckCallback callback) { + auto url_callback = std::bind(&PutDevicecheck::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(nonce), + {}, + GeneratePayload(blob, signature), + "application/json; charset=utf-8", + ledger::UrlMethod::PUT, + url_callback); +} + +void PutDevicecheck::OnRequest( + const ledger::UrlResponse& response, + PutDevicecheckCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.h new file mode 100644 index 000000000000..14ea0f4231be --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck.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_ENDPOINT_PROMOTION_PUT_DEVICECHECK_PUT_DEVICECHECK_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_PUT_DEVICECHECK_PUT_DEVICECHECK_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PutDevicecheckCallback = std::function; + +class PutDevicecheck { + public: + explicit PutDevicecheck(bat_ledger::LedgerImpl* ledger); + ~PutDevicecheck(); + + void Request( + const std::string& blob, + const std::string& signature, + const std::string& nonce, + PutDevicecheckCallback callback); + + private: + std::string GetUrl(const std::string& nonce); + + std::string GeneratePayload( + const std::string& blob, + const std::string& signature); + + ledger::Result CheckStatusCode(const int status_code); + + void OnRequest( + const ledger::UrlResponse& response, + PutDevicecheckCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_PUT_DEVICECHECK_PUT_DEVICECHECK_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck_unittest.cc new file mode 100644 index 000000000000..199278ec2070 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_devicecheck/put_devicecheck_unittest.cc @@ -0,0 +1,151 @@ +/* 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/endpoint/promotion/put_devicecheck/put_devicecheck.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PutDevicecheckTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PutDevicecheckTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr devicecheck_; + + PutDevicecheckTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + devicecheck_ = + std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PutDevicecheckTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + devicecheck_->Request( + "dsfqwf4f901a1", + "asdfasdf", + "fsadfasdfff4901a1", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PutDevicecheckTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + devicecheck_->Request( + "dsfqwf4f901a1", + "asdfasdf", + "fsadfasdfff4901a1", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::CAPTCHA_FAILED); + }); +} + +TEST_F(PutDevicecheckTest, ServerError401) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 401; + response.url = url; + response.body = ""; + callback(response); + })); + + devicecheck_->Request( + "dsfqwf4f901a1", + "asdfasdf", + "fsadfasdfff4901a1", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::CAPTCHA_FAILED); + }); +} + +TEST_F(PutDevicecheckTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + devicecheck_->Request( + "dsfqwf4f901a1", + "asdfasdf", + "fsadfasdfff4901a1", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.cc new file mode 100644 index 000000000000..9f1b6f1ccc64 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.cc @@ -0,0 +1,118 @@ +/* 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/endpoint/promotion/put_safetynet/put_safetynet.h" + +#include + +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "bat/ledger/internal/endpoint/promotion/promotions_util.h" +#include "bat/ledger/internal/ledger_impl.h" +#include "net/http/http_status_code.h" + +using std::placeholders::_1; + +// PUT /v2/attestations/safetynet/{nonce} +// +// Request body: +// { +// "token": "dfasdfasdpflsadfplf2r23re2" +// } +// +// Success: +// HTTP_OK (200) +// +// Error codes: +// HTTP_BAD_REQUEST (400) +// HTTP_UNAUTHORIZED (401) +// HTTP_INTERNAL_SERVER_ERROR (500) +// +// Response body (success): +// {Empty} +// +// Response body (error): +// { +// "message": "Error solving captcha", +// "code": 401 +// } + +namespace ledger { +namespace endpoint { +namespace promotion { + +PutSafetynet::PutSafetynet(bat_ledger::LedgerImpl* ledger): + ledger_(ledger) { + DCHECK(ledger_); +} + +PutSafetynet::~PutSafetynet() = default; + +std::string PutSafetynet::GetUrl(const std::string& nonce) { + const std::string path = base::StringPrintf( + "/v2/attestations/safetynet/%s", + nonce.c_str()); + + return GetServerUrl(path); +} + +std::string PutSafetynet::GeneratePayload(const std::string& token) { + base::Value dictionary(base::Value::Type::DICTIONARY); + dictionary.SetStringKey("token", token); + std::string payload; + base::JSONWriter::Write(dictionary, &payload); + + return payload; +} + +ledger::Result PutSafetynet::CheckStatusCode(const int status_code) { + if (status_code == net::HTTP_BAD_REQUEST) { + BLOG(0, "Invalid request"); + return ledger::Result::CAPTCHA_FAILED; + } + + if (status_code == net::HTTP_UNAUTHORIZED) { + BLOG(0, "Invalid solution"); + return ledger::Result::CAPTCHA_FAILED; + } + + if (status_code == net::HTTP_INTERNAL_SERVER_ERROR) { + BLOG(0, "Failed to verify captcha solution"); + return ledger::Result::LEDGER_ERROR; + } + + if (status_code != net::HTTP_OK) { + return ledger::Result::LEDGER_ERROR; + } + + return ledger::Result::LEDGER_OK; +} + +void PutSafetynet::Request( + const std::string& token, + const std::string& nonce, + PutSafetynetCallback callback) { + auto url_callback = std::bind(&PutSafetynet::OnRequest, + this, + _1, + callback); + ledger_->LoadURL( + GetUrl(nonce), + {}, + GeneratePayload(token), + "application/json; charset=utf-8", + ledger::UrlMethod::PUT, + url_callback); +} + +void PutSafetynet::OnRequest( + const ledger::UrlResponse& response, + PutSafetynetCallback callback) { + ledger::LogUrlResponse(__func__, response); + callback(CheckStatusCode(response.status_code)); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.h new file mode 100644 index 000000000000..876fd48cffd9 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet.h @@ -0,0 +1,51 @@ +/* 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_ENDPOINT_PROMOTION_PUT_SAFETYNET_PUT_SAFETYNET_H_ +#define BRAVELEDGER_ENDPOINT_PROMOTION_PUT_SAFETYNET_PUT_SAFETYNET_H_ + +#include + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace endpoint { +namespace promotion { + +using PutSafetynetCallback = std::function; + +class PutSafetynet { + public: + explicit PutSafetynet(bat_ledger::LedgerImpl* ledger); + ~PutSafetynet(); + + void Request( + const std::string& token, + const std::string& nonce, + PutSafetynetCallback callback); + + private: + std::string GetUrl(const std::string& nonce); + + std::string GeneratePayload(const std::string& token); + + ledger::Result CheckStatusCode(const int status_code); + + void OnRequest( + const ledger::UrlResponse& response, + PutSafetynetCallback callback); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED +}; + +} // namespace promotion +} // namespace endpoint +} // namespace ledger + +#endif // BRAVELEDGER_ENDPOINT_PROMOTION_PUT_SAFETYNET_PUT_SAFETYNET_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet_unittest.cc new file mode 100644 index 000000000000..4fa2243de9ec --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/endpoint/promotion/put_safetynet/put_safetynet_unittest.cc @@ -0,0 +1,147 @@ +/* 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/endpoint/promotion/put_safetynet/put_safetynet.h" + +#include +#include +#include + +#include "base/test/task_environment.h" +#include "bat/ledger/internal/ledger_client_mock.h" +#include "bat/ledger/internal/ledger_impl_mock.h" +#include "bat/ledger/ledger.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PutSafetynetTest.* + +using ::testing::_; +using ::testing::Invoke; + +namespace ledger { +namespace endpoint { +namespace promotion { + +class PutSafetynetTest : public testing::Test { + private: + base::test::TaskEnvironment scoped_task_environment_; + + protected: + std::unique_ptr mock_ledger_client_; + std::unique_ptr mock_ledger_impl_; + std::unique_ptr safetynet_; + + PutSafetynetTest() { + mock_ledger_client_ = std::make_unique(); + mock_ledger_impl_ = + std::make_unique(mock_ledger_client_.get()); + safetynet_ = + std::make_unique(mock_ledger_impl_.get()); + } +}; + +TEST_F(PutSafetynetTest, ServerOK) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 200; + response.url = url; + response.body = R"({})"; + callback(response); + })); + + safetynet_->Request( + "sdfsdf32d323d23d", + "dfasdfasdpflsadfplf2r23re2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_OK); + }); +} + +TEST_F(PutSafetynetTest, ServerError400) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 400; + response.url = url; + response.body = ""; + callback(response); + })); + + safetynet_->Request( + "sdfsdf32d323d23d", + "dfasdfasdpflsadfplf2r23re2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::CAPTCHA_FAILED); + }); +} + +TEST_F(PutSafetynetTest, ServerError401) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 401; + response.url = url; + response.body = ""; + callback(response); + })); + + safetynet_->Request( + "sdfsdf32d323d23d", + "dfasdfasdpflsadfplf2r23re2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::CAPTCHA_FAILED); + }); +} + +TEST_F(PutSafetynetTest, ServerError500) { + ON_CALL(*mock_ledger_client_, LoadURL(_, _, _, _, _, _)) + .WillByDefault( + Invoke([]( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::UrlMethod method, + ledger::LoadURLCallback callback) { + ledger::UrlResponse response; + response.status_code = 500; + response.url = url; + response.body = ""; + callback(response); + })); + + safetynet_->Request( + "sdfsdf32d323d23d", + "dfasdfasdpflsadfplf2r23re2", + [](const ledger::Result result) { + EXPECT_EQ(result, ledger::Result::LEDGER_ERROR); + }); +} + +} // namespace promotion +} // namespace endpoint +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc index c09348eb7bc6..1a8fa46329e8 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 @@ -10,7 +10,6 @@ #include "bat/ledger/internal/common/security_helper.h" #include "bat/ledger/internal/common/time_util.h" #include "bat/ledger/internal/publisher/publisher_status_helper.h" -#include "bat/ledger/internal/recovery/recovery.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/helper.h" #include "bat/ledger/internal/sku/sku_factory.h" @@ -27,11 +26,12 @@ LedgerImpl::LedgerImpl(ledger::LedgerClient* client) : publisher_(new braveledger_publisher::Publisher(this)), media_(new braveledger_media::Media(this)), contribution_(new braveledger_contribution::Contribution(this)), - wallet_(new braveledger_wallet::Wallet(this)), + wallet_(new ledger::wallet::Wallet(this)), database_(new braveledger_database::Database(this)), report_(new braveledger_report::Report(this)), state_(new braveledger_state::State(this)), api_(new braveledger_api::API(this)), + recovery_(new ledger::recovery::Recovery(this)), initialized_task_scheduler_(false), initializing_(false), last_tab_active_time_(0), @@ -88,7 +88,7 @@ braveledger_contribution::Contribution* LedgerImpl::contribution() const { return contribution_.get(); } -braveledger_wallet::Wallet* LedgerImpl::wallet() const { +ledger::wallet::Wallet* LedgerImpl::wallet() const { return wallet_.get(); } @@ -143,7 +143,7 @@ void LedgerImpl::StartServices() { contribution()->Initialize(); promotion()->Initialize(); api()->Initialize(); - braveledger_recovery::Check(this); + recovery_->Check(); } void LedgerImpl::Initialize( 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 eb6c3723b794..60b9c35a5df8 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 @@ -21,6 +21,7 @@ #include "bat/ledger/internal/media/media.h" #include "bat/ledger/internal/promotion/promotion.h" #include "bat/ledger/internal/publisher/publisher.h" +#include "bat/ledger/internal/recovery/recovery.h" #include "bat/ledger/internal/report/report.h" #include "bat/ledger/internal/sku/sku.h" #include "bat/ledger/internal/state/state.h" @@ -58,7 +59,7 @@ class LedgerImpl : public ledger::Ledger { braveledger_contribution::Contribution* contribution() const; - braveledger_wallet::Wallet* wallet() const; + ledger::wallet::Wallet* wallet() const; braveledger_report::Report* report() const; @@ -340,12 +341,13 @@ class LedgerImpl : public ledger::Ledger { std::unique_ptr publisher_; std::unique_ptr media_; std::unique_ptr contribution_; - std::unique_ptr wallet_; + std::unique_ptr wallet_; std::unique_ptr database_; std::unique_ptr report_; std::unique_ptr sku_; std::unique_ptr state_; std::unique_ptr api_; + std::unique_ptr recovery_; scoped_refptr task_runner_; bool initialized_task_scheduler_; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.cc index 269c50b576f8..47dfea8f8b71 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.cc @@ -97,7 +97,8 @@ std::string UrlResponseToString( void LogUrlResponse( const char* func, - const ledger::UrlResponse& response) { + const ledger::UrlResponse& response, + const bool long_response) { std::string result; if (!response.error.empty()) { result = "Error (" + response.error + ")"; @@ -132,7 +133,7 @@ void LogUrlResponse( response.url.c_str(), formatted_headers.c_str()); - BLOG(6, response_basic); + BLOG(long_response ? 7 : 6, response_basic); BLOG(9, response_headers); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.h index 3c949a464e5a..f004f8c72202 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/logging_util.h @@ -30,7 +30,8 @@ std::string UrlResponseToString( void LogUrlResponse( const char* func, - const ledger::UrlResponse& response); + const ledger::UrlResponse& response, + const bool long_response = false); } // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc index e5ad8a4eb935..9329491ab210 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.cc @@ -20,9 +20,6 @@ #include "bat/ledger/internal/legacy/wallet_info_properties.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/response/response_promotion.h" #include "bat/ledger/internal/static_values.h" #include "wrapper.hpp" // NOLINT @@ -77,9 +74,11 @@ void HandleExpiredPromotions( } // namespace Promotion::Promotion(bat_ledger::LedgerImpl* ledger) : - attestation_(std::make_unique + attestation_(std::make_unique (ledger)), transfer_(std::make_unique(ledger)), + promotion_server_( + std::make_unique(ledger)), ledger_(ledger) { DCHECK(ledger_); credentials_ = braveledger_credentials::CredentialsFactory::Create( @@ -139,28 +138,20 @@ void Promotion::Fetch(ledger::FetchPromotionCallback callback) { auto url_callback = std::bind(&Promotion::OnFetch, this, _1, + _2, + _3, std::move(callback)); auto client_info = ledger_->ledger_client()->GetClientInfo(); const std::string client = ParseClientInfoToString(std::move(client_info)); - - const std::string url = braveledger_request_util::GetFetchPromotionUrl( - wallet_payment_id, - client); - - ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, url_callback); + promotion_server_->get_available()->Request(client, url_callback); } void Promotion::OnFetch( - const ledger::UrlResponse& response, + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions, ledger::FetchPromotionCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - ledger::PromotionList list; - - const ledger::Result result = - braveledger_response_util::CheckFetchPromotions(response); - if (result == ledger::Result::NOT_FOUND) { ProcessFetchedPromotions( ledger::Result::NOT_FOUND, @@ -169,7 +160,7 @@ void Promotion::OnFetch( return; } - if (result != ledger::Result::LEDGER_OK) { + if (result == ledger::Result::LEDGER_ERROR) { ProcessFetchedPromotions( ledger::Result::LEDGER_ERROR, std::move(list), @@ -177,10 +168,20 @@ void Promotion::OnFetch( return; } + // even though that some promotions are corrupted + // we should display non corrupted ones either way + BLOG_IF( + 1, + result == ledger::Result::CORRUPTED_DATA, + "Promotions are not correct: " + << base::JoinString(corrupted_promotions, ", ")); + + auto shared_list = std::make_shared(std::move(list)); + auto all_callback = std::bind(&Promotion::OnGetAllPromotions, this, _1, - response, + shared_list, callback); ledger_->database()->GetAllPromotions(all_callback); @@ -188,37 +189,17 @@ void Promotion::OnFetch( void Promotion::OnGetAllPromotions( ledger::PromotionMap promotions, - const ledger::UrlResponse& response, + std::shared_ptr list, ledger::FetchPromotionCallback callback) { HandleExpiredPromotions(ledger_, &promotions); - ledger::PromotionList list; - std::vector corrupted_promotions; - const ledger::Result result = - braveledger_response_util::ParseFetchPromotions( - response, - &list, - &corrupted_promotions); - - if (result == ledger::Result::LEDGER_ERROR) { - BLOG(0, "Failed to parse promotions"); - ProcessFetchedPromotions( - ledger::Result::LEDGER_ERROR, - std::move(list), - callback); + if (!list) { + callback(ledger::Result::LEDGER_ERROR, {}); return; } - // even though that some promotions are corrupted - // we should display non corrupted ones either way - if (result == ledger::Result::CORRUPTED_DATA) { - BLOG(0, "Promotions are not correct: " - << base::JoinString(corrupted_promotions, ", ")); - } - ledger::PromotionList promotions_ui; - - for (const auto& item : list) { + for (const auto& item : *list) { auto it = promotions.find(item->id); if (it != promotions.end()) { const auto status = it->second->status; @@ -258,7 +239,7 @@ void Promotion::OnGetAllPromotions( } bool found = - std::any_of(list.begin(), list.end(), [&promotion](auto& item) { + std::any_of(list->begin(), list->end(), [&promotion](auto& item) { return item->id == promotion.second->id; }); @@ -716,35 +697,19 @@ void Promotion::CorruptedPromotions( return; } - base::Value body(base::Value::Type::DICTIONARY); - body.SetKey("claimIds", std::move(corrupted_claims)); - - std::string json; - base::JSONWriter::Write(body, &json); - - const std::string url = braveledger_request_util::ReportClobberedClaimsUrl(); - auto url_callback = std::bind(&Promotion::OnCheckForCorrupted, this, _1, ids); - ledger_->LoadURL( - url, - {}, - json, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, + promotion_server_->post_clobbered_claims()->Request( + std::move(corrupted_claims), url_callback); } void Promotion::OnCheckForCorrupted( - const ledger::UrlResponse& response, + const ledger::Result result, const std::vector& promotion_id_list) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const ledger::Result result = - braveledger_response_util::CheckCorruptedPromotions(response); if (result != ledger::Result::LEDGER_OK) { BLOG(0, "Failed to parse corrupted promotions response"); return; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.h b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.h index 78940b71e520..0df3959f7e50 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion.h @@ -16,6 +16,7 @@ #include "bat/ledger/mojom_structs.h" #include "bat/ledger/internal/attestation/attestation_impl.h" #include "bat/ledger/internal/credentials/credentials_factory.h" +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" namespace bat_ledger { class LedgerImpl; @@ -50,12 +51,14 @@ class Promotion { private: void OnFetch( - const ledger::UrlResponse& response, + const ledger::Result result, + ledger::PromotionList list, + const std::vector& corrupted_promotions, ledger::FetchPromotionCallback callback); void OnGetAllPromotions( ledger::PromotionMap promotions, - const ledger::UrlResponse& response, + std::shared_ptr list, ledger::FetchPromotionCallback callback); void OnGetAllPromotionsFromDatabase( @@ -127,7 +130,7 @@ class Promotion { const std::vector& ids); void OnCheckForCorrupted( - const ledger::UrlResponse& response, + const ledger::Result result, const std::vector& promotion_id_list); void ErrorStatusSaved( @@ -140,9 +143,10 @@ class Promotion { void OnLastCheckTimerElapsed(); - std::unique_ptr attestation_; + std::unique_ptr attestation_; std::unique_ptr transfer_; std::unique_ptr credentials_; + std::unique_ptr promotion_server_; bat_ledger::LedgerImpl* ledger_; // NOT OWNED base::OneShotTimer last_check_timer_; base::OneShotTimer retry_timer_; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.cc index aef4b6eaeb11..3556927fc98c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.cc @@ -3,16 +3,26 @@ * 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/ledger_impl.h" #include "bat/ledger/internal/recovery/recovery.h" -#include "bat/ledger/internal/recovery/recovery_empty_balance.h" -namespace braveledger_recovery { +namespace ledger { +namespace recovery { -void Check(bat_ledger::LedgerImpl* ledger) { - if (!ledger->state()->GetEmptyBalanceChecked()) { +Recovery::Recovery(bat_ledger::LedgerImpl* ledger): + ledger_(ledger), + empty_balance_(std::make_unique(ledger)) { + DCHECK(ledger_); +} + +Recovery::~Recovery() = default; + +void Recovery::Check() { + if (!ledger_->state()->GetEmptyBalanceChecked()) { BLOG(1, "Running empty balance check...") - EmptyBalance::Check(ledger); + empty_balance_->Check(); } } -} // namespace braveledger_recovery +} // namespace recovery +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.h b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.h index 198a09bc8c6b..d3c8f08f9b7d 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery.h @@ -6,12 +6,30 @@ #ifndef BRAVELEDGER_RECOVERY_RECOVERY_H_ #define BRAVELEDGER_RECOVERY_RECOVERY_H_ -#include "bat/ledger/internal/ledger_impl.h" +#include -namespace braveledger_recovery { +#include "bat/ledger/internal/recovery/recovery_empty_balance.h" -void Check(bat_ledger::LedgerImpl* ledger); +namespace bat_ledger { +class LedgerImpl; +} -} // namespace braveledger_recovery +namespace ledger { +namespace recovery { + +class Recovery { + public: + explicit Recovery(bat_ledger::LedgerImpl* ledger); + ~Recovery(); + + void Check(); + + private: + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr empty_balance_; +}; + +} // namespace recovery +} // namespace ledger #endif // BRAVELEDGER_RECOVERY_RECOVERY_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc index ee3afb4f7b0b..0c09b2a5a665 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.cc @@ -9,9 +9,8 @@ #include "base/strings/stringprintf.h" #include "bat/ledger/internal/credentials/credentials_util.h" +#include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/recovery/recovery_empty_balance.h" -#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; @@ -22,27 +21,31 @@ const int32_t kVersion = 1; } // namespace -namespace braveledger_recovery { +namespace ledger { +namespace recovery { -void EmptyBalance::Check(bat_ledger::LedgerImpl* ledger) { - auto get_callback = std::bind( - &EmptyBalance::OnAllContributions, - _1, - ledger); +EmptyBalance::EmptyBalance(bat_ledger::LedgerImpl* ledger): + ledger_(ledger), + promotion_server_(std::make_unique(ledger)) { + DCHECK(ledger_); +} + +EmptyBalance::~EmptyBalance() = default; - ledger->database()->GetAllContributions(get_callback); +void EmptyBalance::Check() { + auto get_callback = std::bind(&EmptyBalance::OnAllContributions, this, _1); + ledger_->database()->GetAllContributions(get_callback); } -void EmptyBalance::OnAllContributions( - ledger::ContributionInfoList list, - bat_ledger::LedgerImpl* ledger) { +void EmptyBalance::OnAllContributions(ledger::ContributionInfoList list) { // we can just restore all tokens if no contributions if (list.empty()) { - auto get_callback = std::bind(&EmptyBalance::GetCredsByPromotions, - _1, - ledger); + auto get_callback = std::bind( + &EmptyBalance::GetCredsByPromotions, + this, + _1); - GetPromotions(ledger, get_callback); + GetPromotions(get_callback); return; } @@ -56,21 +59,20 @@ void EmptyBalance::OnAllContributions( BLOG(1, "Contribution SUM: " << contribution_sum); auto get_callback = std::bind(&EmptyBalance::GetAllTokens, + this, _1, - ledger, contribution_sum); - GetPromotions(ledger, get_callback); + GetPromotions(get_callback); } -void EmptyBalance::GetPromotions( - bat_ledger::LedgerImpl* ledger, - ledger::GetPromotionListCallback callback) { +void EmptyBalance::GetPromotions(ledger::GetPromotionListCallback callback) { auto get_callback = std::bind(&EmptyBalance::OnPromotions, + this, _1, callback); - ledger->database()->GetAllPromotions(get_callback); + ledger_->database()->GetAllPromotions(get_callback); } void EmptyBalance::OnPromotions( @@ -92,27 +94,21 @@ void EmptyBalance::OnPromotions( callback(std::move(list)); } -void EmptyBalance::GetCredsByPromotions( - ledger::PromotionList list, - bat_ledger::LedgerImpl* ledger) { +void EmptyBalance::GetCredsByPromotions(ledger::PromotionList list) { std::vector promotion_ids; for (auto& promotion : list) { promotion_ids.push_back(promotion->id); } - auto get_callback = std::bind(&EmptyBalance::OnCreds, - _1, - ledger); + auto get_callback = std::bind(&EmptyBalance::OnCreds, this, _1); - ledger->database()->GetCredsBatchesByTriggers(promotion_ids, get_callback); + ledger_->database()->GetCredsBatchesByTriggers(promotion_ids, get_callback); } -void EmptyBalance::OnCreds( - ledger::CredsBatchList list, - bat_ledger::LedgerImpl* ledger) { +void EmptyBalance::OnCreds(ledger::CredsBatchList list) { if (list.empty()) { BLOG(1, "Creds batch list is emtpy"); - ledger->state()->SetEmptyBalanceChecked(true); + ledger_->state()->SetEmptyBalanceChecked(true); return; } @@ -147,29 +143,24 @@ void EmptyBalance::OnCreds( if (token_list.empty()) { BLOG(1, "Unblinded token list is emtpy"); - ledger->state()->SetEmptyBalanceChecked(true); + ledger_->state()->SetEmptyBalanceChecked(true); return; } - auto save_callback = std::bind(&EmptyBalance::OnSaveUnblindedCreds, - _1, - ledger); + auto save_callback = std::bind(&EmptyBalance::OnSaveUnblindedCreds, this, _1); - ledger->database()->SaveUnblindedTokenList( + ledger_->database()->SaveUnblindedTokenList( std::move(token_list), save_callback); } -void EmptyBalance::OnSaveUnblindedCreds( - const ledger::Result result, - bat_ledger::LedgerImpl* ledger) { +void EmptyBalance::OnSaveUnblindedCreds(const ledger::Result result) { BLOG(1, "Finished empty balance migration with result: " << result); - ledger->state()->SetEmptyBalanceChecked(true); + ledger_->state()->SetEmptyBalanceChecked(true); } void EmptyBalance::GetAllTokens( ledger::PromotionList list, - bat_ledger::LedgerImpl* ledger, const double contribution_sum) { // from all completed promotions get creds // unblind them and save them @@ -181,19 +172,18 @@ void EmptyBalance::GetAllTokens( BLOG(1, "Promotion SUM: " << promotion_sum); auto tokens_callback = std::bind(&EmptyBalance::ReportResults, + this, _1, - ledger, contribution_sum, promotion_sum); - ledger->database()->GetSpendableUnblindedTokensByBatchTypes( + ledger_->database()->GetSpendableUnblindedTokensByBatchTypes( {ledger::CredsBatchType::PROMOTION}, tokens_callback); } void EmptyBalance::ReportResults( ledger::UnblindedTokenList list, - bat_ledger::LedgerImpl* ledger, const double contribution_sum, const double promotion_sum) { double tokens_sum = 0.0; @@ -206,55 +196,28 @@ void EmptyBalance::ReportResults( if (total <= 0) { BLOG(1, "Unblinded token total is OK"); - ledger->state()->SetEmptyBalanceChecked(true); + ledger_->state()->SetEmptyBalanceChecked(true); return; } BLOG(1, "Unblinded token total is " << total); - const std::string json = base::StringPrintf( - R"({"amount": %f})", - total); + auto url_callback = std::bind(&EmptyBalance::Sent, this, _1); - const std::string payment_id = ledger->state()->GetPaymentId(); - auto url_callback = std::bind(&EmptyBalance::Sent, - _1, - ledger); - - const std::string header_url = base::StringPrintf( - "post /v1/wallets/%s/events/batloss/%d", - payment_id.c_str(), - kVersion); - - const auto headers = braveledger_request_util::BuildSignHeaders( - header_url, - json, - payment_id, - ledger->state()->GetRecoverySeed()); - - const std::string url = braveledger_request_util::GetBatlossURL( - payment_id, - kVersion); - ledger->LoadURL( - url, - headers, - json, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, + promotion_server_->post_bat_loss()->Request( + total, + kVersion, url_callback); } -void EmptyBalance::Sent( - const ledger::UrlResponse& response, - bat_ledger::LedgerImpl* ledger) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - if (response.status_code != net::HTTP_OK) { +void EmptyBalance::Sent(const ledger::Result result) { + if (result != ledger::Result::LEDGER_OK) { return; } BLOG(1, "Finished empty balance migration!"); - ledger->state()->SetEmptyBalanceChecked(true); + ledger_->state()->SetEmptyBalanceChecked(true); } -} // namespace braveledger_recovery +} // namespace recovery +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.h b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.h index e4ed521ae387..821daeac098e 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/recovery/recovery_empty_balance.h @@ -6,55 +6,55 @@ #ifndef BRAVELEDGER_RECOVERY_RECOVERY_EMPTY_BALANCE_H_ #define BRAVELEDGER_RECOVERY_RECOVERY_EMPTY_BALANCE_H_ -#include "bat/ledger/internal/ledger_impl.h" +#include -namespace braveledger_recovery { +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" + +namespace bat_ledger { +class LedgerImpl; +} + +namespace ledger { +namespace recovery { class EmptyBalance { public: - static void Check(bat_ledger::LedgerImpl* ledger); + explicit EmptyBalance(bat_ledger::LedgerImpl* ledger); + ~EmptyBalance(); + + void Check(); private: - static void OnAllContributions( - ledger::ContributionInfoList list, - bat_ledger::LedgerImpl* ledger); + void OnAllContributions(ledger::ContributionInfoList list); - static void GetPromotions( - bat_ledger::LedgerImpl* ledger, - ledger::GetPromotionListCallback callback); + void GetPromotions(ledger::GetPromotionListCallback callback); - static void OnPromotions( + void OnPromotions( ledger::PromotionMap promotions, ledger::GetPromotionListCallback callback); - static void GetCredsByPromotions( - ledger::PromotionList list, - bat_ledger::LedgerImpl* ledger); + void GetCredsByPromotions(ledger::PromotionList list); - static void OnCreds( - ledger::CredsBatchList list, - bat_ledger::LedgerImpl* ledger); + void OnCreds(ledger::CredsBatchList list); - static void OnSaveUnblindedCreds( - const ledger::Result result, - bat_ledger::LedgerImpl* ledger); + void OnSaveUnblindedCreds(const ledger::Result result); - static void GetAllTokens( + void GetAllTokens( ledger::PromotionList list, - bat_ledger::LedgerImpl* ledger, const double contribution_sum); - static void ReportResults( + void ReportResults( ledger::UnblindedTokenList list, - bat_ledger::LedgerImpl* ledger, const double contribution_sum, const double promotion_sum); - static void Sent( - const ledger::UrlResponse& response, - bat_ledger::LedgerImpl* ledger); + void Sent(const ledger::Result result); + + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr promotion_server_; }; -} // namespace braveledger_recovery +} // namespace recovery +} // namespace ledger #endif // BRAVELEDGER_RECOVERY_RECOVERY_EMPTY_BALANCE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_attestation.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_attestation.cc deleted file mode 100644 index ee155bfd49c1..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_attestation.cc +++ /dev/null @@ -1,61 +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 "base/strings/stringprintf.h" -#include "bat/ledger/internal/static_values.h" -#include "bat/ledger/internal/request/request_attestation.h" -#include "bat/ledger/internal/request/request_util.h" - -namespace braveledger_request_util { - -std::string GetStartAttestationDesktopUrl() { - return BuildUrl("/captchas", PREFIX_V1, ServerTypes::kPromotion); -} - -std::string GetCaptchaUrl(const std::string& captcha_id) { - const std::string path = base::StringPrintf( - "/captchas/%s.png", - captcha_id.c_str()); - return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); -} - -std::string GetClaimAttestationDesktopUrl(const std::string& captcha_id) { - const std::string path = base::StringPrintf( - "/captchas/%s", - captcha_id.c_str()); - return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); -} - -std::string GetStartAttestationAndroidUrl() { - return BuildUrl( - "/attestations/safetynet", - PREFIX_V2, - ServerTypes::kPromotion); -} - -std::string GetConfirmAttestationAndroidUrl(const std::string& nonce) { - const std::string path = base::StringPrintf( - "/attestations/safetynet/%s", - nonce.c_str()); - return BuildUrl(path, PREFIX_V2, ServerTypes::kPromotion); -} - -std::string GetStartAttestationIOSUrl() { - return BuildUrl( - "/devicecheck/attestations", - PREFIX_V1, - ServerTypes::kPromotion); -} - -std::string GetConfirmAttestationIOSUrl(const std::string& nonce) { - const std::string path = base::StringPrintf( - "/devicecheck/attestations/%s", - nonce.c_str()); - return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); -} - -} // namespace braveledger_request_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_attestation.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_attestation.h deleted file mode 100644 index 04a6afe14d36..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_attestation.h +++ /dev/null @@ -1,29 +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_COMMON_ATTESTATION_REQUESTS_H_ -#define BRAVELEDGER_COMMON_ATTESTATION_REQUESTS_H_ - -#include - -namespace braveledger_request_util { - -std::string GetStartAttestationDesktopUrl(); - -std::string GetCaptchaUrl(const std::string& captcha_id); - -std::string GetClaimAttestationDesktopUrl(const std::string& captcha_id); - -std::string GetConfirmAttestationAndroidUrl(const std::string& nonce); - -std::string GetStartAttestationAndroidUrl(); - -std::string GetStartAttestationIOSUrl(); - -std::string GetConfirmAttestationIOSUrl(const std::string& nonce); - -} // namespace braveledger_request_util - -#endif // BRAVELEDGER_COMMON_ATTESTATION_REQUESTS_H_ 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 deleted file mode 100644 index c5c0a8ec411f..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.cc +++ /dev/null @@ -1,97 +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 "base/strings/stringprintf.h" -#include "bat/ledger/internal/static_values.h" -#include "bat/ledger/internal/request/request_promotion.h" -#include "bat/ledger/internal/request/request_util.h" - -namespace braveledger_request_util { - -std::string GetFetchPromotionUrl( - const std::string& payment_id, - const std::string& platform) { - const std::string& arguments = base::StringPrintf( - "migrate=true&paymentId=%s&platform=%s", - payment_id.c_str(), - platform.c_str()); - - const std::string& path = base::StringPrintf( - "/promotions?%s", - arguments.c_str()); - - return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); -} - -std::string ClaimCredsUrl(const std::string& promotion_id) { - const std::string& path = base::StringPrintf( - "/promotions/%s", - promotion_id.c_str()); - return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); -} - -std::string FetchSignedCredsUrl( - const std::string& promotion_id, - const std::string& claim_id) { - const std::string& path = base::StringPrintf( - "/promotions/%s/claims/%s", - promotion_id.c_str(), - claim_id.c_str()); - return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); -} - -std::string GetRedeemTokensUrl() { - return BuildUrl("/suggestions", PREFIX_V1, ServerTypes::kPromotion); -} - -std::string ReportClobberedClaimsUrl() { - return BuildUrl( - "/promotions/reportclobberedclaims", - PREFIX_V2, - ServerTypes::kPromotion); -} - -std::string GetTransferTokens() { - return BuildUrl("/suggestions/claim", PREFIX_V1, ServerTypes::kPromotion); -} - -std::string GetBatlossURL( - const std::string& payment_id, - const int32_t version) { - const std::string& path = base::StringPrintf( - "/wallets/%s/events/batloss/%d", - payment_id.c_str(), - version); - return BuildUrl(path, PREFIX_V1, ServerTypes::kPromotion); -} - -std::string GetCreateWalletURL() { - return BuildUrl("/wallet/brave", PREFIX_V3, ServerTypes::kPromotion); -} - -std::string GetRecoverWalletURL(const std::string& public_key) { - const std::string& path = base::StringPrintf( - "/wallet/recover/%s", - public_key.c_str()); - return BuildUrl(path, PREFIX_V3, ServerTypes::kPromotion); -} - -std::string GetClaimWalletURL(const std::string& payment_id) { - const std::string& path = base::StringPrintf( - "/wallet/uphold/%s/claim", - payment_id.c_str()); - return BuildUrl(path, PREFIX_V3, ServerTypes::kPromotion); -} - -std::string GetBalanceWalletURL(const std::string& payment_id) { - const std::string path = base::StringPrintf( - "/wallet/uphold/%s", - payment_id.c_str()); - return BuildUrl(path, PREFIX_V3, ServerTypes::kPromotion); -} - -} // namespace braveledger_request_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h deleted file mode 100644 index 4ee5b6b40b45..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_promotion.h +++ /dev/null @@ -1,42 +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_COMMON_PROMOTION_REQUESTS_H_ -#define BRAVELEDGER_COMMON_PROMOTION_REQUESTS_H_ - -#include -#include "bat/ledger/mojom_structs.h" - -namespace braveledger_request_util { - -std::string GetFetchPromotionUrl( - const std::string& payment_id, - const std::string& platform); - -std::string ClaimCredsUrl(const std::string& promotion_id); - -std::string FetchSignedCredsUrl( - const std::string& promotion_id, - const std::string& claim_id); - -std::string GetRedeemTokensUrl(); - -std::string ReportClobberedClaimsUrl(); - -std::string GetTransferTokens(); - -std::string GetBatlossURL(const std::string& payment_id, const int32_t version); - -std::string GetCreateWalletURL(); - -std::string GetRecoverWalletURL(const std::string& public_key); - -std::string GetClaimWalletURL(const std::string& payment_id); - -std::string GetBalanceWalletURL(const std::string& payment_id); - -} // namespace braveledger_request_util - -#endif // BRAVELEDGER_COMMON_PROMOTION_REQUESTS_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.cc index b8fcb3504577..443437d8fe0c 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 @@ -18,12 +18,6 @@ const char kStaging[] = "https://rewards-stg.bravesoftware.com"; const char kProduction[] = "https://rewards.brave.com"; } // namespace publisher -namespace promotion { -const char kDevelopment[] = "https://grant.rewards.brave.software"; -const char kStaging[] = "https://grant.rewards.bravesoftware.com"; -const char kProduction[] = "https://grant.rewards.brave.com"; -} // namespace promotion - namespace payment { const char kDevelopment[] = "https://payment.rewards.brave.software"; const char kStaging[] = "http://payment.rewards.bravesoftware.com"; @@ -53,23 +47,6 @@ std::string BuildPublisherUrl() { return url; } -std::string BuildPromotionUrl() { - std::string url; - switch (ledger::_environment) { - case ledger::Environment::DEVELOPMENT: - url = promotion::kDevelopment; - break; - case ledger::Environment::STAGING: - url = promotion::kStaging; - break; - case ledger::Environment::PRODUCTION: - url = promotion::kProduction; - break; - } - - return url; -} - std::string BuildPaymentsUrl() { std::string url; switch (ledger::_environment) { @@ -114,10 +91,6 @@ std::string BuildUrl( url = BuildPublisherUrl(); break; } - case ServerTypes::kPromotion: { - url = BuildPromotionUrl(); - break; - } case ServerTypes::kPayments: { url = BuildPaymentsUrl(); break; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h index 2559dd948a98..31e1ea18208f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/request/request_util.h @@ -14,7 +14,6 @@ namespace braveledger_request_util { enum class ServerTypes { kPublisher, - kPromotion, kPayments, kPrivateCDN }; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_attestation.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_attestation.cc deleted file mode 100644 index d76743a83469..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_attestation.cc +++ /dev/null @@ -1,190 +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 "bat/ledger/internal/response/response_attestation.h" - -#include "base/base64.h" -#include "base/json/json_reader.h" -#include "base/strings/stringprintf.h" -#include "bat/ledger/internal/logging.h" -#include "net/http/http_status_code.h" - -namespace braveledger_response_util { - -// Request Url: -// POST /v1/attestations/safetynet (Android) -// POST /v1/devicecheck/attestations (ios) -// -// Success: -// OK (200) -// -// Response Format: -// {Empty body} - -ledger::Result CheckStartAttestation(const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } - - // Unauthorized (401) - if (response.status_code == net::HTTP_UNAUTHORIZED) { - BLOG(0, "Invalid token"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - return ledger::Result::LEDGER_OK; -} - -// Request Url: -// POST /v1/captchas (Desktop) -// -// Success: -// OK (200) -// -// Response Format: -// { -// "hint": "circle", -// "captchaId": "d155d2d2-2627-425b-9be8-44ae9f541762" -// } - -ledger::Result ParseCaptcha( - const ledger::UrlResponse& response, - base::Value* result) { - DCHECK(result); - - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - base::Optional value = base::JSONReader::Read(response.body); - if (!value || !value->is_dict()) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - const auto* captcha_id = dictionary->FindStringKey("captchaId"); - if (!captcha_id) { - BLOG(0, "Captcha id is wrong"); - return ledger::Result::LEDGER_ERROR; - } - - const auto* hint = dictionary->FindStringKey("hint"); - if (!hint) { - BLOG(0, "Hint is wrong"); - return ledger::Result::LEDGER_ERROR; - } - - result->SetStringKey("hint", *hint); - result->SetStringKey("captchaId", *captcha_id); - - return ledger::Result::LEDGER_OK; -} - -// Request Url: -// GET /v1/captchas/{captcha_id}.png -// -// Success: -// OK (200) -// -// Response Format: -// {PNG data} - -ledger::Result ParseCaptchaImage( - const ledger::UrlResponse& response, - std::string* encoded_image) { - DCHECK(encoded_image); - - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid captcha id"); - return ledger::Result::LEDGER_ERROR; - } - - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized captcha id"); - return ledger::Result::NOT_FOUND; - } - - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Failed to generate the captcha image"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - base::Base64Encode(response.body, encoded_image); - *encoded_image = - base::StringPrintf("data:image/jpeg;base64,%s", encoded_image->c_str()); - - return ledger::Result::LEDGER_OK; -} - -// Request Url: -// PUT /v1/captchas/{captcha_id} (Desktop) -// POST /v2/attestations/safetynet/{nonce} (Android) -// POST /v1/devicecheck/attestations/{nonce} (ios) -// -// Success: -// OK (200) -// -// Response Format (success): -// {Empty body} -// -// Response Format (error): -// { -// "message": "Error solving captcha", -// "code": 401 -// } - -ledger::Result CheckConfirmAttestation( - const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::CAPTCHA_FAILED; - } - - // Unauthorized (401) - if (response.status_code == net::HTTP_UNAUTHORIZED) { - BLOG(0, "Invalid solution"); - return ledger::Result::CAPTCHA_FAILED; - } - - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Failed to verify captcha solution"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - return ledger::Result::LEDGER_OK; -} - -} // namespace braveledger_response_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_attestation.h b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_attestation.h deleted file mode 100644 index 7a658d76087f..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_attestation.h +++ /dev/null @@ -1,31 +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/. */ - -#ifndef BRAVELEDGER_RESPONSE_RESPONSE_ATTESTATION_H_ -#define BRAVELEDGER_RESPONSE_RESPONSE_ATTESTATION_H_ - -#include - -#include "base/values.h" -#include "bat/ledger/mojom_structs.h" - -namespace braveledger_response_util { - -ledger::Result CheckStartAttestation(const ledger::UrlResponse& response); - -ledger::Result ParseCaptcha( - const ledger::UrlResponse& response, - base::Value* result); - -ledger::Result ParseCaptchaImage( - const ledger::UrlResponse& response, - std::string* encoded_image); - -ledger::Result CheckConfirmAttestation( - const ledger::UrlResponse& response); - -} // namespace braveledger_response_util - -#endif // BRAVELEDGER_RESPONSE_RESPONSE_ATTESTATION_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_promotion.h b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_promotion.h deleted file mode 100644 index ccb41d7a170d..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_promotion.h +++ /dev/null @@ -1,33 +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/. */ - -#ifndef BRAVELEDGER_RESPONSE_RESPONSE_PROMOTION_H_ -#define BRAVELEDGER_RESPONSE_RESPONSE_PROMOTION_H_ - -#include -#include - -#include "bat/ledger/mojom_structs.h" - -namespace braveledger_response_util { - -ledger::Result ParseClaimCreds( - const ledger::UrlResponse& response, - std::string* claim_id); - -ledger::Result CheckFetchPromotions(const ledger::UrlResponse& response); - -ledger::Result ParseFetchPromotions( - const ledger::UrlResponse& response, - ledger::PromotionList* list, - std::vector* corrupted_promotions); - -ledger::Result CheckCorruptedPromotions(const ledger::UrlResponse& response); - -ledger::Result CheckRedeemTokens(const ledger::UrlResponse& response); - -} // namespace braveledger_response_util - -#endif // BRAVELEDGER_RESPONSE_RESPONSE_PROMOTION_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc deleted file mode 100644 index db4e1cc6a4c7..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.cc +++ /dev/null @@ -1,248 +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 "bat/ledger/internal/response/response_wallet.h" - -#include - -#include "base/json/json_reader.h" -#include "base/strings/string_number_conversions.h" -#include "base/values.h" -#include "bat/ledger/global_constants.h" -#include "bat/ledger/internal/logging.h" -#include "net/http/http_status_code.h" - -namespace braveledger_response_util { - -// Request Url: -// POST /v3/wallet/brave -// -// Success: -// OK (201) -// -// Response Format: -// { -// "paymentId": "37742974-3b80-461a-acfb-937e105e5af4", -// "walletProvider": { -// "id": "", -// "name": "brave" -// }, -// "altcurrency": "BAT", -// "publicKey": "90035db3b131044c7c845bfa987946258ef4dc947ba" -// } - -ledger::Result ParseCreateWallet( - const ledger::UrlResponse& response, - std::string* payment_id) { - DCHECK(payment_id); - - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } - - // Service Unavailable (503) - if (response.status_code == net::HTTP_SERVICE_UNAVAILABLE) { - BLOG(0, "No conversion rate yet in ratios service"); - return ledger::Result::BAD_REGISTRATION_RESPONSE; - } - - if (response.status_code != net::HTTP_CREATED) { - return ledger::Result::LEDGER_ERROR; - } - - base::Optional value = base::JSONReader::Read(response.body); - if (!value || !value->is_dict()) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - const auto* payment_id_string = dictionary->FindStringKey("paymentId"); - if (!payment_id_string || payment_id_string->empty()) { - BLOG(1, "Payment id is wrong"); - return ledger::Result::LEDGER_ERROR; - } - - *payment_id = *payment_id_string; - - return ledger::Result::LEDGER_OK; -} - -// Request Url: -// GET /v3/wallet/recover/{public_key} -// -// Success: -// OK (200) -// -// Response Format: -// { -// "paymentId": "d59d4b69-f66e-4ee8-9c88-1c522e02ffd3", -// "walletProvider": { -// "id": "a9d12d76-2b6d-4f8b-99df-bb801bff9407", -// "name": "uphold" -// }, -// "altcurrency": "BAT", -// "publicKey": "79d7da2a756cc8d9403d0353a64fae5698e01b44a2c2745" -// } - -ledger::Result ParseRecoverWallet( - const ledger::UrlResponse& response, - std::string* payment_id) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } - - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Not found"); - return ledger::Result::NOT_FOUND; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - base::Optional value = base::JSONReader::Read(response.body); - if (!value || !value->is_dict()) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - BLOG(0, "Invalid JSON"); - return ledger::Result::LEDGER_ERROR; - } - - const auto* payment_id_string = dictionary->FindStringKey("paymentId"); - if (!payment_id_string || payment_id_string->empty()) { - BLOG(0, "Payment id is missing"); - return ledger::Result::LEDGER_ERROR; - } - - *payment_id = *payment_id_string; - return ledger::Result::LEDGER_OK; -} - -// Request Url: -// POST /v3/wallet/uphold/{payment_id}/claim -// -// Success: -// OK (200) -// -// Response Format: -// {Empty body} - -ledger::Result CheckClaimWallet(const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid request"); - return ledger::Result::LEDGER_ERROR; - } - - // Forbidden (403) - if (response.status_code == net::HTTP_FORBIDDEN) { - BLOG(0, "Forbidden"); - return ledger::Result::NOT_FOUND; - } - - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Not found"); - return ledger::Result::LEDGER_ERROR; - } - - // Conflict (409) - if (response.status_code == net::HTTP_CONFLICT) { - BLOG(0, "Not found"); - return ledger::Result::ALREADY_EXISTS; - } - - // Internal Server Error (500) - if (response.status_code == net::HTTP_INTERNAL_SERVER_ERROR) { - BLOG(0, "Internal server error"); - return ledger::Result::LEDGER_ERROR; - } - - if (response.status_code != net::HTTP_OK) { - return ledger::Result::LEDGER_ERROR; - } - - return ledger::Result::LEDGER_OK; -} - -// Request Url: -// GET /v3/wallet/uphold/{payment_id} -// -// Success: -// OK (200) -// -// Response Format: -// { -// "total": 0.0 -// "spendable": 0.0 -// "confirmed": 0.0 -// "unconfirmed": 0.0 -// } - -ledger::BalancePtr ParseWalletBalance(const ledger::UrlResponse& response) { - // Bad Request (400) - if (response.status_code == net::HTTP_BAD_REQUEST) { - BLOG(0, "Invalid payment id"); - return nullptr; - } - - // Not Found (404) - if (response.status_code == net::HTTP_NOT_FOUND) { - BLOG(0, "Unrecognized payment id"); - return nullptr; - } - - // Service Unavailable (503) - if (response.status_code == net::HTTP_SERVICE_UNAVAILABLE) { - BLOG(0, "No conversion rate yet in ratios service"); - return nullptr; - } - - if (response.status_code != net::HTTP_OK) { - return nullptr; - } - - base::Optional value = base::JSONReader::Read(response.body); - if (!value || !value->is_dict()) { - BLOG(0, "Invalid JSON"); - return nullptr; - } - - base::DictionaryValue* dictionary = nullptr; - if (!value->GetAsDictionary(&dictionary)) { - BLOG(0, "Invalid JSON"); - return nullptr; - } - - ledger::BalancePtr balance = ledger::Balance::New(); - - const auto confirmed = dictionary->FindDoubleKey("confirmed"); - if (confirmed) { - balance->total = *confirmed; - } - - balance->user_funds = balance->total; - balance->wallets.insert( - std::make_pair(ledger::kWalletAnonymous, balance->total)); - - return balance; -} - -} // namespace braveledger_response_util diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h deleted file mode 100644 index 27243c11fb25..000000000000 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/response/response_wallet.h +++ /dev/null @@ -1,29 +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/. */ - -#ifndef BRAVELEDGER_RESPONSE_RESPONSE_WALLET_H_ -#define BRAVELEDGER_RESPONSE_RESPONSE_WALLET_H_ - -#include - -#include "bat/ledger/mojom_structs.h" - -namespace braveledger_response_util { - -ledger::Result ParseCreateWallet( - const ledger::UrlResponse& response, - std::string* payment_id); - -ledger::Result ParseRecoverWallet( - const ledger::UrlResponse& response, - std::string* payment_id); - -ledger::Result CheckClaimWallet(const ledger::UrlResponse& response); - -ledger::BalancePtr ParseWalletBalance(const ledger::UrlResponse& response); - -} // namespace braveledger_response_util - -#endif // BRAVELEDGER_RESPONSE_RESPONSE_WALLET_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 e7373fca80ef..b6ccfce57f05 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 @@ -208,7 +208,7 @@ void Uphold::DisconnectWallet() { return; } - wallet = braveledger_wallet::ResetWallet(std::move(wallet)); + wallet = ledger::wallet::ResetWallet(std::move(wallet)); ledger_->ledger_client()->ShowNotification( "wallet_disconnected", diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc index 162f44ccdfc0..9247529c362b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc @@ -16,7 +16,8 @@ #include "wally_bip39.h" // NOLINT -namespace braveledger_wallet { +namespace ledger { +namespace wallet { Wallet::Wallet(bat_ledger::LedgerImpl* ledger) : ledger_(ledger), @@ -216,4 +217,5 @@ void Wallet::DisconnectAllWallets(ledger::ResultCallback callback) { callback(ledger::Result::LEDGER_OK); } -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h index c0e6a580c2d6..9ba2727a0fbf 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h @@ -22,7 +22,8 @@ namespace bat_ledger { class LedgerImpl; } -namespace braveledger_wallet { +namespace ledger { +namespace wallet { class Wallet { public: @@ -67,5 +68,6 @@ class Wallet { std::unique_ptr uphold_; }; -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger #endif // BRAVELEDGER_WALLET_WALLET_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc index fef9d269f5d0..5af96c30aed8 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.cc @@ -12,19 +12,18 @@ #include "bat/ledger/global_constants.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_promotion.h" -#include "bat/ledger/internal/response/response_wallet.h" #include "bat/ledger/internal/static_values.h" -#include "bat/ledger/internal/uphold/uphold.h" using std::placeholders::_1; using std::placeholders::_2; -namespace braveledger_wallet { +namespace ledger { +namespace wallet { WalletBalance::WalletBalance(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), uphold_(std::make_unique(ledger)), - ledger_(ledger) { + promotion_server_(new endpoint::PromotionServer(ledger)) { } WalletBalance::~WalletBalance() = default; @@ -39,31 +38,26 @@ void WalletBalance::Fetch(ledger::FetchBalanceCallback callback) { return; } - const std::string payment_id = ledger_->state()->GetPaymentId(); - if (payment_id.empty()) { + if (ledger_->state()->GetPaymentId().empty()) { BLOG(0, "Payment ID is empty"); callback(ledger::Result::LEDGER_ERROR, nullptr); return; } - const std::string url = braveledger_request_util::GetBalanceWalletURL( - ledger_->state()->GetPaymentId()); - auto load_callback = std::bind(&WalletBalance::OnFetch, this, _1, + _2, callback); - ledger_->LoadURL(url, {}, "", "", ledger::UrlMethod::GET, load_callback); + + promotion_server_->get_wallet_balance()->Request(load_callback); } void WalletBalance::OnFetch( - const ledger::UrlResponse& response, + const ledger::Result result, + ledger::BalancePtr balance, ledger::FetchBalanceCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - ledger::BalancePtr balance = - braveledger_response_util::ParseWalletBalance(response); - if (!balance) { + if (result != ledger::Result::LEDGER_OK || !balance) { BLOG(0, "Couldn't fetch wallet balance"); callback(ledger::Result::LEDGER_ERROR, nullptr); return; @@ -169,4 +163,5 @@ double WalletBalance::GetPerWalletBalance( return 0.0; } -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h index f75ad6c2fa94..d360ee55ea50 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_balance.h @@ -12,17 +12,16 @@ #include #include +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" +#include "bat/ledger/internal/uphold/uphold.h" #include "bat/ledger/ledger.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_uphold { -class Uphold; -} - -namespace braveledger_wallet { +namespace ledger { +namespace wallet { class WalletBalance { public: @@ -37,7 +36,8 @@ class WalletBalance { private: void OnFetch( - const ledger::UrlResponse& response, + const ledger::Result result, + ledger::BalancePtr balance, ledger::FetchBalanceCallback callback); void GetUnblindedTokens( @@ -59,9 +59,11 @@ class WalletBalance { const ledger::Result result, const double balance); - std::unique_ptr uphold_; bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr uphold_; + std::unique_ptr promotion_server_; }; -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger #endif // BRAVELEDGER_WALLET_WALLET_BALANCE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc index 0a43b64e4e07..366e9299a6a1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.cc @@ -13,11 +13,7 @@ #include "base/json/json_writer.h" #include "base/strings/stringprintf.h" #include "base/values.h" -#include "bat/ledger/internal/common/security_helper.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_promotion.h" -#include "bat/ledger/internal/request/request_util.h" -#include "bat/ledger/internal/response/response_wallet.h" #include "bat/ledger/internal/uphold/uphold_util.h" using std::placeholders::_1; @@ -25,63 +21,15 @@ using std::placeholders::_2; namespace { -std::string GeneratePayload( - const std::string& user_funds, - const std::string& address, - const std::vector& seed) { - const std::string amount = user_funds.empty() ? "0" : user_funds; - - base::Value denomination(base::Value::Type::DICTIONARY); - denomination.SetStringKey("amount", amount); - denomination.SetStringKey("currency", "BAT"); - - base::Value octets(base::Value::Type::DICTIONARY); - octets.SetKey("denomination", std::move(denomination)); - octets.SetStringKey("destination", address); - std::string octets_json; - base::JSONWriter::Write(octets, &octets_json); - - const std::string header_digest = - braveledger_helper::Security::DigestValue(octets_json); - - std::vector> headers; - headers.push_back({{"digest", header_digest}}); - - const std::string header_signature = braveledger_helper::Security::Sign( - headers, - "primary", - seed); - - base::Value signed_reqeust(base::Value::Type::DICTIONARY); - signed_reqeust.SetStringKey("octets", octets_json); - signed_reqeust.SetKey("body", std::move(octets)); - - base::Value headers_dict(base::Value::Type::DICTIONARY); - headers_dict.SetStringKey("digest", header_digest); - headers_dict.SetStringKey("signature", header_signature); - signed_reqeust.SetKey("headers", std::move(headers_dict)); - - std::string signed_request_json; - base::JSONWriter::Write(signed_reqeust, &signed_request_json); - - std::string signed_request_base64; - base::Base64Encode(signed_request_json, &signed_request_base64); - - base::Value payload(base::Value::Type::DICTIONARY); - payload.SetStringKey("signedLinkingRequest", signed_request_base64); - std::string json; - base::JSONWriter::Write(payload, &json); - - return json; -} - } // namespace -namespace braveledger_wallet { +namespace ledger { +namespace wallet { WalletClaim::WalletClaim(bat_ledger::LedgerImpl* ledger) : ledger_(ledger), - uphold_(std::make_unique(ledger)) { + uphold_(std::make_unique(ledger)), + promotion_server_(new endpoint::PromotionServer(ledger)) { } WalletClaim::~WalletClaim() = default; @@ -120,50 +68,19 @@ void WalletClaim::OnBalance( return; } - TransferFunds(balance->user_funds, callback); -} - -void WalletClaim::TransferFunds( - const std::string user_funds, - ledger::ResultCallback callback) { - auto wallets = ledger_->ledger_client()->GetExternalWallets(); - auto wallet_ptr = braveledger_uphold::GetWallet(std::move(wallets)); - if (!wallet_ptr) { - BLOG(0, "Wallet is null"); - callback(ledger::Result::LEDGER_ERROR); - return; - } - auto url_callback = std::bind(&WalletClaim::OnTransferFunds, this, _1, callback); - const std::string url = braveledger_request_util::GetClaimWalletURL( - ledger_->state()->GetPaymentId()); - - const std::string payload = GeneratePayload( - user_funds, - wallet_ptr->address, - ledger_->state()->GetRecoverySeed()); - - ledger_->LoadURL( - url, - {}, - payload, - "application/json; charset=utf-8", - ledger::UrlMethod::POST, + promotion_server_->post_claim_uphold()->Request( + balance->user_funds, url_callback); } void WalletClaim::OnTransferFunds( - const ledger::UrlResponse& response, + const ledger::Result result, ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - const auto result = braveledger_response_util::CheckClaimWallet( - response); - if (result == ledger::Result::LEDGER_OK) { ledger_->state()->SetAnonTransferChecked(true); callback(ledger::Result::LEDGER_OK); @@ -179,4 +96,5 @@ void WalletClaim::OnTransferFunds( callback(ledger::Result::LEDGER_ERROR); } -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h index 546ba86f78d0..0d9dd6653b84 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_claim.h @@ -9,14 +9,16 @@ #include #include -#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" #include "bat/ledger/internal/uphold/uphold.h" +#include "bat/ledger/ledger.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_wallet { +namespace ledger { +namespace wallet { class WalletClaim { public: @@ -31,17 +33,15 @@ class WalletClaim { ledger::BalancePtr properties, ledger::ResultCallback callback); - void TransferFunds( - const std::string user_funds, - ledger::ResultCallback callback); - void OnTransferFunds( - const ledger::UrlResponse& response, + const ledger::Result result, ledger::ResultCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED std::unique_ptr uphold_; + std::unique_ptr promotion_server_; }; -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger #endif // BRAVELEDGER_WALLET_WALLET_CLAIM_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc index 37f75bc6c2a4..f40aaff8449e 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.cc @@ -11,66 +11,46 @@ #include "bat/ledger/internal/common/security_helper.h" #include "bat/ledger/internal/common/time_util.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_promotion.h" -#include "bat/ledger/internal/request/request_util.h" -#include "bat/ledger/internal/response/response_wallet.h" using std::placeholders::_1; +using std::placeholders::_2; -namespace braveledger_wallet { +namespace ledger { +namespace wallet { -WalletCreate::WalletCreate(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { +WalletCreate::WalletCreate(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), + promotion_server_(new endpoint::PromotionServer(ledger)) { + DCHECK(ledger_); } WalletCreate::~WalletCreate() = default; void WalletCreate::Start(ledger::ResultCallback callback) { const auto payment_id = ledger_->state()->GetPaymentId(); - const auto stamp = ledger_->state()->GetCreationStamp(); - if (!payment_id.empty() && stamp != 0) { + if (!payment_id.empty()) { BLOG(1, "Wallet already exists"); callback(ledger::Result::WALLET_CREATED); return; } - auto key_info_seed = braveledger_helper::Security::GenerateSeed(); + const auto key_info_seed = braveledger_helper::Security::GenerateSeed(); ledger_->state()->SetRecoverySeed(key_info_seed); - const std::string public_key_hex = - braveledger_helper::Security::GetPublicKeyHexFromSeed(key_info_seed); - auto url_callback = std::bind(&WalletCreate::OnCreate, this, _1, + _2, callback); - const auto headers = braveledger_request_util::BuildSignHeaders( - "post /v3/wallet/brave", - "", - public_key_hex, - ledger_->state()->GetRecoverySeed()); - - const std::string url = braveledger_request_util::GetCreateWalletURL(); - ledger_->LoadURL( - url, - headers, - "", - "application/json; charset=utf-8", - ledger::UrlMethod::POST, - url_callback); + promotion_server_->post_wallet_brave()->Request(url_callback); } void WalletCreate::OnCreate( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& payment_id, ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - std::string payment_id; - const auto result = braveledger_response_util::ParseCreateWallet( - response, - &payment_id); - if (result != ledger::Result::LEDGER_OK) { callback(result); return; @@ -83,6 +63,8 @@ void WalletCreate::OnCreate( ledger_->state()->ResetReconcileStamp(); if (!ledger::is_testing) { ledger_->state()->SetFetchOldBalanceEnabled(false); + ledger_->state()->SetEmptyBalanceChecked(true); + ledger_->state()->SetPromotionCorruptedMigrated(true); } ledger_->state()->SetCreationStamp( braveledger_time_util::GetCurrentTimeStamp()); @@ -98,4 +80,5 @@ void WalletCreate::OnCreate( callback(ledger::Result::WALLET_CREATED); } -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h index 51f7542b99b9..71261e6a89e1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_create.h @@ -8,15 +8,18 @@ #include +#include #include +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" #include "bat/ledger/ledger.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_wallet { +namespace ledger { +namespace wallet { class WalletCreate { public: @@ -27,11 +30,14 @@ class WalletCreate { private: void OnCreate( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& payment_id, ledger::ResultCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr promotion_server_; }; -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger #endif // BRAVELEDGER_WALLET_WALLET_CREATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc index 9378901d006d..38e4351576f4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.cc @@ -11,17 +11,19 @@ #include "base/strings/string_split.h" #include "bat/ledger/internal/common/security_helper.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/request/request_promotion.h" -#include "bat/ledger/internal/request/request_util.h" -#include "bat/ledger/internal/response/response_wallet.h" #include "wally_bip39.h" // NOLINT using std::placeholders::_1; +using std::placeholders::_2; -namespace braveledger_wallet { +namespace ledger { +namespace wallet { -WalletRecover::WalletRecover(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { +WalletRecover::WalletRecover(bat_ledger::LedgerImpl* ledger) : + ledger_(ledger), + promotion_server_(new endpoint::PromotionServer(ledger)) { + DCHECK(ledger_); } WalletRecover::~WalletRecover() = default; @@ -69,31 +71,20 @@ void WalletRecover::Start( auto url_callback = std::bind(&WalletRecover::OnRecover, this, _1, + _2, new_seed, callback); - const std::string url = - braveledger_request_util::GetRecoverWalletURL(public_key_hex); - ledger_->LoadURL( - url, - {}, - "", - "application/json; charset=utf-8", - ledger::UrlMethod::GET, + promotion_server_->get_recover_wallet()->Request( + public_key_hex, url_callback); } void WalletRecover::OnRecover( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& payment_id, const std::vector& new_seed, ledger::ResultCallback callback) { - BLOG(6, ledger::UrlResponseToString(__func__, response)); - - std::string payment_id; - const auto result = braveledger_response_util::ParseRecoverWallet( - response, - &payment_id); - if (result != ledger::Result::LEDGER_OK) { callback(result); return; @@ -108,4 +99,5 @@ void WalletRecover::OnRecover( callback(ledger::Result::LEDGER_OK); } -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h index 4129bf76df84..a974fdd11cbb 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_recover.h @@ -8,16 +8,19 @@ #include +#include #include #include +#include "bat/ledger/internal/endpoint/promotion/promotion_server.h" #include "bat/ledger/ledger.h" namespace bat_ledger { class LedgerImpl; } -namespace braveledger_wallet { +namespace ledger { +namespace wallet { class WalletRecover { public: @@ -30,12 +33,15 @@ class WalletRecover { private: void OnRecover( - const ledger::UrlResponse& response, + const ledger::Result result, + const std::string& payment_id, const std::vector& new_seed, ledger::ResultCallback callback); bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::unique_ptr promotion_server_; }; -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger #endif // BRAVELEDGER_WALLET_WALLET_RECOVER_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc index 32bf71d9e598..cb9042b86c98 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc @@ -7,7 +7,8 @@ #include "bat/ledger/internal/wallet/wallet_util.h" -namespace braveledger_wallet { +namespace ledger { +namespace wallet { ledger::ExternalWalletPtr GetWallet( const std::string& wallet_type, @@ -40,4 +41,5 @@ ledger::ExternalWalletPtr ResetWallet(ledger::ExternalWalletPtr wallet) { return wallet; } -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.h index 194aaa255d57..c11e2f48abb8 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.h @@ -11,7 +11,8 @@ #include "bat/ledger/ledger.h" -namespace braveledger_wallet { +namespace ledger { +namespace wallet { ledger::ExternalWalletPtr GetWallet( const std::string& wallet_type, @@ -19,6 +20,7 @@ ledger::ExternalWalletPtr GetWallet( ledger::ExternalWalletPtr ResetWallet(ledger::ExternalWalletPtr wallet); -} // namespace braveledger_wallet +} // namespace wallet +} // namespace ledger #endif // BRAVELEDGER_WALLET_WALLET_UTIL_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc index 5b9f4111071e..ad409ab23101 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util_unittest.cc @@ -21,28 +21,26 @@ class WalletUtilTest : public testing::Test { TEST(WalletUtilTest, GetWallet) { // no wallets std::map wallets; - auto result = braveledger_wallet::GetWallet("brave", std::move(wallets)); + auto result = ledger::wallet::GetWallet("brave", std::move(wallets)); ASSERT_TRUE(!result); // different wallet auto diff = ledger::ExternalWallet::New(); diff->address = "add1"; wallets.insert(std::make_pair("different", std::move(diff))); - result = - braveledger_wallet::GetWallet(ledger::kWalletUphold, std::move(wallets)); + result = ledger::wallet::GetWallet(ledger::kWalletUphold, std::move(wallets)); ASSERT_TRUE(!result); // uphold wallet auto uphold = ledger::ExternalWallet::New(); uphold->address = "12355"; wallets.insert(std::make_pair(ledger::kWalletUphold, std::move(uphold))); - result = - braveledger_wallet::GetWallet(ledger::kWalletUphold, std::move(wallets)); + result = ledger::wallet::GetWallet(ledger::kWalletUphold, std::move(wallets)); ASSERT_EQ(result->address, "12355"); } TEST(WalletUtilTest, ResetWalletNull) { - auto result = braveledger_wallet::ResetWallet(nullptr); + auto result = ledger::wallet::ResetWallet(nullptr); ASSERT_TRUE(!result); } @@ -54,7 +52,7 @@ TEST(WalletUtilTest, ResetWalletVerifiedWallet) { wallet->one_time_string = "4"; wallet->status = ledger::WalletStatus::VERIFIED; - auto reset_wallet = braveledger_wallet::ResetWallet(std::move(wallet)); + auto reset_wallet = ledger::wallet::ResetWallet(std::move(wallet)); ledger::ExternalWallet expected_wallet; expected_wallet.status = ledger::WalletStatus::DISCONNECTED_VERIFIED; @@ -66,7 +64,7 @@ TEST(WalletUtilTest, ResetWalletNotVerifiedWallet) { auto not_verified = ledger::ExternalWallet::New(); not_verified->status = ledger::WalletStatus::CONNECTED; auto reset_wallet = - braveledger_wallet::ResetWallet(std::move(not_verified)); + ledger::wallet::ResetWallet(std::move(not_verified)); ledger::ExternalWallet expected_wallet; expected_wallet.status = ledger::WalletStatus::DISCONNECTED_NOT_VERIFIED; diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.mm b/vendor/brave-ios/Ledger/BATBraveLedger.mm index dbca240d68c1..874e811e365d 100644 --- a/vendor/brave-ios/Ledger/BATBraveLedger.mm +++ b/vendor/brave-ios/Ledger/BATBraveLedger.mm @@ -957,12 +957,9 @@ - (void)claimPromotion:(NSString *)promotionId publicKey:(NSString *)deviceCheck return; } const auto jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; - ledger->ClaimPromotion(promotionId.UTF8String, jsonString.UTF8String, ^(const ledger::Result result, const std::string& json) { - const auto jsonData = [[NSString stringWithUTF8String:json.c_str()] dataUsingEncoding:NSUTF8StringEncoding]; - NSDictionary *nonce = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil]; + ledger->ClaimPromotion(promotionId.UTF8String, jsonString.UTF8String, ^(const ledger::Result result, const std::string& nonce) { dispatch_async(dispatch_get_main_queue(), ^{ - completion(static_cast(result), - nonce[@"nonce"]); + completion(static_cast(result), [NSString stringWithUTF8String:nonce.c_str()]); }); }); }