diff --git a/test/BUILD.gn b/test/BUILD.gn index 10fca519741c..74872dafa869 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -214,6 +214,22 @@ test("brave_unit_tests") { "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/bat_util_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state_unittest.cc", + "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/test/niceware_partial_unittest.cc", "//brave/vendor/bat-native-ledger/src/bat/ledger/internal/promotion/promotion_unittest.cc", "//brave/components/brave_rewards/browser/database/publisher_info_database_unittest.cc", diff --git a/vendor/bat-native-ledger/BUILD.gn b/vendor/bat-native-ledger/BUILD.gn index 0b452f3ad866..7f0b86e0cd98 100644 --- a/vendor/bat-native-ledger/BUILD.gn +++ b/vendor/bat-native-ledger/BUILD.gn @@ -143,6 +143,40 @@ source_set("ledger") { "src/bat/ledger/internal/promotion/promotion.h", "src/bat/ledger/internal/promotion/promotion_util.cc", "src/bat/ledger/internal/promotion/promotion_util.h", + "src/bat/ledger/internal/properties/ballot_properties.cc", + "src/bat/ledger/internal/properties/ballot_properties.h", + "src/bat/ledger/internal/properties/batch_proof_properties.cc", + "src/bat/ledger/internal/properties/batch_proof_properties.h", + "src/bat/ledger/internal/properties/client_properties.cc", + "src/bat/ledger/internal/properties/client_properties.h", + "src/bat/ledger/internal/properties/current_reconcile_properties.cc", + "src/bat/ledger/internal/properties/current_reconcile_properties.h", + "src/bat/ledger/internal/properties/publisher_properties.cc", + "src/bat/ledger/internal/properties/publisher_properties.h", + "src/bat/ledger/internal/properties/publisher_settings_properties.cc", + "src/bat/ledger/internal/properties/publisher_settings_properties.h", + "src/bat/ledger/internal/properties/publisher_vote_properties.cc", + "src/bat/ledger/internal/properties/publisher_vote_properties.h", + "src/bat/ledger/internal/properties/publisher_votes_properties.cc", + "src/bat/ledger/internal/properties/publisher_votes_properties.h", + "src/bat/ledger/internal/properties/reconcile_direction_properties.cc", + "src/bat/ledger/internal/properties/reconcile_direction_properties.h", + "src/bat/ledger/internal/properties/reconcile_request_properties.cc", + "src/bat/ledger/internal/properties/reconcile_request_properties.h", + "src/bat/ledger/internal/properties/report_balance_properties.cc", + "src/bat/ledger/internal/properties/report_balance_properties.h", + "src/bat/ledger/internal/properties/surveyor_properties.cc", + "src/bat/ledger/internal/properties/surveyor_properties.h", + "src/bat/ledger/internal/properties/transaction_ballot_properties.cc", + "src/bat/ledger/internal/properties/transaction_ballot_properties.h", + "src/bat/ledger/internal/properties/transaction_properties.cc", + "src/bat/ledger/internal/properties/transaction_properties.h", + "src/bat/ledger/internal/properties/unsigned_tx_properties.cc", + "src/bat/ledger/internal/properties/unsigned_tx_properties.h", + "src/bat/ledger/internal/properties/wallet_info_properties.cc", + "src/bat/ledger/internal/properties/wallet_info_properties.h", + "src/bat/ledger/internal/properties/winner_properties.cc", + "src/bat/ledger/internal/properties/winner_properties.h", "src/bat/ledger/internal/publisher/publisher.cc", "src/bat/ledger/internal/publisher/publisher.h", "src/bat/ledger/internal/publisher/publisher_server_list.cc", @@ -154,6 +188,40 @@ source_set("ledger") { "src/bat/ledger/internal/request/request_util.cc", "src/bat/ledger/internal/request/request_util.h", "src/bat/ledger/internal/state_keys.h", + "src/bat/ledger/internal/state/ballot_state.cc", + "src/bat/ledger/internal/state/ballot_state.h", + "src/bat/ledger/internal/state/client_state.cc", + "src/bat/ledger/internal/state/client_state.h", + "src/bat/ledger/internal/state/current_reconcile_state.cc", + "src/bat/ledger/internal/state/current_reconcile_state.h", + "src/bat/ledger/internal/state/publisher_settings_state.cc", + "src/bat/ledger/internal/state/publisher_settings_state.h", + "src/bat/ledger/internal/state/publisher_state.cc", + "src/bat/ledger/internal/state/publisher_state.h", + "src/bat/ledger/internal/state/publisher_vote_state.cc", + "src/bat/ledger/internal/state/publisher_vote_state.h", + "src/bat/ledger/internal/state/publisher_votes_state.cc", + "src/bat/ledger/internal/state/publisher_votes_state.h", + "src/bat/ledger/internal/state/reconcile_direction_state.cc", + "src/bat/ledger/internal/state/reconcile_direction_state.h", + "src/bat/ledger/internal/state/reconcile_request_state.cc", + "src/bat/ledger/internal/state/reconcile_request_state.h", + "src/bat/ledger/internal/state/report_balance_state.cc", + "src/bat/ledger/internal/state/report_balance_state.h", + "src/bat/ledger/internal/state/state_reader.h", + "src/bat/ledger/internal/state/state_writer.h", + "src/bat/ledger/internal/state/surveyor_state.cc", + "src/bat/ledger/internal/state/surveyor_state.h", + "src/bat/ledger/internal/state/transaction_ballot_state.cc", + "src/bat/ledger/internal/state/transaction_ballot_state.h", + "src/bat/ledger/internal/state/transaction_state.cc", + "src/bat/ledger/internal/state/transaction_state.h", + "src/bat/ledger/internal/state/unsigned_tx_state.cc", + "src/bat/ledger/internal/state/unsigned_tx_state.h", + "src/bat/ledger/internal/state/wallet_info_state.cc", + "src/bat/ledger/internal/state/wallet_info_state.h", + "src/bat/ledger/internal/state/wallet_state.cc", + "src/bat/ledger/internal/state/wallet_state.h", "src/bat/ledger/internal/uphold/uphold.h", "src/bat/ledger/internal/uphold/uphold.cc", "src/bat/ledger/internal/uphold/uphold_authorization.h", diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc index 7fa0c48b38c0..2e7028f42739 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.cc @@ -17,1350 +17,28 @@ #include "bat/ledger/internal/rapidjson_bat_helper.h" #include "bat/ledger/internal/static_values.h" #include "bat/ledger/ledger.h" +#include "rapidjson/document.h" +#include "rapidjson/error/en.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" #include "third_party/re2/src/re2/re2.h" #include "tweetnacl.h" // NOLINT #include "url/gurl.h" namespace braveledger_bat_helper { -bool isProbiValid(const std::string& probi) { - // probi shouldn't be longer then 44 - if (probi.length() > 44) { - return false; - } - - // checks if probi only contains numbers - return re2::RE2::FullMatch(probi, "^-?[0-9]*$"); -} - -///////////////////////////////////////////////////////////////////////////// -RECONCILE_PAYLOAD_ST::RECONCILE_PAYLOAD_ST() {} - -RECONCILE_PAYLOAD_ST::~RECONCILE_PAYLOAD_ST() {} - -///////////////////////////////////////////////////////////////////////////// -WALLET_INFO_ST::WALLET_INFO_ST() {} - -WALLET_INFO_ST::WALLET_INFO_ST(const WALLET_INFO_ST& other) { - paymentId_ = other.paymentId_; - addressBAT_ = other.addressBAT_; - addressBTC_ = other.addressBTC_; - addressCARD_ID_ = other.addressCARD_ID_; - addressETH_ = other.addressETH_; - addressLTC_ = other.addressLTC_; - keyInfoSeed_ = other.keyInfoSeed_; -} - -WALLET_INFO_ST::~WALLET_INFO_ST() {} - - -bool WALLET_INFO_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("paymentId") && d["paymentId"].IsString() && - d.HasMember("addressBAT") && d["addressBAT"].IsString() && - d.HasMember("addressBTC") && d["addressBTC"].IsString() && - d.HasMember("addressCARD_ID") && d["addressCARD_ID"].IsString() && - d.HasMember("addressETH") && d["addressETH"].IsString() && - d.HasMember("addressLTC") && d["addressLTC"].IsString() && - d.HasMember("keyInfoSeed") && d["keyInfoSeed"].IsString() ); - } - - if (!error) { - // convert keyInfoSeed and check error - std::string sKeyInfoSeed = d["keyInfoSeed"].GetString(); - error = !getFromBase64(sKeyInfoSeed, &keyInfoSeed_); - } - - if (!error) { - paymentId_ = d["paymentId"].GetString(); - addressBAT_ = d["addressBAT"].GetString(); - addressBTC_ = d["addressBTC"].GetString(); - addressCARD_ID_ = d["addressCARD_ID"].GetString(); - addressETH_ = d["addressETH"].GetString(); - addressLTC_ = d["addressLTC"].GetString(); - } - return !error; -} - -void saveToJson(JsonWriter* writer, const WALLET_INFO_ST& data) { - writer->StartObject(); - - writer->String("paymentId"); - writer->String(data.paymentId_.c_str()); - - writer->String("addressBAT"); - writer->String(data.addressBAT_.c_str()); - - writer->String("addressBTC"); - writer->String(data.addressBTC_.c_str()); - - writer->String("addressCARD_ID"); - writer->String(data.addressCARD_ID_.c_str()); - - writer->String("addressETH"); - writer->String(data.addressETH_.c_str()); - - writer->String("addressLTC"); - writer->String(data.addressLTC_.c_str()); - - writer->String("keyInfoSeed"); - if (data.keyInfoSeed_.size() == 0) { - writer->String(""); - } else { - writer->String(getBase64(data.keyInfoSeed_).c_str()); - } - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -UNSIGNED_TX::UNSIGNED_TX() {} - -UNSIGNED_TX::~UNSIGNED_TX() {} - -///////////////////////////////////////////////////////////////////////////// -TRANSACTION_BALLOT_ST::TRANSACTION_BALLOT_ST() : - offset_(0) {} - -TRANSACTION_BALLOT_ST::~TRANSACTION_BALLOT_ST() {} - -bool TRANSACTION_BALLOT_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("publisher") && d["publisher"].IsString() && - d.HasMember("offset") && d["offset"].IsUint() ); - } - - if (!error) { - publisher_ = d["publisher"].GetString(); - offset_ = d["offset"].GetUint(); - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const TRANSACTION_BALLOT_ST& data) { - writer->StartObject(); - - writer->String("publisher"); - writer->String(data.publisher_.c_str()); - - writer->String("offset"); - writer->Uint(data.offset_); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -TRANSACTION_ST::TRANSACTION_ST(): - votes_(0) {} - -TRANSACTION_ST::TRANSACTION_ST(const TRANSACTION_ST& transaction) { - viewingId_ = transaction.viewingId_; - surveyorId_ = transaction.surveyorId_; - contribution_rates_ = transaction.contribution_rates_; - contribution_probi_ = transaction.contribution_probi_; - submissionStamp_ = transaction.submissionStamp_; - contribution_rates_ = transaction.contribution_rates_; - anonizeViewingId_ = transaction.anonizeViewingId_; - registrarVK_ = transaction.registrarVK_; - masterUserToken_ = transaction.masterUserToken_; - surveyorIds_ = transaction.surveyorIds_; - votes_ = transaction.votes_; - ballots_ = transaction.ballots_; -} - -TRANSACTION_ST::~TRANSACTION_ST() {} - -bool TRANSACTION_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("viewingId") && d["viewingId"].IsString() && - d.HasMember("surveyorId") && d["surveyorId"].IsString() && - d.HasMember("rates") && d["rates"].IsObject() && - d["rates"].HasMember("ETH") && - d["rates"].HasMember("LTC") && - d["rates"].HasMember("BTC") && - d["rates"].HasMember("USD") && - d["rates"].HasMember("EUR") && - d.HasMember("contribution_probi") && d["contribution_probi"].IsString() && - d.HasMember("submissionStamp") && d["submissionStamp"].IsString() && - d.HasMember("anonizeViewingId") && d["anonizeViewingId"].IsString() && - d.HasMember("registrarVK") && d["registrarVK"].IsString() && - d.HasMember("masterUserToken") && d["masterUserToken"].IsString() && - d.HasMember("surveyorIds") && d["surveyorIds"].IsArray() && - d.HasMember("votes") && d["votes"].IsUint() && - d.HasMember("ballots") && d["ballots"].IsArray()); - } - - if (!error) { - viewingId_ = d["viewingId"].GetString(); - surveyorId_ = d["surveyorId"].GetString(); - contribution_probi_ = d["contribution_probi"].GetString(); - submissionStamp_ = d["submissionStamp"].GetString(); - anonizeViewingId_ = d["anonizeViewingId"].GetString(); - registrarVK_ = d["registrarVK"].GetString(); - masterUserToken_ = d["masterUserToken"].GetString(); - votes_ = d["votes"].GetUint(); - - for (auto & i : d["rates"].GetObject()) { - contribution_rates_.insert( - std::make_pair(i.name.GetString(), i.value.GetDouble())); - } - - for (auto & i : d["surveyorIds"].GetArray()) { - surveyorIds_.push_back(i.GetString()); - } - - for (const auto & i : d["ballots"].GetArray()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - - TRANSACTION_BALLOT_ST ballot; - ballot.loadFromJson(sb.GetString()); - ballots_.push_back(ballot); - } - } - - return !error; -} - - -void saveToJson(JsonWriter* writer, const TRANSACTION_ST& data) { - writer->StartObject(); - - writer->String("viewingId"); - writer->String(data.viewingId_.c_str()); - - writer->String("surveyorId"); - writer->String(data.surveyorId_.c_str()); - - writer->String("rates"); - writer->StartObject(); - for (auto & p : data.contribution_rates_) { - writer->String(p.first.c_str()); - writer->Double(p.second); - } - writer->EndObject(); - - writer->String("contribution_probi"); - writer->String(data.contribution_probi_.c_str()); - - writer->String("submissionStamp"); - writer->String(data.submissionStamp_.c_str()); - - writer->String("anonizeViewingId"); - writer->String(data.anonizeViewingId_.c_str()); - - writer->String("registrarVK"); - writer->String(data.registrarVK_.c_str()); - - writer->String("masterUserToken"); - writer->String(data.masterUserToken_.c_str()); - - writer->String("surveyorIds"); - writer->StartArray(); - for (auto & i : data.surveyorIds_) { - writer->String(i.c_str()); - } - writer->EndArray(); - - writer->String("votes"); - writer->Uint(data.votes_); - - writer->String("ballots"); - writer->StartArray(); - for (auto & i : data.ballots_) { - saveToJson(writer, i); - } - writer->EndArray(); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -BALLOT_ST::BALLOT_ST(): - offset_(0), - delayStamp_(0) {} - -BALLOT_ST::BALLOT_ST(const BALLOT_ST& ballot) { - viewingId_ = ballot.viewingId_; - surveyorId_ = ballot.surveyorId_; - publisher_ = ballot.publisher_; - offset_ = ballot.offset_; - prepareBallot_ = ballot.prepareBallot_; - proofBallot_ = ballot.proofBallot_; - delayStamp_ = ballot.delayStamp_; -} - -BALLOT_ST::~BALLOT_ST() {} - -bool BALLOT_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("viewingId") && d["viewingId"].IsString() && - d.HasMember("surveyorId") && d["surveyorId"].IsString() && - d.HasMember("publisher") && d["publisher"].IsString() && - d.HasMember("offset") && d["offset"].IsUint() && - d.HasMember("prepareBallot") && d["prepareBallot"].IsString() && - d.HasMember("delayStamp") && d["delayStamp"].IsUint64() ); - } - - if (!error) { - viewingId_ = d["viewingId"].GetString(); - surveyorId_ = d["surveyorId"].GetString(); - publisher_ = d["publisher"].GetString(); - offset_ = d["offset"].GetUint(); - prepareBallot_ = d["prepareBallot"].GetString(); - delayStamp_ = d["delayStamp"].GetUint64(); - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const BALLOT_ST& data) { - writer->StartObject(); - - writer->String("viewingId"); - writer->String(data.viewingId_.c_str()); - - writer->String("surveyorId"); - writer->String(data.surveyorId_.c_str()); - - writer->String("publisher"); - writer->String(data.publisher_.c_str()); - - writer->String("offset"); - writer->Uint(data.offset_); - - writer->String("prepareBallot"); - writer->String(data.prepareBallot_.c_str()); - - writer->String("delayStamp"); - writer->Uint64(data.delayStamp_); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -BATCH_VOTES_INFO_ST::BATCH_VOTES_INFO_ST() {} - -BATCH_VOTES_INFO_ST::BATCH_VOTES_INFO_ST(const BATCH_VOTES_INFO_ST& other) { - surveyorId_ = other.surveyorId_; - proof_ = other.proof_; -} - -BATCH_VOTES_INFO_ST::~BATCH_VOTES_INFO_ST() {} - -bool BATCH_VOTES_INFO_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // Has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("surveyorId") && d["surveyorId"].IsString() && - d.HasMember("proof") && d["proof"].IsString()); - } - - if (!error) { - surveyorId_ = d["surveyorId"].GetString(); - proof_ = d["proof"].GetString(); - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const BATCH_VOTES_INFO_ST& data) { - writer->StartObject(); - - writer->String("surveyorId"); - writer->String(data.surveyorId_.c_str()); - - writer->String("proof"); - writer->String(data.proof_.c_str()); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -BATCH_VOTES_ST::BATCH_VOTES_ST() {} - -BATCH_VOTES_ST::BATCH_VOTES_ST(const BATCH_VOTES_ST& other) { - publisher_ = other.publisher_; - batchVotesInfo_ = other.batchVotesInfo_; -} - -BATCH_VOTES_ST::~BATCH_VOTES_ST() {} - -bool BATCH_VOTES_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // Has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("publisher") && d["publisher"].IsString() && - d.HasMember("batchVotesInfo") && d["batchVotesInfo"].IsArray()); - } - - if (!error) { - publisher_ = d["publisher"].GetString(); - for (const auto & i : d["batchVotesInfo"].GetArray()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - - BATCH_VOTES_INFO_ST b; - b.loadFromJson(sb.GetString()); - batchVotesInfo_.push_back(b); - } - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const BATCH_VOTES_ST& data) { - writer->StartObject(); - - writer->String("publisher"); - writer->String(data.publisher_.c_str()); - - writer->String("batchVotesInfo"); - writer->StartArray(); - for (auto & b : data.batchVotesInfo_) { - saveToJson(writer, b); - } - writer->EndArray(); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -REPORT_BALANCE_ST::REPORT_BALANCE_ST(): - opening_balance_("0"), - closing_balance_("0"), - deposits_("0"), - grants_("0"), - earning_from_ads_("0"), - auto_contribute_("0"), - recurring_donation_("0"), - one_time_donation_("0"), - total_("0") {} - -REPORT_BALANCE_ST::REPORT_BALANCE_ST(const REPORT_BALANCE_ST& state) { - opening_balance_ = state.opening_balance_; - closing_balance_ = state.closing_balance_; - deposits_ = state.deposits_; - grants_ = state.grants_; - earning_from_ads_ = state.earning_from_ads_; - auto_contribute_ = state.auto_contribute_; - recurring_donation_ = state.recurring_donation_; - one_time_donation_ = state.one_time_donation_; - total_ = state.total_; -} - -REPORT_BALANCE_ST::~REPORT_BALANCE_ST() {} - -bool REPORT_BALANCE_ST::loadFromJson(const std::string& json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("opening_balance") && - d["opening_balance"].IsString() && - isProbiValid(d["opening_balance"].GetString()) && - d.HasMember("closing_balance") && d["closing_balance"].IsString() && - isProbiValid(d["closing_balance"].GetString()) && - d.HasMember("deposits") && d["deposits"].IsString() && - isProbiValid(d["deposits"].GetString()) && - d.HasMember("grants") && d["grants"].IsString() && - isProbiValid(d["grants"].GetString()) && - d.HasMember("earning_from_ads") && d["earning_from_ads"].IsString() && - isProbiValid(d["earning_from_ads"].GetString()) && - d.HasMember("auto_contribute") && d["auto_contribute"].IsString() && - isProbiValid(d["auto_contribute"].GetString()) && - d.HasMember("recurring_donation") && - d["recurring_donation"].IsString() && - isProbiValid(d["recurring_donation"].GetString()) && - d.HasMember("one_time_donation") && d["one_time_donation"].IsString() && - isProbiValid(d["one_time_donation"].GetString()) && - d.HasMember("total") && d["total"].IsString() && - isProbiValid(d["total"].GetString())); - } - - if (!error) { - opening_balance_ = d["opening_balance"].GetString(); - closing_balance_ = d["closing_balance"].GetString(); - deposits_ = d["deposits"].GetString(); - grants_ = d["grants"].GetString(); - earning_from_ads_ = d["earning_from_ads"].GetString(); - auto_contribute_ = d["auto_contribute"].GetString(); - recurring_donation_ = d["recurring_donation"].GetString(); - one_time_donation_ = d["one_time_donation"].GetString(); - total_ = d["total"].GetString(); - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const REPORT_BALANCE_ST& data) { - writer->StartObject(); - - writer->String("opening_balance"); - - writer->String(data.opening_balance_.c_str()); - - writer->String("closing_balance"); - - writer->String(data.closing_balance_.c_str()); - - writer->String("deposits"); - - writer->String(data.deposits_.c_str()); - - writer->String("grants"); - - writer->String(data.grants_.c_str()); - - writer->String("earning_from_ads"); - - writer->String(data.earning_from_ads_.c_str()); - - writer->String("auto_contribute"); - - writer->String(data.auto_contribute_.c_str()); - - writer->String("recurring_donation"); - - writer->String(data.recurring_donation_.c_str()); - - writer->String("one_time_donation"); - - writer->String(data.one_time_donation_.c_str()); - - writer->String("total"); - - writer->String(data.total_.c_str()); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -PUBLISHER_STATE_ST::PUBLISHER_STATE_ST(): - min_publisher_duration_(braveledger_ledger::_default_min_publisher_duration), - min_visits_(1), - allow_non_verified_(true), - allow_videos_(true) {} - -PUBLISHER_STATE_ST::PUBLISHER_STATE_ST(const PUBLISHER_STATE_ST& state) { - min_publisher_duration_ = state.min_publisher_duration_; - min_visits_ = state.min_visits_; - allow_non_verified_ = state.allow_non_verified_; - allow_videos_ = state.allow_videos_; - monthly_balances_ = state.monthly_balances_; - migrate_score_2 = state.migrate_score_2; - processed_pending_publishers = state.processed_pending_publishers; -} - -PUBLISHER_STATE_ST::~PUBLISHER_STATE_ST() {} - -bool PUBLISHER_STATE_ST::loadFromJson(const std::string& json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("min_pubslisher_duration") && - d["min_pubslisher_duration"].IsUint() && - d.HasMember("min_visits") && d["min_visits"].IsUint() && - d.HasMember("allow_non_verified") && d["allow_non_verified"].IsBool() && - d.HasMember("allow_videos") && d["allow_videos"].IsBool() && - d.HasMember("monthly_balances") && d["monthly_balances"].IsArray()); - } - - if (!error) { - min_publisher_duration_ = d["min_pubslisher_duration"].GetUint(); - min_visits_ = d["min_visits"].GetUint(); - allow_non_verified_ = d["allow_non_verified"].GetBool(); - allow_videos_ = d["allow_videos"].GetBool(); - - for (const auto & i : d["monthly_balances"].GetArray()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - - rapidjson::Document d1; - d1.Parse(sb.GetString()); - - rapidjson::Value::ConstMemberIterator itr = d1.MemberBegin(); - if (itr != d1.MemberEnd()) { - rapidjson::StringBuffer sb1; - rapidjson::Writer writer1(sb1); - itr->value.Accept(writer1); - REPORT_BALANCE_ST r; - r.loadFromJson(sb1.GetString()); - monthly_balances_.insert(std::make_pair(itr->name.GetString(), r)); - } - } - - if (d.HasMember("migrate_score_2") && d["migrate_score_2"].IsBool()) { - migrate_score_2 = d["migrate_score_2"].GetBool(); - } else { - migrate_score_2 = true; - } - - if (d.HasMember("processed_pending_publishers") && - d["processed_pending_publishers"].IsArray()) { - for (const auto & i : d["processed_pending_publishers"].GetArray()) { - processed_pending_publishers.push_back(i.GetString()); - } - } - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const PUBLISHER_STATE_ST& data) { - writer->StartObject(); - - writer->String("min_pubslisher_duration"); - writer->Uint(data.min_publisher_duration_); - - writer->String("min_visits"); - writer->Uint(data.min_visits_); - - writer->String("allow_non_verified"); - writer->Bool(data.allow_non_verified_); - - writer->String("allow_videos"); - writer->Bool(data.allow_videos_); - - writer->String("monthly_balances"); - writer->StartArray(); - for (auto & p : data.monthly_balances_) { - writer->StartObject(); - writer->String(p.first.c_str()); - saveToJson(writer, p.second); - writer->EndObject(); - } - writer->EndArray(); - - writer->String("migrate_score_2"); - writer->Bool(data.migrate_score_2); - - writer->String("processed_pending_publishers"); - writer->StartArray(); - for (const auto &p : data.processed_pending_publishers) { - writer->String(p.c_str()); - } - writer->EndArray(); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -PUBLISHER_ST::PUBLISHER_ST(): - id_(""), - duration_(0), - score_(0), - visits_(0), - percent_(0), - weight_(0), - status_(0) {} - -PUBLISHER_ST::~PUBLISHER_ST() {} - -bool PUBLISHER_ST::operator<(const PUBLISHER_ST& rhs) const { - return score_ > rhs.score_; -} - -bool PUBLISHER_ST::loadFromJson(const std::string& json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("id") && d["id"].IsString() && - d.HasMember("duration") && d["duration"].IsUint64() && - d.HasMember("score") && d["score"].IsDouble() && - d.HasMember("visits") && d["visits"].IsUint() && - d.HasMember("percent") && d["percent"].IsUint() && - d.HasMember("weight") && d["weight"].IsDouble()); - } - - if (!error) { - id_ = d["id"].GetString(); - duration_ = d["duration"].GetUint64(); - score_ = d["score"].GetDouble(); - visits_ = d["visits"].GetUint(); - percent_ = d["percent"].GetUint(); - weight_ = d["weight"].GetDouble(); - status_ = 0; // ledger::PublisherStatus::NOT_VERIFIED - - if (d.HasMember("status") && d["status"].IsUint()) { - status_ = d["status"].GetUint(); - } - - // LEGACY CHECK - if (d.HasMember("verified") && d["verified"].IsBool()) { - const bool verified = d["verified"].GetBool(); - status_ = verified - ? 2 // ledger::PublisherStatus::VERIFIED - : 0; // ledger::PublisherStatus::NOT_VERIFIED - } - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const PUBLISHER_ST& data) { - writer->StartObject(); - - writer->String("id"); - writer->String(data.id_.c_str()); - - writer->String("duration"); - writer->Uint64(data.duration_); - - writer->String("score"); - writer->Double(data.score_); - - writer->String("visits"); - writer->Uint(data.visits_); - - writer->String("percent"); - writer->Uint(data.percent_); - - writer->String("weight"); - writer->Double(data.weight_); - - writer->String("status"); - writer->Uint(data.status_); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -WINNERS_ST::WINNERS_ST() : - votes_(0) {} - -WINNERS_ST::~WINNERS_ST() {} - -///////////////////////////////////////////////////////////////////////////// -WALLET_PROPERTIES_ST::WALLET_PROPERTIES_ST() {} - -WALLET_PROPERTIES_ST::~WALLET_PROPERTIES_ST() {} - -WALLET_PROPERTIES_ST::WALLET_PROPERTIES_ST( - const WALLET_PROPERTIES_ST &properties) { - fee_amount_ = properties.fee_amount_; - parameters_choices_ = properties.parameters_choices_; -} - -bool WALLET_PROPERTIES_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("parameters") && d["parameters"].IsObject()); - } - - if (!error) { - for (auto & i : d["parameters"]["adFree"]["choices"]["BAT"].GetArray()) { - parameters_choices_.push_back(i.GetDouble()); - } - - fee_amount_ = d["parameters"]["adFree"]["fee"]["BAT"].GetDouble(); - } - return !error; -} - -void saveToJson(JsonWriter* writer, const WALLET_PROPERTIES_ST& data) { - writer->StartObject(); - - writer->String("fee_amount"); - writer->Double(data.fee_amount_); - - writer->String("parameters"); - writer->StartObject(); - writer->String("adFree"); - writer->StartObject(); - - writer->String("fee"); - writer->StartObject(); - writer->String("BAT"); - writer->Double(data.fee_amount_); - writer->EndObject(); - - writer->String("choices"); - writer->StartObject(); - writer->String("BAT"); - - writer->StartArray(); - for (auto & choice : data.parameters_choices_) { - writer->Double(choice); - } - writer->EndArray(); - writer->EndObject(); - - writer->EndObject(); - writer->EndObject(); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -SURVEYOR_INFO_ST::SURVEYOR_INFO_ST() {} - -SURVEYOR_INFO_ST::~SURVEYOR_INFO_ST() {} - -///////////////////////////////////////////////////////////////////////////// -SURVEYOR_ST::SURVEYOR_ST() {} - -SURVEYOR_ST::~SURVEYOR_ST() {} - -bool SURVEYOR_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("signature") && d["signature"].IsString() && - d.HasMember("surveyorId") && d["surveyorId"].IsString() && - d.HasMember("surveyVK") && d["surveyVK"].IsString() && - d.HasMember("registrarVK") && d["registrarVK"].IsString()); - } - - if (!error) { - signature_ = d["signature"].GetString(); - surveyorId_ = d["surveyorId"].GetString(); - surveyVK_ = d["surveyVK"].GetString(); - registrarVK_ = d["registrarVK"].GetString(); - if (d.HasMember("surveySK") && d["surveySK"].IsString()) { - surveySK_ = d["surveySK"].GetString(); - } - } - - return !error; -} - -///////////////////////////////////////////////////////////////////////////// -RECONCILE_DIRECTION::RECONCILE_DIRECTION() {} -RECONCILE_DIRECTION::RECONCILE_DIRECTION(const std::string& publisher_key, - const double amount_percent) : - publisher_key_(publisher_key), - amount_percent_(amount_percent) {} -RECONCILE_DIRECTION::~RECONCILE_DIRECTION() {} - -bool RECONCILE_DIRECTION::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("publisher_key") && d["publisher_key"].IsString()); - } - - if (!error) { - if (d.HasMember("amount") && d["amount"].IsInt()) { - amount_percent_ = static_cast(d["amount"].GetInt()); - } else if (d["amount_percent"].IsDouble()) { - amount_percent_ = d["amount_percent"].GetDouble(); - } else { - return false; - } - - publisher_key_ = d["publisher_key"].GetString(); - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const RECONCILE_DIRECTION& data) { - writer->StartObject(); - - writer->String("amount_percent"); - writer->Double(data.amount_percent_); - - writer->String("publisher_key"); - writer->String(data.publisher_key_.c_str()); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -CURRENT_RECONCILE::CURRENT_RECONCILE() : - timestamp_(0), - fee_(.0), - retry_step_(ledger::ContributionRetry::STEP_NO), - retry_level_(0) {} - -CURRENT_RECONCILE::CURRENT_RECONCILE(const CURRENT_RECONCILE& data): - viewingId_(data.viewingId_), - anonizeViewingId_(data.anonizeViewingId_), - registrarVK_(data.registrarVK_), - preFlight_(data.preFlight_), - masterUserToken_(data.masterUserToken_), - surveyorInfo_(data.surveyorInfo_), - timestamp_(data.timestamp_), - rates_(data.rates_), - amount_(data.amount_), - currency_(data.currency_), - fee_(data.fee_), - directions_(data.directions_), - type_(data.type_), - retry_step_(data.retry_step_), - retry_level_(data.retry_level_), - destination_(data.destination_), - proof_(data.proof_) {} - -CURRENT_RECONCILE::~CURRENT_RECONCILE() {} - -bool CURRENT_RECONCILE::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("viewingId") && d["viewingId"].IsString() && - d.HasMember("fee") && d["fee"].IsDouble() && - ((d.HasMember("category") && d["category"].IsInt()) || - (d.HasMember("type") && d["type"].IsInt()))); - } - - if (!error) { - viewingId_ = d["viewingId"].GetString(); - anonizeViewingId_ = d["anonizeViewingId"].GetString(); - registrarVK_ = d["registrarVK"].GetString(); - preFlight_ = d["preFlight"].GetString(); - masterUserToken_ = d["masterUserToken"].GetString(); - timestamp_ = d["timestamp"].GetUint64(); - amount_ = d["amount"].GetString(); - currency_ = d["currency"].GetString(); - fee_ = d["fee"].GetDouble(); - if (d.HasMember("category") && d["category"].IsInt()) { - type_ = static_cast(d["category"].GetInt()); - } else { - type_ = static_cast(d["type"].GetInt()); - } - - if (d.HasMember("surveyorInfo") && d["surveyorInfo"].IsObject()) { - auto obj = d["surveyorInfo"].GetObject(); - SURVEYOR_INFO_ST info; - info.surveyorId_ = obj["surveyorId"].GetString(); - surveyorInfo_ = info; - } - - if (d.HasMember("rates") && d["rates"].IsObject()) { - for (auto & i : d["rates"].GetObject()) { - rates_.insert(std::make_pair(i.name.GetString(), i.value.GetDouble())); - } - } - - if (d.HasMember("directions") && d["directions"].IsArray()) { - for (auto & i : d["directions"].GetArray()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - - RECONCILE_DIRECTION direction; - direction.loadFromJson(sb.GetString()); - directions_.push_back(direction); - } - } - - // LEGACY MIGRATION from publisher object - if (d.HasMember("list") && d["list"].IsArray()) { - for (auto &i : d["list"].GetArray()) { - RECONCILE_DIRECTION direction; - - auto obj = i.GetObject(); - direction.publisher_key_ = obj["id"].GetString(); - direction.amount_percent_ = obj["weight"].GetDouble(); - directions_.push_back(direction); - } - } - - if (d.HasMember("retry_step") && d["retry_step"].IsInt()) { - retry_step_ = static_cast( - d["retry_step"].GetInt()); - } else { - retry_step_ = ledger::ContributionRetry::STEP_NO; - } - - if (d.HasMember("retry_level") && d["retry_level"].IsInt()) { - retry_level_ = d["retry_level"].GetInt(); - } else { - retry_level_ = 0; - } - - if (d.HasMember("destination") && d["destination"].IsString()) { - destination_ = d["destination"].GetString(); - } - - if (d.HasMember("proof") && d["proof"].IsString()) { - proof_ = d["proof"].GetString(); - } - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const CURRENT_RECONCILE& data) { - writer->StartObject(); - - writer->String("viewingId"); - writer->String(data.viewingId_.c_str()); - - writer->String("anonizeViewingId"); - writer->String(data.anonizeViewingId_.c_str()); - - writer->String("registrarVK"); - writer->String(data.registrarVK_.c_str()); - - writer->String("preFlight"); - writer->String(data.preFlight_.c_str()); - - writer->String("masterUserToken"); - writer->String(data.masterUserToken_.c_str()); - - writer->String("surveyorInfo"); - writer->StartObject(); - writer->String("surveyorId"); - writer->String(data.surveyorInfo_.surveyorId_.c_str()); - writer->EndObject(); - - writer->String("timestamp"); - writer->Uint64(data.timestamp_); - - writer->String("amount"); - writer->String(data.amount_.c_str()); - - writer->String("currency"); - writer->String(data.currency_.c_str()); - - writer->String("fee"); - writer->Double(data.fee_); - - writer->String("type"); - writer->Int(static_cast(data.type_)); - - writer->String("rates"); - writer->StartObject(); - for (auto & p : data.rates_) { - writer->String(p.first.c_str()); - writer->Double(p.second); - } - writer->EndObject(); - - writer->String("directions"); - writer->StartArray(); - for (auto & i : data.directions_) { - saveToJson(writer, i); - } - writer->EndArray(); - - writer->String("retry_step"); - writer->Int(static_cast(data.retry_step_)); - - writer->String("retry_level"); - writer->Int(data.retry_level_); - - writer->String("destination"); - writer->String(data.destination_.c_str()); - - writer->String("proof"); - writer->String(data.proof_.c_str()); - - writer->EndObject(); -} - -///////////////////////////////////////////////////////////////////////////// -CLIENT_STATE_ST::CLIENT_STATE_ST(): - bootStamp_(0), - reconcileStamp_(0), - settings_(AD_FREE_SETTINGS), - fee_amount_(0), - user_changed_fee_(false), - days_(0), - auto_contribute_(false), - rewards_enabled_(false) {} - -CLIENT_STATE_ST::CLIENT_STATE_ST(const CLIENT_STATE_ST& other) { - walletProperties_ = other.walletProperties_; - walletInfo_ = other.walletInfo_; - bootStamp_ = other.bootStamp_; - reconcileStamp_ = other.reconcileStamp_; - personaId_ = other.personaId_; - userId_ = other.userId_; - registrarVK_ = other.registrarVK_; - masterUserToken_ = other.masterUserToken_; - preFlight_ = other.preFlight_; - fee_currency_ = other.fee_currency_; - settings_ = other.settings_; - fee_amount_ = other.fee_amount_; - user_changed_fee_ = other.user_changed_fee_; - days_ = other.days_; - transactions_ = other.transactions_; - ballots_ = other.ballots_; - ruleset_ = other.ruleset_; - rulesetV2_ = other.rulesetV2_; - batch_ = other.batch_; - auto_contribute_ = other.auto_contribute_; - rewards_enabled_ = other.rewards_enabled_; - current_reconciles_ = other.current_reconciles_; - inline_tip_ = other.inline_tip_; -} - -CLIENT_STATE_ST::~CLIENT_STATE_ST() {} - -bool CLIENT_STATE_ST::loadFromJson(const std::string & json) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser error or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("walletInfo") && d["walletInfo"].IsObject() && - d.HasMember("bootStamp") && d["bootStamp"].IsUint64() && - d.HasMember("reconcileStamp") && d["reconcileStamp"].IsUint64() && - d.HasMember("personaId") && d["personaId"].IsString() && - d.HasMember("userId") && d["userId"].IsString() && - d.HasMember("registrarVK") && d["registrarVK"].IsString() && - d.HasMember("masterUserToken") && d["masterUserToken"].IsString() && - d.HasMember("preFlight") && d["preFlight"].IsString() && - d.HasMember("fee_currency") && d["fee_currency"].IsString() && - d.HasMember("settings") && d["settings"].IsString() && - d.HasMember("fee_amount") && d["fee_amount"].IsDouble() && - d.HasMember("user_changed_fee") && d["user_changed_fee"].IsBool() && - d.HasMember("days") && d["days"].IsUint() && - d.HasMember("transactions") && d["transactions"].IsArray() && - d.HasMember("ballots") && d["ballots"].IsArray() && - d.HasMember("ruleset") && d["ruleset"].IsString() && - d.HasMember("rulesetV2") && d["rulesetV2"].IsString() && - d.HasMember("batch") && d["batch"].IsArray() && - d.HasMember("auto_contribute") && d["auto_contribute"].IsBool() && - d.HasMember("rewards_enabled") && d["rewards_enabled"].IsBool()); - } - - if (!error) { - { - auto & i = d["walletInfo"]; - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - walletInfo_.loadFromJson(sb.GetString()); - } - - bootStamp_ = d["bootStamp"].GetUint64(); - reconcileStamp_ = d["reconcileStamp"].GetUint64(); - personaId_ = d["personaId"].GetString(); - userId_ = d["userId"].GetString(); - registrarVK_ = d["registrarVK"].GetString(); - masterUserToken_ = d["masterUserToken"].GetString(); - preFlight_ = d["preFlight"].GetString(); - fee_currency_ = d["fee_currency"].GetString(); - settings_ = d["settings"].GetString(); - fee_amount_ = d["fee_amount"].GetDouble(); - user_changed_fee_ = d["user_changed_fee"].GetBool(); - days_ = d["days"].GetUint(); - auto_contribute_ = d["auto_contribute"].GetBool(); - rewards_enabled_ = d["rewards_enabled"].GetBool(); - - for (const auto & i : d["transactions"].GetArray()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - - TRANSACTION_ST ta; - ta.loadFromJson(sb.GetString()); - transactions_.push_back(ta); - } - - for (const auto & i : d["ballots"].GetArray()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - - BALLOT_ST b; - b.loadFromJson(sb.GetString()); - ballots_.push_back(b); - } - - ruleset_ = d["ruleset"].GetString(); - rulesetV2_ = d["rulesetV2"].GetString(); - - for (const auto & i : d["batch"].GetArray()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - - BATCH_VOTES_ST b; - b.loadFromJson(sb.GetString()); - batch_.push_back(b); - } - - if (d.HasMember("current_reconciles") && - d["current_reconciles"].IsObject()) { - for (const auto & i : d["current_reconciles"].GetObject()) { - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.value.Accept(writer); - - CURRENT_RECONCILE b; - b.loadFromJson(sb.GetString()); - current_reconciles_[i.name.GetString()] = b; - } - } - - if (d.HasMember("walletProperties") && d["walletProperties"].IsObject()) { - auto & i = d["walletProperties"]; - rapidjson::StringBuffer sb; - rapidjson::Writer writer(sb); - i.Accept(writer); - walletProperties_.loadFromJson(sb.GetString()); - } - - if (d.HasMember("inlineTip") && d["inlineTip"].IsObject()) { - for (auto & k : d["inlineTip"].GetObject()) { - inline_tip_.insert( - std::make_pair(k.name.GetString(), k.value.GetBool())); - } - } - } - - return !error; -} - -void saveToJson(JsonWriter* writer, const CLIENT_STATE_ST& data) { - writer->StartObject(); - - writer->String("walletInfo"); - saveToJson(writer, data.walletInfo_); - - writer->String("bootStamp"); - writer->Uint64(data.bootStamp_); - - writer->String("reconcileStamp"); - writer->Uint64(data.reconcileStamp_); - - writer->String("personaId"); - writer->String(data.personaId_.c_str()); - - writer->String("userId"); - writer->String(data.userId_.c_str()); - - writer->String("registrarVK"); - writer->String(data.registrarVK_.c_str()); - - writer->String("masterUserToken"); - writer->String(data.masterUserToken_.c_str()); - - writer->String("preFlight"); - writer->String(data.preFlight_.c_str()); - - writer->String("fee_currency"); - writer->String(data.fee_currency_.c_str()); - - writer->String("settings"); - writer->String(data.settings_.c_str()); - - writer->String("fee_amount"); - writer->Double(data.fee_amount_); - - writer->String("user_changed_fee"); - writer->Bool(data.user_changed_fee_); - - writer->String("days"); - writer->Uint(data.days_); - - writer->String("rewards_enabled"); - writer->Bool(data.rewards_enabled_); - - writer->String("auto_contribute"); - writer->Bool(data.auto_contribute_); - - writer->String("transactions"); - writer->StartArray(); - for (auto & t : data.transactions_) { - saveToJson(writer, t); - } - writer->EndArray(); - - writer->String("ballots"); - writer->StartArray(); - for (auto & b : data.ballots_) { - saveToJson(writer, b); - } - writer->EndArray(); - - writer->String("ruleset"); - writer->String(data.ruleset_.c_str()); - - writer->String("rulesetV2"); - writer->String(data.rulesetV2_.c_str()); - - writer->String("batch"); - writer->StartArray(); - for (auto & b : data.batch_) { - saveToJson(writer, b); - } - writer->EndArray(); - - writer->String("current_reconciles"); - writer->StartObject(); - for (auto & t : data.current_reconciles_) { - writer->Key(t.first.c_str()); - saveToJson(writer, t.second); - } - writer->EndObject(); +using JsonWriter = rapidjson::Writer; - writer->String("walletProperties"); - saveToJson(writer, data.walletProperties_); - - writer->String("inlineTip"); - writer->StartObject(); - for (auto & p : data.inline_tip_) { - writer->String(p.first.c_str()); - writer->Bool(p.second); +bool isProbiValid(const std::string& probi) { + // probi shouldn't be longer then 44 + if (probi.length() > 44) { + return false; } - writer->EndObject(); - writer->EndObject(); + // checks if probi only contains numbers + return re2::RE2::FullMatch(probi, "^-?[0-9]*$"); } -///////////////////////////////////////////////////////////////////////////// -BATCH_PROOF::BATCH_PROOF() {} - -BATCH_PROOF::~BATCH_PROOF() {} - ///////////////////////////////////////////////////////////////////////////// bool getJSONValue(const std::string& fieldName, @@ -1490,48 +168,8 @@ bool getJSONRates(const std::string& json, return !error; } -bool getJSONTransaction(const std::string& json, TRANSACTION_ST* transaction) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !(d.HasMember("paymentStamp") && d["paymentStamp"].IsUint64() && - d.HasMember("probi") && d["probi"].IsString() && - d.HasMember("altcurrency") && d["altcurrency"].IsString() ); - } - - if (!error) { - uint64_t stamp = d["paymentStamp"].GetUint64(); - transaction->submissionStamp_ = std::to_string(stamp); - transaction->contribution_probi_ = d["probi"].GetString(); - } - return !error; -} - -bool getJSONUnsignedTx(const std::string& json, UNSIGNED_TX* unsignedTx) { - rapidjson::Document d; - d.Parse(json.c_str()); - - // has parser errors or wrong types - bool error = d.HasParseError(); - if (!error) { - error = !d.HasMember("unsignedTx") || !(d["unsignedTx"].IsObject()); - } - - if (!error) { - unsignedTx->amount_ = - d["unsignedTx"]["denomination"]["amount"].GetString(); - unsignedTx->currency_ = - d["unsignedTx"]["denomination"]["currency"].GetString(); - unsignedTx->destination_ = d["unsignedTx"]["destination"].GetString(); - } - return !error; -} - bool getJSONWalletInfo(const std::string& json, - WALLET_INFO_ST* walletInfo, + ledger::WalletInfoProperties* walletInfo, std::string* fee_currency, double* fee_amount, unsigned int* days) { @@ -1550,13 +188,9 @@ bool getJSONWalletInfo(const std::string& json, if (!error) { if (d.HasMember("payload") && d["payload"].IsObject()) { - walletInfo->paymentId_ = d["wallet"]["paymentId"].GetString(); - walletInfo->addressBAT_ = d["wallet"]["addresses"]["BAT"].GetString(); - walletInfo->addressBTC_ = d["wallet"]["addresses"]["BTC"].GetString(); - walletInfo->addressCARD_ID_ = + walletInfo->payment_id = d["wallet"]["paymentId"].GetString(); + walletInfo->address_card_id = d["wallet"]["addresses"]["CARD_ID"].GetString(); - walletInfo->addressETH_ = d["wallet"]["addresses"]["ETH"].GetString(); - walletInfo->addressLTC_ = d["wallet"]["addresses"]["LTC"].GetString(); *days = d["payload"]["adFree"]["days"].GetUint(); const auto & fee = d["payload"]["adFree"]["fee"].GetObject(); @@ -1566,11 +200,7 @@ bool getJSONWalletInfo(const std::string& json, *fee_amount = itr->value.GetDouble(); } } else if (d.HasMember("parameters") && d["parameters"].IsObject()) { - walletInfo->addressBAT_ = d["addresses"]["BAT"].GetString(); - walletInfo->addressBTC_ = d["addresses"]["BTC"].GetString(); - walletInfo->addressCARD_ID_ = d["addresses"]["CARD_ID"].GetString(); - walletInfo->addressETH_ = d["addresses"]["ETH"].GetString(); - walletInfo->addressLTC_ = d["addresses"]["LTC"].GetString(); + walletInfo->address_card_id = d["addresses"]["CARD_ID"].GetString(); *days = d["parameters"]["adFree"]["days"].GetUint(); const auto & fee = d["parameters"]["adFree"]["fee"].GetObject(); auto itr = fee.MemberBegin(); @@ -1726,20 +356,6 @@ std::string uint8ToHex(const std::vector& in) { return res.str(); } - -std::string stringifyBatch(std::vector payload) { - rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); - - writer.StartArray(); - for (auto & d : payload) { - saveToJson(&writer, d); - } - writer.EndArray(); - - return buffer.GetString(); -} - std::string stringify(std::string* keys, std::string* values, const unsigned int size) { @@ -1756,91 +372,6 @@ std::string stringify(std::string* keys, return buffer.GetString(); } -std::string stringifyUnsignedTx(const UNSIGNED_TX& unsignedTx) { - rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); - writer.StartObject(); - - writer.String("denomination"); - writer.StartObject(); - - writer.String("amount"); - writer.String(unsignedTx.amount_.c_str()); - - writer.String("currency"); - writer.String(unsignedTx.currency_.c_str()); - writer.EndObject(); - - writer.String("destination"); - writer.String(unsignedTx.destination_.c_str()); - - writer.EndObject(); - return buffer.GetString(); -} - -std::string stringifyReconcilePayloadSt( - const RECONCILE_PAYLOAD_ST& reconcile_payload) { - rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); - writer.StartObject(); // root - - if (!reconcile_payload.requestType_.empty()) { - writer.String("requestType"); - writer.String(reconcile_payload.requestType_.c_str()); - } - - writer.String("signedTx"); - writer.StartObject(); // signedTx - - writer.String("headers"); - writer.StartObject(); // headers - - writer.String("digest"); - writer.String(reconcile_payload.request_signedtx_headers_digest_.c_str()); - - writer.String("signature"); - writer.String(reconcile_payload.request_signedtx_headers_signature_.c_str()); - - writer.EndObject(); // headers - - writer.String("body"); - writer.StartObject(); // body - - writer.String("denomination"); - writer.StartObject(); // denomination - - writer.String("amount"); - writer.String(reconcile_payload.request_signedtx_body_.amount_.c_str()); - - writer.String("currency"); - writer.String(reconcile_payload.request_signedtx_body_.currency_.c_str()); - - writer.EndObject(); // denomination - - writer.String("destination"); - writer.String(reconcile_payload.request_signedtx_body_.destination_.c_str()); - - writer.EndObject(); // body - - writer.String("octets"); - writer.String(reconcile_payload.request_signedtx_octets_.c_str()); - - writer.EndObject(); // signedTx - - if (!reconcile_payload.request_surveyorId_.empty()) { - writer.String("surveyorId"); - writer.String(reconcile_payload.request_surveyorId_.c_str()); - } - - if (!reconcile_payload.request_viewingId_.empty()) { - writer.String("viewingId"); - writer.String(reconcile_payload.request_viewingId_.c_str()); - } - - writer.EndObject(); // root - return buffer.GetString(); -} - std::vector getSHA256(const std::string& in) { std::vector res(SHA256_DIGEST_LENGTH); SHA256((uint8_t*)in.c_str(), in.length(), &res.front()); @@ -1988,34 +519,4 @@ uint8_t niceware_mnemonic_to_bytes( return 0; } -void saveToJson(JsonWriter* writer, const ledger::VisitData& visitData) { - writer->StartObject(); - - writer->String("tld"); - writer->String(visitData.tld.c_str()); - - writer->String("domain"); - writer->String(visitData.domain.c_str()); - - writer->String("path"); - writer->String(visitData.path.c_str()); - - writer->String("tab_id"); - writer->Uint(visitData.tab_id); - - writer->String("name"); - writer->String(visitData.name.c_str()); - - writer->String("url"); - writer->String(visitData.url.c_str()); - - writer->String("provider"); - writer->String(visitData.provider.c_str()); - - writer->String("favicon_url"); - writer->String(visitData.favicon_url.c_str()); - - writer->EndObject(); -} - } // namespace braveledger_bat_helper diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h index 781d2b73ab47..b6f505e192d9 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper.h @@ -11,319 +11,13 @@ #include #include -#include "bat/ledger/ledger.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/internal/static_values.h" +#include "bat/ledger/ledger.h" namespace braveledger_bat_helper { bool isProbiValid(const std::string& number); -struct UNSIGNED_TX { - UNSIGNED_TX(); - ~UNSIGNED_TX(); - - std::string amount_; - std::string currency_; - std::string destination_; -}; - -struct RECONCILE_PAYLOAD_ST { - RECONCILE_PAYLOAD_ST(); - ~RECONCILE_PAYLOAD_ST(); - - std::string requestType_; - std::string request_signedtx_headers_digest_; - std::string request_signedtx_headers_signature_; - UNSIGNED_TX request_signedtx_body_; - std::string request_signedtx_octets_; - std::string request_viewingId_; - std::string request_surveyorId_; -}; - -struct WALLET_INFO_ST { - WALLET_INFO_ST(); - WALLET_INFO_ST(const WALLET_INFO_ST&); - ~WALLET_INFO_ST(); - - // load from json string - bool loadFromJson(const std::string & json); - - std::string paymentId_; - std::string addressBAT_; - std::string addressBTC_; - std::string addressCARD_ID_; - std::string addressETH_; - std::string addressLTC_; - std::vector keyInfoSeed_; -}; - -struct TRANSACTION_BALLOT_ST { - TRANSACTION_BALLOT_ST(); - ~TRANSACTION_BALLOT_ST(); - - // load from json string - bool loadFromJson(const std::string & json); - - std::string publisher_; - unsigned int offset_ = 0u; -}; - -struct TRANSACTION_ST { - TRANSACTION_ST(); - TRANSACTION_ST(const TRANSACTION_ST& transaction); - ~TRANSACTION_ST(); - - // load from json string - bool loadFromJson(const std::string & json); - - std::string viewingId_; - std::string surveyorId_; - std::map contribution_rates_; - std::string contribution_probi_; - std::string submissionStamp_; - std::string anonizeViewingId_; - std::string registrarVK_; - std::string masterUserToken_; - std::vector surveyorIds_; - unsigned int votes_ = 0u; - std::vector ballots_; -}; - -struct BALLOT_ST { - BALLOT_ST(); - BALLOT_ST(const BALLOT_ST& ballot); - ~BALLOT_ST(); - - // Load from json string - bool loadFromJson(const std::string & json); - - std::string viewingId_; - std::string surveyorId_; - std::string publisher_; - unsigned int offset_ = 0u; - std::string prepareBallot_; - std::string proofBallot_; - uint64_t delayStamp_ = 0u; -}; - -struct BATCH_VOTES_INFO_ST { - BATCH_VOTES_INFO_ST(); - BATCH_VOTES_INFO_ST(const BATCH_VOTES_INFO_ST&); - ~BATCH_VOTES_INFO_ST(); - - // Load from json string - bool loadFromJson(const std::string & json); - - std::string surveyorId_; - std::string proof_; -}; - -struct BATCH_VOTES_ST { - BATCH_VOTES_ST(); - BATCH_VOTES_ST(const BATCH_VOTES_ST&); - ~BATCH_VOTES_ST(); - - // Load from json string - bool loadFromJson(const std::string & json); - - std::string publisher_; - std::vector batchVotesInfo_; -}; - -struct WALLET_PROPERTIES_ST { - WALLET_PROPERTIES_ST(); - ~WALLET_PROPERTIES_ST(); - WALLET_PROPERTIES_ST(const WALLET_PROPERTIES_ST& properties); - - // load from json string - bool loadFromJson(const std::string & json); - - double fee_amount_; - std::vector parameters_choices_; -}; - -struct REPORT_BALANCE_ST { - REPORT_BALANCE_ST(); - REPORT_BALANCE_ST(const REPORT_BALANCE_ST&); - ~REPORT_BALANCE_ST(); - - bool loadFromJson(const std::string &json); - - std::string opening_balance_ = "0"; - std::string closing_balance_ = "0"; - std::string deposits_ = "0"; - std::string grants_ = "0"; - std::string earning_from_ads_ = "0"; - std::string auto_contribute_ = "0"; - std::string recurring_donation_ = "0"; - std::string one_time_donation_ = "0"; - std::string total_ = "0"; -}; - -struct PUBLISHER_STATE_ST { - PUBLISHER_STATE_ST(); - PUBLISHER_STATE_ST(const PUBLISHER_STATE_ST&); - ~PUBLISHER_STATE_ST(); - - // load from json string - bool loadFromJson(const std::string &json); - - uint64_t min_publisher_duration_ = - braveledger_ledger::_default_min_publisher_duration; // In seconds - unsigned int min_visits_ = 1u; - bool allow_non_verified_ = true; - bool allow_videos_ = true; - std::map monthly_balances_; - bool migrate_score_2 = false; - std::vector processed_pending_publishers; -}; - -struct PUBLISHER_ST { - PUBLISHER_ST(); - ~PUBLISHER_ST(); - bool operator<(const PUBLISHER_ST& rhs) const; - - // load from json string - bool loadFromJson(const std::string & json); - - std::string id_; - uint64_t duration_ = 0u; - double score_ = .0; - unsigned int visits_ = 0; - - // The mathematically rounded publisher voting weight, as described - // below. - unsigned int percent_ = 0; - - // The exact weight to use when calculating the number of votes to - // cast for each publisher. - double weight_ = .0; - - unsigned int status_ = 0; -}; - -struct RECONCILE_DIRECTION { - RECONCILE_DIRECTION(); - RECONCILE_DIRECTION(const std::string& publisher_key, - double amount_percent); - ~RECONCILE_DIRECTION(); - - bool loadFromJson(const std::string &json); - - std::string publisher_key_; - double amount_percent_; -}; - -typedef std::vector Directions; - -struct WINNERS_ST { - WINNERS_ST(); - ~WINNERS_ST(); - - RECONCILE_DIRECTION direction_; - unsigned int votes_ = 0; -}; - -typedef std::vector Winners; - -struct SURVEYOR_INFO_ST { - SURVEYOR_INFO_ST(); - ~SURVEYOR_INFO_ST(); - - std::string surveyorId_; -}; - -struct SURVEYOR_ST { - SURVEYOR_ST(); - ~SURVEYOR_ST(); - - // load from json string - bool loadFromJson(const std::string & json); - - std::string signature_; - std::string surveyorId_; - std::string surveyVK_; - std::string registrarVK_; - std::string surveySK_; -}; - - -typedef std::vector PublisherList; - -struct CURRENT_RECONCILE { - CURRENT_RECONCILE(); - CURRENT_RECONCILE(const CURRENT_RECONCILE&); - ~CURRENT_RECONCILE(); - - // load from json string - bool loadFromJson(const std::string & json); - - std::string viewingId_; - std::string anonizeViewingId_; - std::string registrarVK_; - std::string preFlight_; - std::string masterUserToken_; - SURVEYOR_INFO_ST surveyorInfo_; - uint64_t timestamp_ = 0u; - std::map rates_; - std::string amount_; - std::string currency_; - double fee_; - Directions directions_; - ledger::RewardsType type_; - ledger::ContributionRetry retry_step_; - int retry_level_; - std::string destination_; - std::string proof_; -}; - -typedef std::vector Transactions; -typedef std::vector Ballots; -typedef std::vector BatchVotes; -typedef std::map CurrentReconciles; - -struct CLIENT_STATE_ST { - CLIENT_STATE_ST(); - CLIENT_STATE_ST(const CLIENT_STATE_ST&); - ~CLIENT_STATE_ST(); - - // Load from json string - bool loadFromJson(const std::string & json); - - WALLET_INFO_ST walletInfo_; - WALLET_PROPERTIES_ST walletProperties_; - uint64_t bootStamp_ = 0u; - uint64_t reconcileStamp_ = 0u; - std::string personaId_; - std::string userId_; - std::string registrarVK_; - std::string masterUserToken_; - std::string preFlight_; - std::string fee_currency_; - std::string settings_ = AD_FREE_SETTINGS; - double fee_amount_ = .0; - bool user_changed_fee_ = false; - unsigned int days_ = 0u; - Transactions transactions_; - Ballots ballots_; - std::string ruleset_; - std::string rulesetV2_; - BatchVotes batch_; - CurrentReconciles current_reconciles_; - bool auto_contribute_ = false; - bool rewards_enabled_ = false; - std::map inline_tip_; -}; - -struct BATCH_PROOF { - BATCH_PROOF(); - ~BATCH_PROOF(); - - TRANSACTION_ST transaction_; - BALLOT_ST ballot_; -}; - -typedef std::vector BatchProofs; - using SaveVisitSignature = void(const std::string&, uint64_t); using SaveVisitCallback = std::function; @@ -336,15 +30,11 @@ bool getJSONList(const std::string& fieldName, std::vector* value); bool getJSONWalletInfo(const std::string& json, - WALLET_INFO_ST* walletInfo, + ledger::WalletInfoProperties* walletInfo, std::string* fee_currency, double* fee_amount, unsigned int* days); -bool getJSONUnsignedTx(const std::string& json, UNSIGNED_TX* unsignedTx); - -bool getJSONTransaction(const std::string& json, TRANSACTION_ST* transaction); - bool getJSONRates(const std::string& json, std::map* rates); @@ -382,13 +72,6 @@ std::string stringify(std::string* keys, std::string* values, const unsigned int size); -std::string stringifyReconcilePayloadSt( - const RECONCILE_PAYLOAD_ST& reconcile_payload); - -std::string stringifyUnsignedTx(const UNSIGNED_TX& unsignedTx); - -std::string stringifyBatch(std::vector payload); - std::vector getSHA256(const std::string& in); std::string getBase64(const std::vector& in); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper_unittest.cc index b98b712bb140..87a6be1845b4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_helper_unittest.cc @@ -4,7 +4,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "bat/ledger/internal/bat_helper.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" #include "bat/ledger/ledger.h" #include "testing/gtest/include/gtest/gtest.h" @@ -92,51 +91,3 @@ TEST(BatHelperTest, HasSameDomainAndPath) { url, url_portion, path); ASSERT_EQ(result, false); } - -TEST(BatHelperTest, TransactionSerialization) { - braveledger_bat_helper::TRANSACTION_ST transaction; - transaction.viewingId_ = "VIEWING_ID"; - transaction.surveyorId_ = "SURVEYOR_ID"; - transaction.contribution_probi_ = "CONTRIBUTION_PROBI"; - transaction.submissionStamp_ = "SUBMISSION_STAMP"; - transaction.anonizeViewingId_ = "ANONIZE_VIEWING_ID"; - transaction.registrarVK_ = "REGISTRAR_VK"; - transaction.masterUserToken_ = "MASTER_USER_TOKEN"; - transaction.surveyorIds_ = { "SURVEYOR_ID" }; - transaction.votes_ = 5; - transaction.contribution_rates_ = { - { "BAT", 1.0 }, - { "ETH", 2.0 }, - { "LTC", 3.0 }, - { "BTC", 4.0 }, - { "USD", 5.0 }, - { "EUR", 6.0 }, - }; - - braveledger_bat_helper::TRANSACTION_BALLOT_ST ballot; - ballot.publisher_ = "brave.com"; - ballot.offset_ = 5; - transaction.ballots_.push_back(ballot); - - std::string json; - braveledger_bat_helper::saveToJsonString(transaction, &json); - ASSERT_FALSE(json.empty()); - - braveledger_bat_helper::TRANSACTION_ST deserialized; - ASSERT_TRUE(deserialized.loadFromJson(json)); - - ASSERT_EQ(deserialized.viewingId_, transaction.viewingId_); - ASSERT_EQ(deserialized.surveyorId_, transaction.surveyorId_); - ASSERT_EQ(deserialized.contribution_probi_, transaction.contribution_probi_); - ASSERT_EQ(deserialized.submissionStamp_, transaction.submissionStamp_); - ASSERT_EQ(deserialized.anonizeViewingId_, transaction.anonizeViewingId_); - ASSERT_EQ(deserialized.registrarVK_, transaction.registrarVK_); - ASSERT_EQ(deserialized.masterUserToken_, transaction.masterUserToken_); - ASSERT_EQ(deserialized.surveyorIds_, transaction.surveyorIds_); - ASSERT_EQ(deserialized.votes_, transaction.votes_); - ASSERT_EQ(deserialized.contribution_rates_, transaction.contribution_rates_); - ASSERT_EQ(deserialized.ballots_[0].publisher_, - transaction.ballots_[0].publisher_); - ASSERT_EQ(deserialized.ballots_[0].offset_, - transaction.ballots_[0].offset_); -} diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc index 0fc419855d16..2a0d70b62c73 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.cc @@ -6,41 +6,43 @@ #include #include +#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/bat_state.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" +#include "bat/ledger/internal/state/client_state.h" namespace braveledger_bat_state { BatState::BatState(bat_ledger::LedgerImpl* ledger) : ledger_(ledger), - state_(new braveledger_bat_helper::CLIENT_STATE_ST()) { + state_(new ledger::ClientProperties()) { } BatState::~BatState() { } bool BatState::LoadState(const std::string& data) { - braveledger_bat_helper::CLIENT_STATE_ST state; - if (!braveledger_bat_helper::loadFromJson(&state, data.c_str())) { + ledger::ClientProperties state; + const ledger::ClientState client_state; + if (!client_state.FromJson(data, &state)) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Failed to load client state: " << data; return false; } - state_.reset(new braveledger_bat_helper::CLIENT_STATE_ST(state)); + state_.reset(new ledger::ClientProperties(state)); bool stateChanged = false; // fix timestamp ms to s conversion - if (std::to_string(state_->reconcileStamp_).length() > 10) { - state_->reconcileStamp_ = state_->reconcileStamp_ / 1000; + if (std::to_string(state_->reconcile_timestamp).length() > 10) { + state_->reconcile_timestamp = state_->reconcile_timestamp / 1000; stateChanged = true; } // fix timestamp ms to s conversion - if (std::to_string(state_->bootStamp_).length() > 10) { - state_->bootStamp_ = state_->bootStamp_ / 1000; + if (std::to_string(state_->boot_timestamp).length() > 10) { + state_->boot_timestamp = state_->boot_timestamp / 1000; stateChanged = true; } @@ -52,200 +54,198 @@ bool BatState::LoadState(const std::string& data) { } void BatState::SaveState() { - std::string data; - braveledger_bat_helper::saveToJsonString(*state_, &data); + const ledger::ClientState client_state; + const std::string data = client_state.ToJson(*state_); ledger_->SaveLedgerState(data); } void BatState::AddReconcile(const std::string& viewing_id, - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile) { - state_->current_reconciles_.insert(std::make_pair(viewing_id, reconcile)); + const ledger::CurrentReconcileProperties& reconcile) { + state_->current_reconciles.insert(std::make_pair(viewing_id, reconcile)); SaveState(); } bool BatState::UpdateReconcile( - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile) { - if (state_->current_reconciles_.count(reconcile.viewingId_) == 0) { + const ledger::CurrentReconcileProperties& reconcile) { + if (state_->current_reconciles.count(reconcile.viewing_id) == 0) { return false; } - state_->current_reconciles_[reconcile.viewingId_] = reconcile; + state_->current_reconciles[reconcile.viewing_id] = reconcile; SaveState(); return true; } -braveledger_bat_helper::CURRENT_RECONCILE BatState::GetReconcileById( +ledger::CurrentReconcileProperties BatState::GetReconcileById( const std::string& viewingId) const { - if (state_->current_reconciles_.count(viewingId) == 0) { + if (state_->current_reconciles.count(viewingId) == 0) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Could not find any reconcile tasks with the id " << viewingId; - return braveledger_bat_helper::CURRENT_RECONCILE(); + return ledger::CurrentReconcileProperties(); } - return state_->current_reconciles_[viewingId]; + return state_->current_reconciles[viewingId]; } bool BatState::ReconcileExists(const std::string& viewingId) const { - return state_->current_reconciles_.count(viewingId) > 0; + return state_->current_reconciles.count(viewingId) > 0; } void BatState::RemoveReconcileById(const std::string& viewingId) { - braveledger_bat_helper::CurrentReconciles::iterator it = - state_->current_reconciles_.find(viewingId); - if (it != state_->current_reconciles_.end()) { - state_->current_reconciles_.erase(it); + ledger::CurrentReconciles::iterator it = + state_->current_reconciles.find(viewingId); + if (it != state_->current_reconciles.end()) { + state_->current_reconciles.erase(it); SaveState(); } } void BatState::SetRewardsMainEnabled(bool enabled) { - state_->rewards_enabled_ = enabled; + state_->rewards_enabled = enabled; SaveState(); } bool BatState::GetRewardsMainEnabled() const { - return state_->rewards_enabled_; + return state_->rewards_enabled; } void BatState::SetContributionAmount(double amount) { - braveledger_bat_helper::WALLET_PROPERTIES_ST properties = - GetWalletProperties(); - auto hasAmount = std::find(properties.parameters_choices_.begin(), - properties.parameters_choices_.end(), + ledger::WalletProperties properties = GetWalletProperties(); + auto hasAmount = std::find(properties.parameters_choices.begin(), + properties.parameters_choices.end(), amount); - if (hasAmount == properties.parameters_choices_.end()) { + if (hasAmount == properties.parameters_choices.end()) { // amount is missing in the list - properties.parameters_choices_.push_back(amount); - std::sort(properties.parameters_choices_.begin(), - properties.parameters_choices_.end()); + properties.parameters_choices.push_back(amount); + std::sort(properties.parameters_choices.begin(), + properties.parameters_choices.end()); ledger_->OnWalletProperties(ledger::Result::LEDGER_OK, properties); - state_->walletProperties_ = properties; + state_->wallet = properties; } - state_->fee_amount_ = amount; + state_->fee_amount = amount; SaveState(); } double BatState::GetContributionAmount() const { - return state_->fee_amount_; + return state_->fee_amount; } void BatState::SetUserChangedContribution() { - state_->user_changed_fee_ = true; + state_->user_changed_fee = true; SaveState(); } bool BatState::GetUserChangedContribution() const { - return state_->user_changed_fee_; + return state_->user_changed_fee; } void BatState::SetAutoContribute(bool enabled) { - state_->auto_contribute_ = enabled; + state_->auto_contribute = enabled; SaveState(); } bool BatState::GetAutoContribute() const { - return state_->auto_contribute_; + return state_->auto_contribute; } const std::string& BatState::GetCardIdAddress() const { - return state_->walletInfo_.addressCARD_ID_; + return state_->wallet_info.address_card_id; } uint64_t BatState::GetReconcileStamp() const { - return state_->reconcileStamp_; + return state_->reconcile_timestamp; } void BatState::ResetReconcileStamp() { if (ledger::reconcile_time > 0) { - state_->reconcileStamp_ = braveledger_bat_helper::currentTime() + + state_->reconcile_timestamp = braveledger_bat_helper::currentTime() + ledger::reconcile_time * 60; } else { - state_->reconcileStamp_ = braveledger_bat_helper::currentTime() + + state_->reconcile_timestamp = braveledger_bat_helper::currentTime() + braveledger_ledger::_reconcile_default_interval; } SaveState(); } bool BatState::IsWalletCreated() const { - return state_->bootStamp_ != 0u; + return state_->boot_timestamp != 0u; } const std::string& BatState::GetPaymentId() const { - return state_->walletInfo_.paymentId_; + return state_->wallet_info.payment_id; } const std::string& BatState::GetPersonaId() const { - return state_->personaId_; + return state_->persona_id; } void BatState::SetPersonaId(const std::string& persona_id) { - state_->personaId_ = persona_id; + state_->persona_id = persona_id; SaveState(); } const std::string& BatState::GetUserId() const { - return state_->userId_; + return state_->user_id; } void BatState::SetUserId(const std::string& user_id) { - state_->userId_ = user_id; + state_->user_id = user_id; SaveState(); } const std::string& BatState::GetRegistrarVK() const { - return state_->registrarVK_; + return state_->registrar_vk; } void BatState::SetRegistrarVK(const std::string& registrar_vk) { - state_->registrarVK_ = registrar_vk; + state_->registrar_vk = registrar_vk; SaveState(); } const std::string& BatState::GetPreFlight() const { - return state_->preFlight_; + return state_->pre_flight; } void BatState::SetPreFlight(const std::string& pre_flight) { - state_->preFlight_ = pre_flight; + state_->pre_flight = pre_flight; SaveState(); } -const braveledger_bat_helper::WALLET_INFO_ST& BatState::GetWalletInfo() const { - return state_->walletInfo_; +const ledger::WalletInfoProperties& BatState::GetWalletInfo() const { + return state_->wallet_info; } void BatState::SetWalletInfo( - const braveledger_bat_helper::WALLET_INFO_ST& wallet_info) { - state_->walletInfo_ = wallet_info; + const ledger::WalletInfoProperties& wallet_info) { + state_->wallet_info = wallet_info; SaveState(); } -const braveledger_bat_helper::WALLET_PROPERTIES_ST& -BatState::GetWalletProperties() const { - return state_->walletProperties_; +const ledger::WalletProperties& BatState::GetWalletProperties() const { + return state_->wallet; } void BatState::SetWalletProperties( - braveledger_bat_helper::WALLET_PROPERTIES_ST* properties) { + ledger::WalletProperties* properties) { double amount = GetContributionAmount(); - double new_amount = properties->fee_amount_; + double new_amount = properties->fee_amount; bool amount_changed = GetUserChangedContribution(); if (amount_changed) { - auto hasAmount = std::find(properties->parameters_choices_.begin(), - properties->parameters_choices_.end(), + auto hasAmount = std::find(properties->parameters_choices.begin(), + properties->parameters_choices.end(), amount); - if (hasAmount == properties->parameters_choices_.end()) { + if (hasAmount == properties->parameters_choices.end()) { // amount is missing in the list - properties->parameters_choices_.push_back(amount); - std::sort(properties->parameters_choices_.begin(), - properties->parameters_choices_.end()); + properties->parameters_choices.push_back(amount); + std::sort(properties->parameters_choices.begin(), + properties->parameters_choices.end()); } } - state_->walletProperties_ = *properties; + state_->wallet = *properties; if (!amount_changed && amount != new_amount) { SetContributionAmount(new_amount); @@ -255,110 +255,109 @@ void BatState::SetWalletProperties( } unsigned int BatState::GetDays() const { - return state_->days_; + return state_->days; } void BatState::SetDays(unsigned int days) { - state_->days_ = days; + state_->days = days; SaveState(); } -const braveledger_bat_helper::Transactions& BatState::GetTransactions() const { - return state_->transactions_; +const ledger::Transactions& BatState::GetTransactions() const { + return state_->transactions; } void BatState::SetTransactions( - const braveledger_bat_helper::Transactions& transactions) { - state_->transactions_ = transactions; + const ledger::Transactions& transactions) { + state_->transactions = transactions; SaveState(); } -const braveledger_bat_helper::Ballots& BatState::GetBallots() const { - return state_->ballots_; +const ledger::Ballots& BatState::GetBallots() const { + return state_->ballots; } -void BatState::SetBallots(const braveledger_bat_helper::Ballots& ballots) { - state_->ballots_ = ballots; +void BatState::SetBallots(const ledger::Ballots& ballots) { + state_->ballots = ballots; SaveState(); } -const braveledger_bat_helper::BatchVotes& BatState::GetBatch() const { - return state_->batch_; +const ledger::PublisherVotes& BatState::GetPublisherVotes() const { + return state_->publisher_votes; } -void BatState::SetBatch(const braveledger_bat_helper::BatchVotes& votes) { - state_->batch_ = votes; +void BatState::SetPublisherVotes( + const ledger::PublisherVotes& publisher_votes) { + state_->publisher_votes = publisher_votes; SaveState(); } const std::string& BatState::GetCurrency() const { - return state_->fee_currency_; + return state_->fee_currency; } void BatState::SetCurrency(const std::string ¤cy) { - state_->fee_currency_ = currency; + state_->fee_currency = currency; SaveState(); } uint64_t BatState::GetBootStamp() const { - return state_->bootStamp_; + return state_->boot_timestamp; } void BatState::SetBootStamp(uint64_t stamp) { - state_->bootStamp_ = stamp; + state_->boot_timestamp = stamp; SaveState(); } const std::string& BatState::GetMasterUserToken() const { - return state_->masterUserToken_; + return state_->master_user_token; } void BatState::SetMasterUserToken(const std::string &token) { - state_->masterUserToken_ = token; + state_->master_user_token = token; SaveState(); } bool BatState::AddReconcileStep(const std::string& viewing_id, ledger::ContributionRetry step, int level) { - braveledger_bat_helper::CURRENT_RECONCILE reconcile = - GetReconcileById(viewing_id); + ledger::CurrentReconcileProperties reconcile = GetReconcileById(viewing_id); - if (reconcile.viewingId_.empty()) { + if (reconcile.viewing_id.empty()) { return false; } // don't save step when you are already in the same step - if (reconcile.retry_step_ == step && level == -1) { + if (reconcile.retry_step == step && level == -1) { return true; } - reconcile.retry_step_ = step; - reconcile.retry_level_ = level; + reconcile.retry_step = step; + reconcile.retry_level = level; return UpdateReconcile(reconcile); } -const braveledger_bat_helper::CurrentReconciles& -BatState::GetCurrentReconciles() const { - return state_->current_reconciles_; +const ledger::CurrentReconciles& BatState::GetCurrentReconciles() const { + return state_->current_reconciles; } double BatState::GetDefaultContributionAmount() { - return state_->walletProperties_.fee_amount_; + return state_->wallet.fee_amount; } void BatState::SetInlineTipSetting(const std::string& key, bool enabled) { - state_->inline_tip_[key] = enabled; + state_->inline_tips[key] = enabled; SaveState(); } bool BatState::GetInlineTipSetting(const std::string& key) const { - if (state_->inline_tip_.find(key) == state_->inline_tip_.end()) { + if (state_->inline_tips.find(key) == state_->inline_tips.end()) { // not found, all tips are on by default return true; } else { - return state_->inline_tip_[key]; + return state_->inline_tips[key]; } } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h index c75ac78baba7..22c2a176f644 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/bat_state.h @@ -11,7 +11,12 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/properties/ballot_properties.h" +#include "bat/ledger/internal/properties/publisher_votes_properties.h" +#include "bat/ledger/internal/properties/client_properties.h" +#include "bat/ledger/internal/properties/current_reconcile_properties.h" +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" namespace bat_ledger { class LedgerImpl; @@ -28,12 +33,12 @@ class BatState { void AddReconcile( const std::string& viewing_id, - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile); + const ledger::CurrentReconcileProperties& reconcile); bool UpdateReconcile( - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile); + const ledger::CurrentReconcileProperties& reconcile); - braveledger_bat_helper::CURRENT_RECONCILE GetReconcileById( + ledger::CurrentReconcileProperties GetReconcileById( const std::string& viewingId) const; void RemoveReconcileById(const std::string& viewingId); @@ -82,32 +87,32 @@ class BatState { void SetPreFlight(const std::string& pre_flight); - const braveledger_bat_helper::WALLET_INFO_ST& GetWalletInfo() const; + const ledger::WalletInfoProperties& GetWalletInfo() const; - void SetWalletInfo(const braveledger_bat_helper::WALLET_INFO_ST& info); + void SetWalletInfo(const ledger::WalletInfoProperties& info); - const braveledger_bat_helper::WALLET_PROPERTIES_ST& - GetWalletProperties() const; + const ledger::WalletProperties& GetWalletProperties() const; void SetWalletProperties( - braveledger_bat_helper::WALLET_PROPERTIES_ST* properties); + ledger::WalletProperties* properties); unsigned int GetDays() const; void SetDays(unsigned int days); - const braveledger_bat_helper::Transactions& GetTransactions() const; + const ledger::Transactions& GetTransactions() const; void SetTransactions( - const braveledger_bat_helper::Transactions& transactions); + const ledger::Transactions& transactions); - const braveledger_bat_helper::Ballots& GetBallots() const; + const ledger::Ballots& GetBallots() const; - void SetBallots(const braveledger_bat_helper::Ballots& ballots); + void SetBallots(const ledger::Ballots& ballots); - const braveledger_bat_helper::BatchVotes& GetBatch() const; + const ledger::PublisherVotes& GetPublisherVotes() const; - void SetBatch(const braveledger_bat_helper::BatchVotes& votes); + void SetPublisherVotes( + const ledger::PublisherVotes& publisher_votes); const std::string& GetCurrency() const; @@ -125,7 +130,7 @@ class BatState { ledger::ContributionRetry step, int level); - const braveledger_bat_helper::CurrentReconciles& GetCurrentReconciles() const; + const ledger::CurrentReconciles& GetCurrentReconciles() const; double GetDefaultContributionAmount(); @@ -137,7 +142,7 @@ class BatState { void SaveState(); bat_ledger::LedgerImpl* ledger_; // NOT OWNED - std::unique_ptr state_; + std::unique_ptr state_; }; } // namespace braveledger_bat_state 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 883101c57976..01ce859fe2ab 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 @@ -53,16 +53,15 @@ void Contribution::Initialize() { uphold_->Initialize(); // Resume in progress contributions - braveledger_bat_helper::CurrentReconciles currentReconciles = - ledger_->GetCurrentReconciles(); + ledger::CurrentReconciles currentReconciles = ledger_->GetCurrentReconciles(); for (const auto& value : currentReconciles) { - braveledger_bat_helper::CURRENT_RECONCILE reconcile = value.second; + ledger::CurrentReconcileProperties reconcile = value.second; - if (reconcile.retry_step_ == ledger::ContributionRetry::STEP_FINAL) { - ledger_->RemoveReconcileById(reconcile.viewingId_); + if (reconcile.retry_step == ledger::ContributionRetry::STEP_FINAL) { + ledger_->RemoveReconcileById(reconcile.viewing_id); } else { - DoRetry(reconcile.viewingId_); + DoRetry(reconcile.viewing_id); } } @@ -404,15 +403,15 @@ void Contribution::ReconcileSuccess( ledger_->SetBalanceReportItem( braveledger_time_util::GetCurrentMonth(), braveledger_time_util::GetCurrentYear(), - GetReportTypeFromRewardsType(reconcile.type_), + GetReportTypeFromRewardsType(reconcile.type), probi); ledger::ContributionPublisherList publisher_list; - for (auto& item : reconcile.directions_) { + for (auto& item : reconcile.directions) { auto publisher = ledger::ContributionPublisher::New(); publisher->contribution_id = viewing_id; - publisher->publisher_key = item.publisher_key_; - publisher->total_amount = (item.amount_percent_ * amount) / 100; + publisher->publisher_key = item.publisher_key; + publisher->total_amount = (item.amount_percent * amount) / 100; publisher->contributed_amount = publisher->total_amount; publisher_list.push_back(std::move(publisher)); } @@ -421,7 +420,7 @@ void Contribution::ReconcileSuccess( auto info = ledger::ContributionInfo::New(); info->contribution_id = viewing_id; info->amount = amount; - info->type = reconcile.type_; + info->type = reconcile.type; info->step = -1; info->retry_count = -1; info->created_at = now; @@ -437,33 +436,33 @@ void Contribution::ReconcileSuccess( void Contribution::AddRetry( ledger::ContributionRetry step, const std::string& viewing_id, - braveledger_bat_helper::CURRENT_RECONCILE reconcile) { + ledger::CurrentReconcileProperties reconcile) { BLOG(ledger_, ledger::LogLevel::LOG_WARNING) << "Re-trying contribution for step" << std::to_string(static_cast(step)) << "for" << viewing_id; - if (reconcile.viewingId_.empty()) { + if (reconcile.viewing_id.empty()) { reconcile = ledger_->GetReconcileById(viewing_id); } // Don't retry one-time tip if in phase 1 if (GetRetryPhase(step) == 1 && - reconcile.type_ == ledger::RewardsType::ONE_TIME_TIP) { + reconcile.type == ledger::RewardsType::ONE_TIME_TIP) { phase_one_->Complete(ledger::Result::TIP_ERROR, viewing_id, - reconcile.type_); + reconcile.type); return; } uint64_t start_timer_in = GetRetryTimer(step, viewing_id, &reconcile); bool success = ledger_->AddReconcileStep(viewing_id, - reconcile.retry_step_, - reconcile.retry_level_); + reconcile.retry_step, + reconcile.retry_level); if (!success || start_timer_in == 0) { phase_one_->Complete(ledger::Result::LEDGER_ERROR, viewing_id, - reconcile.type_); + reconcile.type); return; } @@ -474,25 +473,25 @@ void Contribution::AddRetry( uint64_t Contribution::GetRetryTimer( ledger::ContributionRetry step, const std::string& viewing_id, - braveledger_bat_helper::CURRENT_RECONCILE* reconcile) { - ledger::ContributionRetry old_step = reconcile->retry_step_; + ledger::CurrentReconcileProperties* reconcile) { + ledger::ContributionRetry old_step = reconcile->retry_step; int phase = GetRetryPhase(step); if (phase > GetRetryPhase(old_step)) { - reconcile->retry_level_ = 0; + reconcile->retry_level = 0; } else { - reconcile->retry_level_++; + reconcile->retry_level++; } - reconcile->retry_step_ = step; + reconcile->retry_step = step; if (phase == 1) { // TODO(nejczdovc) get size from the list - if (reconcile->retry_level_ < 5) { + if (reconcile->retry_level < 5) { if (ledger::short_retries) { - return phase_one_debug_timers[reconcile->retry_level_]; + return phase_one_debug_timers[reconcile->retry_level]; } else { - return phase_one_timers[reconcile->retry_level_]; + return phase_one_timers[reconcile->retry_level]; } } else { @@ -502,7 +501,7 @@ uint64_t Contribution::GetRetryTimer( if (phase == 2) { // TODO(nejczdovc) get size from the list - if (reconcile->retry_level_ > 2) { + if (reconcile->retry_level > 2) { if (ledger::short_retries) { return phase_two_debug_timers[2]; } else { @@ -510,9 +509,9 @@ uint64_t Contribution::GetRetryTimer( } } else { if (ledger::short_retries) { - return phase_two_debug_timers[reconcile->retry_level_]; + return phase_two_debug_timers[reconcile->retry_level]; } else { - return phase_two_timers[reconcile->retry_level_]; + return phase_two_timers[reconcile->retry_level]; } } } @@ -550,7 +549,7 @@ int Contribution::GetRetryPhase(ledger::ContributionRetry step) { void Contribution::DoRetry(const std::string& viewing_id) { auto reconcile = ledger_->GetReconcileById(viewing_id); - switch (reconcile.retry_step_) { + switch (reconcile.retry_step) { case ledger::ContributionRetry::STEP_RECONCILE: { phase_one_->Start(viewing_id); break; @@ -730,22 +729,22 @@ bool Contribution::ProcessReconcileUnblindedTokens( ledger::BalancePtr info, ledger::RewardsType type, double* fee, - braveledger_bat_helper::Directions directions, - braveledger_bat_helper::Directions* leftovers) { + ledger::ReconcileDirections directions, + ledger::ReconcileDirections* leftovers) { if (!fee) { return false; } - auto reconcile = braveledger_bat_helper::CURRENT_RECONCILE(); - reconcile.viewingId_ = ledger_->GenerateGUID(); - reconcile.fee_ = *fee; - reconcile.directions_ = directions; - reconcile.type_ = type; + auto reconcile = ledger::CurrentReconcileProperties(); + reconcile.viewing_id = ledger_->GenerateGUID(); + reconcile.fee = *fee; + reconcile.directions = directions; + reconcile.type = type; - if (ledger_->ReconcileExists(reconcile.viewingId_)) { + if (ledger_->ReconcileExists(reconcile.viewing_id)) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Unable to reconcile with the same viewing id: " - << reconcile.viewingId_; + << reconcile.viewing_id; return false; } @@ -758,26 +757,26 @@ bool Contribution::ProcessReconcileUnblindedTokens( } if (balance >= *fee) { - ledger_->AddReconcile(reconcile.viewingId_, reconcile); - unblinded_->Start(reconcile.viewingId_); + ledger_->AddReconcile(reconcile.viewing_id, reconcile); + unblinded_->Start(reconcile.viewing_id); return true; } *fee = *fee - balance; - reconcile.fee_ = balance; + reconcile.fee = balance; if (type == ledger::RewardsType::RECURRING_TIP || type == ledger::RewardsType::ONE_TIME_TIP) { - braveledger_bat_helper::Directions new_directions; + ledger::ReconcileDirections new_directions; AdjustTipsAmounts(directions, &new_directions, leftovers, balance); - reconcile.directions_ = new_directions; + reconcile.directions = new_directions; } - ledger_->AddReconcile(reconcile.viewingId_, reconcile); - unblinded_->Start(reconcile.viewingId_); + ledger_->AddReconcile(reconcile.viewing_id, reconcile); + unblinded_->Start(reconcile.viewing_id); return false; } @@ -785,22 +784,22 @@ bool Contribution::ProcessReconcileAnonize( ledger::BalancePtr info, ledger::RewardsType type, double* fee, - braveledger_bat_helper::Directions directions, - braveledger_bat_helper::Directions* leftovers) { + ledger::ReconcileDirections directions, + ledger::ReconcileDirections* leftovers) { if (!fee) { return false; } - auto reconcile = braveledger_bat_helper::CURRENT_RECONCILE(); - reconcile.viewingId_ = ledger_->GenerateGUID(); - reconcile.fee_ = *fee; - reconcile.directions_ = directions; - reconcile.type_ = type; + auto reconcile = ledger::CurrentReconcileProperties(); + reconcile.viewing_id = ledger_->GenerateGUID(); + reconcile.fee = *fee; + reconcile.directions = directions; + reconcile.type = type; - if (ledger_->ReconcileExists(reconcile.viewingId_)) { + if (ledger_->ReconcileExists(reconcile.viewing_id)) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Unable to reconcile with the same viewing id: " - << reconcile.viewingId_; + << reconcile.viewing_id; return false; } @@ -812,26 +811,26 @@ bool Contribution::ProcessReconcileAnonize( } if (balance >= *fee) { - ledger_->AddReconcile(reconcile.viewingId_, reconcile); - phase_one_->Start(reconcile.viewingId_); + ledger_->AddReconcile(reconcile.viewing_id, reconcile); + phase_one_->Start(reconcile.viewing_id); return true; } *fee = *fee - balance; - reconcile.fee_ = balance; + reconcile.fee = balance; if (type == ledger::RewardsType::RECURRING_TIP || type == ledger::RewardsType::ONE_TIME_TIP) { - braveledger_bat_helper::Directions new_direction; + ledger::ReconcileDirections new_direction; AdjustTipsAmounts(directions, &new_direction, leftovers, balance); - reconcile.directions_ = new_direction; + reconcile.directions = new_direction; } - ledger_->AddReconcile(reconcile.viewingId_, reconcile); - phase_one_->Start(reconcile.viewingId_); + ledger_->AddReconcile(reconcile.viewing_id, reconcile); + phase_one_->Start(reconcile.viewing_id); return false; } @@ -857,7 +856,7 @@ void Contribution::ProcessReconcile( const auto directions = FromContributionQueuePublishersToReconcileDirections( std::move(contribution->publishers)); - braveledger_bat_helper::Directions anon_directions = directions; + ledger::ReconcileDirections anon_directions = directions; bool result = ProcessReconcileUnblindedTokens( info->Clone(), contribution->type, @@ -870,7 +869,7 @@ void Contribution::ProcessReconcile( return; } - braveledger_bat_helper::Directions wallet_directions = anon_directions; + ledger::ReconcileDirections wallet_directions = anon_directions; result = ProcessReconcileAnonize( info->Clone(), contribution->type, @@ -883,16 +882,16 @@ void Contribution::ProcessReconcile( return; } - auto wallet_reconcile = braveledger_bat_helper::CURRENT_RECONCILE(); - wallet_reconcile.viewingId_ = ledger_->GenerateGUID(); - wallet_reconcile.fee_ = fee; - wallet_reconcile.directions_ = wallet_directions; - wallet_reconcile.type_ = contribution->type; - ledger_->AddReconcile(wallet_reconcile.viewingId_, wallet_reconcile); + auto wallet_reconcile = ledger::CurrentReconcileProperties(); + wallet_reconcile.viewing_id = ledger_->GenerateGUID(); + wallet_reconcile.fee = fee; + wallet_reconcile.directions = wallet_directions; + wallet_reconcile.type = contribution->type; + ledger_->AddReconcile(wallet_reconcile.viewing_id, wallet_reconcile); auto wallets_callback = std::bind(&Contribution::OnExternalWallets, this, - wallet_reconcile.viewingId_, + wallet_reconcile.viewing_id, info->wallets, _1); @@ -902,9 +901,9 @@ void Contribution::ProcessReconcile( } void Contribution::AdjustTipsAmounts( - braveledger_bat_helper::Directions original_directions, - braveledger_bat_helper::Directions* primary_directions, - braveledger_bat_helper::Directions* rest_directions, + ledger::ReconcileDirections original_directions, + ledger::ReconcileDirections* primary_directions, + ledger::ReconcileDirections* rest_directions, double reduce_fee_for) { if (!primary_directions || !rest_directions) { return; @@ -916,20 +915,20 @@ void Contribution::AdjustTipsAmounts( continue; } - if (item.amount_percent_ <= reduce_fee_for) { + if (item.amount_percent <= reduce_fee_for) { primary_directions->push_back(item); - reduce_fee_for -= item.amount_percent_; + reduce_fee_for -= item.amount_percent; continue; } - if (item.amount_percent_ > reduce_fee_for) { + if (item.amount_percent > reduce_fee_for) { // anon wallet - const auto original_weight = item.amount_percent_; - item.amount_percent_ = reduce_fee_for; + const auto original_weight = item.amount_percent; + item.amount_percent = reduce_fee_for; primary_directions->push_back(item); // rest to normal wallet - item.amount_percent_ = original_weight - reduce_fee_for; + item.amount_percent = original_weight - reduce_fee_for; rest_directions->push_back(item); reduce_fee_for = 0; @@ -950,10 +949,10 @@ void Contribution::OnExternalWallets( wallet_balances); const auto reconcile = ledger_->GetReconcileById(viewing_id); - if (wallets.size() == 0 || uphold_balance < reconcile.fee_) { + if (wallets.size() == 0 || uphold_balance < reconcile.fee) { phase_one_->Complete(ledger::Result::NOT_ENOUGH_FUNDS, viewing_id, - reconcile.type_); + reconcile.type); return; } @@ -962,25 +961,25 @@ void Contribution::OnExternalWallets( if (!wallet || wallet->token.empty()) { phase_one_->Complete(ledger::Result::LEDGER_ERROR, viewing_id, - reconcile.type_); + reconcile.type); return; } - if (reconcile.type_ == ledger::RewardsType::AUTO_CONTRIBUTE) { + if (reconcile.type == ledger::RewardsType::AUTO_CONTRIBUTE) { auto callback = std::bind(&Contribution::OnUpholdAC, this, _1, _2, viewing_id); - uphold_->TransferFunds(reconcile.fee_, + uphold_->TransferFunds(reconcile.fee, ledger_->GetCardIdAddress(), std::move(wallet), callback); return; } - for (const auto& item : reconcile.directions_) { - const auto amount = (item.amount_percent_ * reconcile.fee_) / 100; + for (const auto& direction : reconcile.directions) { + const auto amount = (direction.amount_percent * reconcile.fee) / 100; auto callback = std::bind(&Contribution::OnExternalWalletServerPublisherInfo, this, @@ -989,7 +988,7 @@ void Contribution::OnExternalWallets( static_cast(amount), *wallet); - ledger_->GetServerPublisherInfo(item.publisher_key_, callback); + ledger_->GetServerPublisherInfo(direction.publisher_key, callback); } } @@ -1004,7 +1003,7 @@ void Contribution::OnExternalWalletServerPublisherInfo( ledger::Result::LEDGER_ERROR, amount, viewing_id, - reconcile.type_); + reconcile.type); return; } @@ -1012,7 +1011,7 @@ void Contribution::OnExternalWalletServerPublisherInfo( SavePendingContribution( info->publisher_key, amount, - static_cast(reconcile.type_), + static_cast(reconcile.type), [](const ledger::Result _){}); return; } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h index f0eceda255bf..44a879b43ffc 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h @@ -14,7 +14,7 @@ #include "base/gtest_prod_util.h" #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/properties/current_reconcile_properties.h" // Contribution has two big phases. PHASE 1 is starting the contribution, // getting surveyors and transferring BAT from the wallet. @@ -157,7 +157,7 @@ class Contribution { void AddRetry( ledger::ContributionRetry step, const std::string& viewing_id, - braveledger_bat_helper::CURRENT_RECONCILE reconcile = {}); + ledger::CurrentReconcileProperties reconcile = {}); // Resets reconcile stamps void ResetReconcileStamp(); @@ -206,7 +206,7 @@ class Contribution { uint64_t GetRetryTimer(ledger::ContributionRetry step, const std::string& viewing_id, - braveledger_bat_helper::CURRENT_RECONCILE* reconcile); + ledger::CurrentReconcileProperties* reconcile); int GetRetryPhase(ledger::ContributionRetry step); @@ -248,15 +248,15 @@ class Contribution { ledger::BalancePtr info, ledger::RewardsType type, double* fee, - braveledger_bat_helper::Directions directions, - braveledger_bat_helper::Directions* leftovers); + ledger::ReconcileDirections directions, + ledger::ReconcileDirections* leftovers); bool ProcessReconcileAnonize( ledger::BalancePtr info, ledger::RewardsType type, double* fee, - braveledger_bat_helper::Directions directions, - braveledger_bat_helper::Directions* leftovers); + ledger::ReconcileDirections directions, + ledger::ReconcileDirections* leftovers); void ProcessReconcile( ledger::ContributionQueuePtr contribution, @@ -265,9 +265,9 @@ class Contribution { void DeleteContributionQueue(ledger::ContributionQueuePtr contribution); void AdjustTipsAmounts( - braveledger_bat_helper::Directions original_directions, - braveledger_bat_helper::Directions* primary_directions, - braveledger_bat_helper::Directions* rest_directions, + ledger::ReconcileDirections original_directions, + ledger::ReconcileDirections* primary_directions, + ledger::ReconcileDirections* rest_directions, double reduce_fee_for); void OnExternalWallets( 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 19f143e3363e..282bfbaba5dd 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 @@ -156,7 +156,7 @@ void Unblinded::OnUnblindedTokens( continue; } - if (item->value + current_amount > reconcile.fee_) { + if (item->value + current_amount > reconcile.fee) { break; } @@ -168,7 +168,7 @@ void Unblinded::OnUnblindedTokens( ledger_->DeleteUnblindedTokens(delete_list, [](const ledger::Result _){}); } - if (current_amount < reconcile.fee_) { + if (current_amount < reconcile.fee) { ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, viewing_id); return; } @@ -181,28 +181,28 @@ void Unblinded::MakeContribution( ledger::UnblindedTokenList list) { const auto reconcile = ledger_->GetReconcileById(viewing_id); - if (reconcile.type_ == ledger::RewardsType::ONE_TIME_TIP || - reconcile.type_ == ledger::RewardsType::RECURRING_TIP) { + if (reconcile.type == ledger::RewardsType::ONE_TIME_TIP || + reconcile.type == ledger::RewardsType::RECURRING_TIP) { const auto callback = std::bind(&Unblinded::ContributionCompleted, this, _1, viewing_id); SendTokens( - reconcile.directions_.front().publisher_key_, - reconcile.type_, + reconcile.directions.front().publisher_key, + reconcile.type, std::move(list), callback); return; } - if (reconcile.type_ == ledger::RewardsType::AUTO_CONTRIBUTE) { + if (reconcile.type == ledger::RewardsType::AUTO_CONTRIBUTE) { PrepareAutoContribution(viewing_id, std::move(list)); } } bool Unblinded::GetStatisticalVotingWinner( double dart, - const braveledger_bat_helper::Directions& directions, + const ledger::ReconcileDirections& directions, Winners* winners) const { if (!winners) { return false; @@ -210,19 +210,19 @@ bool Unblinded::GetStatisticalVotingWinner( double upper = 0.0; for (const auto& item : directions) { - upper += item.amount_percent_ / 100.0; + upper += item.amount_percent / 100.0; if (upper < dart) { continue; } - auto iter = winners->find(item.publisher_key_); + auto iter = winners->find(item.publisher_key); uint32_t current_value = 0; if (iter != winners->end()) { - current_value = winners->at(item.publisher_key_); - winners->at(item.publisher_key_) = current_value + 1; + current_value = winners->at(item.publisher_key); + winners->at(item.publisher_key) = current_value + 1; } else { - winners->emplace(item.publisher_key_, 1); + winners->emplace(item.publisher_key, 1); } return true; @@ -233,7 +233,7 @@ bool Unblinded::GetStatisticalVotingWinner( void Unblinded::GetStatisticalVotingWinners( uint32_t total_votes, - const braveledger_bat_helper::Directions& directions, + const ledger::ReconcileDirections& directions, Winners* winners) const { while (total_votes > 0) { double dart = brave_base::random::Uniform_01(); @@ -254,18 +254,18 @@ void Unblinded::PrepareAutoContribution( auto reconcile = ledger_->GetReconcileById(viewing_id); const double total_votes = static_cast(list.size()); Winners winners; - GetStatisticalVotingWinners(total_votes, reconcile.directions_, &winners); + GetStatisticalVotingWinners(total_votes, reconcile.directions, &winners); - braveledger_bat_helper::Directions new_directions; + ledger::ReconcileDirections new_directions; uint32_t current_position = 0; for (auto & winner : winners) { if (winner.second == 0) { continue; } - braveledger_bat_helper::RECONCILE_DIRECTION direction; - direction.publisher_key_ = winner.first; - direction.amount_percent_ = (winner.second / total_votes) * 100; + ledger::ReconcileDirectionProperties direction; + direction.publisher_key = winner.first; + direction.amount_percent = (winner.second / total_votes) * 100; new_directions.push_back(direction); const uint32_t new_position = current_position + winner.second; @@ -282,7 +282,7 @@ void Unblinded::PrepareAutoContribution( [](const ledger::Result _){}); } - reconcile.directions_ = new_directions; + reconcile.directions = new_directions; ledger_->UpdateReconcile(reconcile); ContributionCompleted(ledger::Result::LEDGER_OK, viewing_id); @@ -349,9 +349,9 @@ void Unblinded::ContributionCompleted( const auto reconcile = ledger_->GetReconcileById(viewing_id); ledger_->ReconcileComplete( result, - reconcile.fee_, + reconcile.fee, viewing_id, - reconcile.type_); + reconcile.type); } } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h index 45526f1368b9..793e25f6f3b0 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h @@ -13,7 +13,7 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" namespace bat_ledger { class LedgerImpl; @@ -44,7 +44,7 @@ class Unblinded { bool GetStatisticalVotingWinner( double dart, - const braveledger_bat_helper::Directions& directions, + const ledger::ReconcileDirections& directions, Winners* winners) const; void PrepareAutoContribution( @@ -53,7 +53,7 @@ class Unblinded { void GetStatisticalVotingWinners( uint32_t total_votes, - const braveledger_bat_helper::Directions& directions, + const ledger::ReconcileDirections& directions, Winners* winners) const; void SendTokens( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc index fd4b47bef010..a139e6edaeeb 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc @@ -38,8 +38,8 @@ class UnblindedTest : public ::testing::Test { ON_CALL(*mock_ledger_impl_, GetReconcileById(_)) .WillByDefault( Invoke([](const std::string& viewing_id) { - braveledger_bat_helper::CURRENT_RECONCILE reconcile; - reconcile.fee_ = 5.0; + ledger::CurrentReconcileProperties reconcile; + reconcile.fee = 5.0; return reconcile; })); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc index 4767ca4f407d..d1c8d4179cb9 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unittest.cc @@ -7,7 +7,6 @@ #include #include -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/contribution/contribution.h" #include "bat/ledger/internal/logging.h" #include "bat/ledger/internal/ledger_impl.h" diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc index 3850dfcb3a0f..6834acbeaac8 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.cc @@ -9,19 +9,19 @@ namespace braveledger_contribution { -braveledger_bat_helper::Directions +ledger::ReconcileDirections FromContributionQueuePublishersToReconcileDirections( ledger::ContributionQueuePublisherList list) { - braveledger_bat_helper::Directions directions; + ledger::ReconcileDirections directions; for (auto& item : list) { if (!item || item->publisher_key.empty()) { continue; } - const auto direction = braveledger_bat_helper::RECONCILE_DIRECTION( - item->publisher_key, - item->amount_percent); + ledger::ReconcileDirectionProperties direction; + direction.publisher_key = item->publisher_key, + direction.amount_percent = item->amount_percent; directions.push_back(direction); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h index 0b5faa0e078f..f11bd220dc05 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_util.h @@ -10,11 +10,11 @@ #include #include "bat/ledger/mojom_structs.h" -#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" namespace braveledger_contribution { -braveledger_bat_helper::Directions +ledger::ReconcileDirections FromContributionQueuePublishersToReconcileDirections( ledger::ContributionQueuePublisherList list); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.cc index 89dceb539201..cf134bcf546f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.cc @@ -11,6 +11,14 @@ #include "bat/ledger/internal/contribution/phase_two.h" #include "bat/ledger/internal/bat_util.h" #include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/properties/reconcile_request_properties.h" +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "bat/ledger/internal/properties/unsigned_tx_properties.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" +#include "bat/ledger/internal/state/reconcile_request_state.h" +#include "bat/ledger/internal/state/transaction_state.h" +#include "bat/ledger/internal/state/unsigned_tx_state.h" #include "net/http/http_status_code.h" using std::placeholders::_1; @@ -58,7 +66,7 @@ void PhaseOne::ReconcileCallback( auto reconcile = ledger_->GetReconcileById(viewing_id); - if (response_status_code != net::HTTP_OK || reconcile.viewingId_.empty()) { + if (response_status_code != net::HTTP_OK || reconcile.viewing_id.empty()) { contribution_->AddRetry(ledger::ContributionRetry::STEP_RECONCILE, viewing_id); return; @@ -67,7 +75,7 @@ void PhaseOne::ReconcileCallback( bool success = braveledger_bat_helper::getJSONValue( SURVEYOR_ID, response, - &reconcile.surveyorInfo_.surveyorId_); + &reconcile.surveyor_id); if (!success) { contribution_->AddRetry(ledger::ContributionRetry::STEP_RECONCILE, viewing_id); @@ -76,7 +84,7 @@ void PhaseOne::ReconcileCallback( success = ledger_->UpdateReconcile(reconcile); if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type_); + Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); return; } @@ -89,7 +97,7 @@ void PhaseOne::CurrentReconcile(const std::string& viewing_id) { std::ostringstream amount; auto reconcile = ledger_->GetReconcileById(viewing_id); - amount << reconcile.fee_; + amount << reconcile.fee; std::string currency = ledger_->GetCurrency(); std::string path = (std::string)WALLET_PROPERTIES + @@ -131,44 +139,46 @@ void PhaseOne::CurrentReconcileCallback( auto reconcile = ledger_->GetReconcileById(viewing_id); bool success = braveledger_bat_helper::getJSONRates(response, - &reconcile.rates_); + &reconcile.rates); if (!success) { contribution_->AddRetry(ledger::ContributionRetry::STEP_CURRENT, viewing_id); return; } - braveledger_bat_helper::UNSIGNED_TX unsigned_tx; - success = braveledger_bat_helper::getJSONUnsignedTx(response, &unsigned_tx); + ledger::UnsignedTxProperties unsigned_tx; + const ledger::UnsignedTxState unsigned_tx_state; + success = unsigned_tx_state.FromJsonResponse(response, &unsigned_tx); + if (!success) { contribution_->AddRetry(ledger::ContributionRetry::STEP_CURRENT, viewing_id); return; } - if (unsigned_tx.amount_.empty() && - unsigned_tx.currency_.empty() && - unsigned_tx.destination_.empty()) { + if (unsigned_tx.amount.empty() && + unsigned_tx.currency.empty() && + unsigned_tx.destination.empty()) { // We don't have any unsigned transactions contribution_->AddRetry(ledger::ContributionRetry::STEP_CURRENT, viewing_id); return; } - reconcile.amount_ = unsigned_tx.amount_; - reconcile.currency_ = unsigned_tx.currency_; - reconcile.destination_ = unsigned_tx.destination_; + reconcile.amount = unsigned_tx.amount; + reconcile.currency = unsigned_tx.currency; + reconcile.destination = unsigned_tx.destination; if (ledger::is_testing) { std::ostringstream amount; - amount << reconcile.fee_; - reconcile.amount_ = amount.str(); + amount << reconcile.fee; + reconcile.amount = amount.str(); } success = ledger_->UpdateReconcile(reconcile); if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type_); + Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); return; } @@ -179,13 +189,14 @@ void PhaseOne::ReconcilePayload(const std::string& viewing_id) { ledger_->AddReconcileStep(viewing_id, ledger::ContributionRetry::STEP_PAYLOAD); auto reconcile = ledger_->GetReconcileById(viewing_id); - braveledger_bat_helper::WALLET_INFO_ST wallet_info = ledger_->GetWalletInfo(); + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); - braveledger_bat_helper::UNSIGNED_TX unsigned_tx; - unsigned_tx.amount_ = reconcile.amount_; - unsigned_tx.currency_ = reconcile.currency_; - unsigned_tx.destination_ = reconcile.destination_; - std::string octets = braveledger_bat_helper::stringifyUnsignedTx(unsigned_tx); + ledger::UnsignedTxProperties unsigned_tx; + unsigned_tx.amount = reconcile.amount; + unsigned_tx.currency = reconcile.currency; + unsigned_tx.destination = reconcile.destination; + const ledger::UnsignedTxState unsigned_tx_state; + std::string octets = unsigned_tx_state.ToJson(unsigned_tx); std::string header_digest = "SHA-256=" + braveledger_bat_helper::getBase64( @@ -197,7 +208,7 @@ void PhaseOne::ReconcilePayload(const std::string& viewing_id) { header_values.push_back(header_digest); std::vector secret_key = braveledger_bat_helper::getHKDF( - wallet_info.keyInfoSeed_); + wallet_info.key_info_seed); std::vector public_key; std::vector new_secret_key; bool success = braveledger_bat_helper::getPublicKeyFromSeed( @@ -215,16 +226,17 @@ void PhaseOne::ReconcilePayload(const std::string& viewing_id) { "primary", new_secret_key); - braveledger_bat_helper::RECONCILE_PAYLOAD_ST reconcile_payload; - reconcile_payload.requestType_ = "httpSignature"; - reconcile_payload.request_signedtx_headers_digest_ = header_digest; - reconcile_payload.request_signedtx_headers_signature_ = headerSignature; - reconcile_payload.request_signedtx_body_ = unsigned_tx; - reconcile_payload.request_signedtx_octets_ = octets; - reconcile_payload.request_viewingId_ = reconcile.viewingId_; - reconcile_payload.request_surveyorId_ = reconcile.surveyorInfo_.surveyorId_; + ledger::ReconcileRequestProperties reconcile_request; + reconcile_request.type = "httpSignature"; + reconcile_request.signed_tx_headers_digest = header_digest; + reconcile_request.signed_tx_headers_signature = headerSignature; + reconcile_request.signed_tx_body = unsigned_tx; + reconcile_request.signed_tx_octets = octets; + reconcile_request.viewing_id = reconcile.viewing_id; + reconcile_request.surveyor_id = reconcile.surveyor_id; + const ledger::ReconcileRequestState reconcile_request_state; std::string payload_stringify = - braveledger_bat_helper::stringifyReconcilePayloadSt(reconcile_payload); + reconcile_request_state.ToJson(reconcile_request); std::vector wallet_header; wallet_header.push_back("Content-Type: application/json; charset=UTF-8"); @@ -259,7 +271,7 @@ void PhaseOne::ReconcilePayloadCallback( Complete( ledger::Result::CONTRIBUTION_AMOUNT_TOO_LOW, viewing_id, - reconcile.type_); + reconcile.type); } else { contribution_->AddRetry(ledger::ContributionRetry::STEP_PAYLOAD, viewing_id); @@ -267,26 +279,25 @@ void PhaseOne::ReconcilePayloadCallback( return; } - braveledger_bat_helper::TRANSACTION_ST transaction; - bool success = braveledger_bat_helper::getJSONTransaction(response, - &transaction); + ledger::TransactionProperties transaction; + const ledger::TransactionState transaction_state; + bool success = transaction_state.FromJsonResponse(response, &transaction); if (!success) { contribution_->AddRetry(ledger::ContributionRetry::STEP_PAYLOAD, viewing_id); return; } - transaction.viewingId_ = reconcile.viewingId_; - transaction.surveyorId_ = reconcile.surveyorInfo_.surveyorId_; - transaction.contribution_rates_ = reconcile.rates_; + transaction.viewing_id = reconcile.viewing_id; + transaction.surveyor_id = reconcile.surveyor_id; + transaction.contribution_rates = reconcile.rates; if (ledger::is_testing) { - transaction.contribution_probi_ = - braveledger_bat_util::ConvertToProbi(reconcile.amount_); + transaction.contribution_probi = + braveledger_bat_util::ConvertToProbi(reconcile.amount); } - braveledger_bat_helper::Transactions transactions = - ledger_->GetTransactions(); + ledger::Transactions transactions = ledger_->GetTransactions(); transactions.push_back(transaction); ledger_->SetTransactions(transactions); RegisterViewing(viewing_id); @@ -328,28 +339,28 @@ void PhaseOne::RegisterViewingCallback( bool success = braveledger_bat_helper::getJSONValue(REGISTRARVK_FIELDNAME, response, - &reconcile.registrarVK_); - DCHECK(!reconcile.registrarVK_.empty()); - if (!success || reconcile.registrarVK_.empty()) { + &reconcile.registrar_vk); + DCHECK(!reconcile.registrar_vk.empty()); + if (!success || reconcile.registrar_vk.empty()) { contribution_->AddRetry(ledger::ContributionRetry::STEP_REGISTER, viewing_id); return; } - reconcile.anonizeViewingId_ = reconcile.viewingId_; - reconcile.anonizeViewingId_.erase( - std::remove(reconcile.anonizeViewingId_.begin(), - reconcile.anonizeViewingId_.end(), + reconcile.anonize_viewing_id = reconcile.viewing_id; + reconcile.anonize_viewing_id.erase( + std::remove(reconcile.anonize_viewing_id.begin(), + reconcile.anonize_viewing_id.end(), '-'), - reconcile.anonizeViewingId_.end()); - reconcile.anonizeViewingId_.erase(12, 1); - reconcile.proof_ = GetAnonizeProof(reconcile.registrarVK_, - reconcile.anonizeViewingId_, - &reconcile.preFlight_); + reconcile.anonize_viewing_id.end()); + reconcile.anonize_viewing_id.erase(12, 1); + reconcile.proof = GetAnonizeProof(reconcile.registrar_vk, + reconcile.anonize_viewing_id, + &reconcile.pre_flight); success = ledger_->UpdateReconcile(reconcile); if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type_); + Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); return; } @@ -390,7 +401,7 @@ void PhaseOne::ViewingCredentials(const std::string& viewing_id) { auto reconcile = ledger_->GetReconcileById(viewing_id); std::string keys[1] = {"proof"}; - std::string values[1] = {reconcile.proof_}; + std::string values[1] = {reconcile.proof}; std::string proof_stringified = braveledger_bat_helper::stringify(keys, values, 1); @@ -398,7 +409,7 @@ void PhaseOne::ViewingCredentials(const std::string& viewing_id) { std::string url = braveledger_request_util::BuildUrl( (std::string)REGISTER_VIEWING + "/" + - reconcile.anonizeViewingId_, + reconcile.anonize_viewing_id, PREFIX_V2); auto callback = std::bind(&PhaseOne::ViewingCredentialsCallback, @@ -441,13 +452,13 @@ void PhaseOne::ViewingCredentialsCallback( } const char* master_user_token = registerUserFinal( - reconcile.anonizeViewingId_.c_str(), + reconcile.anonize_viewing_id.c_str(), verification.c_str(), - reconcile.preFlight_.c_str(), - reconcile.registrarVK_.c_str()); + reconcile.pre_flight.c_str(), + reconcile.registrar_vk.c_str()); if (master_user_token != nullptr) { - reconcile.masterUserToken_ = master_user_token; + reconcile.master_user_token = master_user_token; // should fix in // https://github.com/brave-intl/bat-native-anonize/issues/11 free((void*)master_user_token); // NOLINT @@ -455,7 +466,7 @@ void PhaseOne::ViewingCredentialsCallback( success = ledger_->UpdateReconcile(reconcile); if (!success) { - Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type_); + Complete(ledger::Result::LEDGER_ERROR, viewing_id, reconcile.type); return; } @@ -471,25 +482,24 @@ void PhaseOne::ViewingCredentialsCallback( std::string probi = "0"; // Save the rest values to transactions - braveledger_bat_helper::Transactions transactions = - ledger_->GetTransactions(); + ledger::Transactions transactions = ledger_->GetTransactions(); for (size_t i = 0; i < transactions.size(); i++) { - if (transactions[i].viewingId_ != reconcile.viewingId_) { + if (transactions[i].viewing_id != reconcile.viewing_id) { continue; } - transactions[i].anonizeViewingId_ = reconcile.anonizeViewingId_; - transactions[i].registrarVK_ = reconcile.registrarVK_; - transactions[i].masterUserToken_ = reconcile.masterUserToken_; - transactions[i].surveyorIds_ = surveyors; - probi = transactions[i].contribution_probi_; + transactions[i].anonize_viewing_id = reconcile.anonize_viewing_id; + transactions[i].registrar_vk = reconcile.registrar_vk; + transactions[i].master_user_token = reconcile.master_user_token; + transactions[i].surveyor_ids = surveyors; + probi = transactions[i].contribution_probi; } ledger_->SetTransactions(transactions); Complete(ledger::Result::LEDGER_OK, - reconcile.viewingId_, - reconcile.type_, + reconcile.viewing_id, + reconcile.type, probi); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.h index 65429e76f023..1ca6c94056ad 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_one.h @@ -12,7 +12,6 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/contribution/contribution.h" namespace bat_ledger { diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.cc index 5575038f0668..3c21d1b70f60 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.cc @@ -9,8 +9,16 @@ #include "base/task/post_task.h" #include "base/task_runner_util.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" +#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/properties/ballot_properties.h" +#include "bat/ledger/internal/properties/batch_proof_properties.h" +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" +#include "bat/ledger/internal/properties/transaction_ballot_properties.h" +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "bat/ledger/internal/properties/winner_properties.h" +#include "bat/ledger/internal/state/publisher_vote_state.h" +#include "bat/ledger/internal/state/surveyor_state.h" #include "brave_base/random.h" #include "net/http/http_status_code.h" @@ -44,20 +52,20 @@ void PhaseTwo::Start(const std::string& viewing_id) { unsigned int ballots_count = GetBallotsCount(viewing_id); const auto reconcile = ledger_->GetReconcileById(viewing_id); - switch (reconcile.type_) { + switch (reconcile.type) { case ledger::RewardsType::AUTO_CONTRIBUTE: { - GetContributeWinners(ballots_count, viewing_id, reconcile.directions_); + GetContributeWinners(ballots_count, viewing_id, reconcile.directions); break; } case ledger::RewardsType::RECURRING_TIP: case ledger::RewardsType::ONE_TIME_TIP: { - braveledger_bat_helper::WINNERS_ST winner; - winner.votes_ = ballots_count; - winner.direction_.publisher_key_ = - reconcile.directions_.front().publisher_key_; - winner.direction_.amount_percent_ = 100.0; - VotePublishers(braveledger_bat_helper::Winners { winner }, viewing_id); + ledger::WinnerProperties winner; + winner.vote_count = ballots_count; + winner.direction.publisher_key = + reconcile.directions.front().publisher_key; + winner.direction.amount_percent = 100.0; + VotePublishers(ledger::Winners { winner }, viewing_id); break; } @@ -70,12 +78,11 @@ void PhaseTwo::Start(const std::string& viewing_id) { unsigned int PhaseTwo::GetBallotsCount( const std::string& viewing_id) { unsigned int count = 0; - braveledger_bat_helper::Transactions transactions = - ledger_->GetTransactions(); + ledger::Transactions transactions = ledger_->GetTransactions(); for (size_t i = 0; i < transactions.size(); i++) { - if (transactions[i].votes_ < transactions[i].surveyorIds_.size() - && transactions[i].viewingId_ == viewing_id) { - count += transactions[i].surveyorIds_.size() - transactions[i].votes_; + if (transactions[i].vote_count < transactions[i].surveyor_ids.size() + && transactions[i].viewing_id == viewing_id) { + count += transactions[i].surveyor_ids.size() - transactions[i].vote_count; } } @@ -84,16 +91,16 @@ unsigned int PhaseTwo::GetBallotsCount( bool PhaseTwo::GetStatisticalVotingWinner( double dart, - const braveledger_bat_helper::Directions& directions, - braveledger_bat_helper::WINNERS_ST* winner) { + const ledger::ReconcileDirections& directions, + ledger::WinnerProperties* winner) { double upper = 0.0; - for (const auto& item : directions) { - upper += item.amount_percent_ / 100.0; + for (const auto& direction : directions) { + upper += direction.amount_percent / 100.0; if (upper < dart) continue; - winner->votes_ = 1; - winner->direction_ = item; + winner->vote_count = 1; + winner->direction = direction; return true; } @@ -101,14 +108,14 @@ bool PhaseTwo::GetStatisticalVotingWinner( return false; } -braveledger_bat_helper::Winners PhaseTwo::GetStatisticalVotingWinners( +ledger::Winners PhaseTwo::GetStatisticalVotingWinners( uint32_t total_votes, - const braveledger_bat_helper::Directions& directions) { - braveledger_bat_helper::Winners winners; + const ledger::ReconcileDirections& directions) { + ledger::Winners winners; while (total_votes > 0) { double dart = brave_base::random::Uniform_01(); - braveledger_bat_helper::WINNERS_ST winner; + ledger::WinnerProperties winner; if (GetStatisticalVotingWinner(dart, directions, &winner)) { winners.push_back(winner); --total_votes; @@ -121,19 +128,18 @@ braveledger_bat_helper::Winners PhaseTwo::GetStatisticalVotingWinners( void PhaseTwo::GetContributeWinners( const unsigned int ballots, const std::string& viewing_id, - const braveledger_bat_helper::Directions& directions) { - braveledger_bat_helper::Winners winners = - GetStatisticalVotingWinners(ballots, directions); + const ledger::ReconcileDirections& directions) { + ledger::Winners winners = GetStatisticalVotingWinners(ballots, directions); VotePublishers(winners, viewing_id); } void PhaseTwo::VotePublishers( - const braveledger_bat_helper::Winners& winners, + const ledger::Winners& winners, const std::string& viewing_id) { std::vector publishers; for (size_t i = 0; i < winners.size(); i++) { - for (size_t j = 0; j < winners[i].votes_; j++) { - publishers.push_back(winners[i].direction_.publisher_key_); + for (size_t j = 0; j < winners[i].vote_count; j++) { + publishers.push_back(winners[i].direction.publisher_key); } } @@ -154,11 +160,10 @@ void PhaseTwo::VotePublisher(const std::string& publisher, return; } - braveledger_bat_helper::BALLOT_ST ballot; + ledger::BallotProperties ballot; int i = 0; - braveledger_bat_helper::Transactions transactions = - ledger_->GetTransactions(); + ledger::Transactions transactions = ledger_->GetTransactions(); if (transactions.size() == 0) { // TODO(nejczdovc) what should we do in this case? @@ -166,11 +171,11 @@ void PhaseTwo::VotePublisher(const std::string& publisher, } for (i = transactions.size() - 1; i >=0; i--) { - if (transactions[i].votes_ >= transactions[i].surveyorIds_.size()) { + if (transactions[i].vote_count >= transactions[i].surveyor_ids.size()) { continue; } - if (transactions[i].viewingId_ == viewing_id || viewing_id.empty()) { + if (transactions[i].viewing_id == viewing_id || viewing_id.empty()) { break; } } @@ -181,13 +186,13 @@ void PhaseTwo::VotePublisher(const std::string& publisher, return; } - ballot.viewingId_ = transactions[i].viewingId_; - ballot.surveyorId_ = transactions[i].surveyorIds_[transactions[i].votes_]; - ballot.publisher_ = publisher; - ballot.offset_ = transactions[i].votes_; - transactions[i].votes_++; + ballot.viewing_id = transactions[i].viewing_id; + ballot.surveyor_id = transactions[i].surveyor_ids[transactions[i].vote_count]; + ballot.publisher = publisher; + ballot.count = transactions[i].vote_count; + transactions[i].vote_count++; - braveledger_bat_helper::Ballots ballots = ledger_->GetBallots(); + ledger::Ballots ballots = ledger_->GetBallots(); ballots.push_back(ballot); ledger_->SetTransactions(transactions); @@ -195,9 +200,8 @@ void PhaseTwo::VotePublisher(const std::string& publisher, } void PhaseTwo::PrepareBallots() { - braveledger_bat_helper::Transactions transactions = - ledger_->GetTransactions(); - braveledger_bat_helper::Ballots ballots = ledger_->GetBallots(); + ledger::Transactions transactions = ledger_->GetTransactions(); + ledger::Ballots ballots = ledger_->GetBallots(); if (ballots.size() == 0) { // skip ballots and start sending votes @@ -207,13 +211,13 @@ void PhaseTwo::PrepareBallots() { for (int i = ballots.size() - 1; i >= 0; i--) { for (size_t j = 0; j < transactions.size(); j++) { - if (transactions[j].viewingId_ == ballots[i].viewingId_) { - if (ballots[i].prepareBallot_.empty()) { + if (transactions[j].viewing_id == ballots[i].viewing_id) { + if (ballots[i].prepare_ballot.empty()) { PrepareBatch(ballots[i], transactions[j]); return; } - if (ballots[i].proofBallot_.empty()) { + if (ballots[i].proof_ballot.empty()) { Proof(); return; } @@ -226,16 +230,16 @@ void PhaseTwo::PrepareBallots() { } void PhaseTwo::PrepareBatch( - const braveledger_bat_helper::BALLOT_ST& ballot, - const braveledger_bat_helper::TRANSACTION_ST& transaction) { + const ledger::BallotProperties& ballot, + const ledger::TransactionProperties& transaction) { std::string url = braveledger_request_util::BuildUrl( (std::string)SURVEYOR_BATCH_VOTING + "/" + - transaction.anonizeViewingId_, PREFIX_V2); + transaction.anonize_viewing_id, PREFIX_V2); auto callback = std::bind(&PhaseTwo::PrepareBatchCallback, this, - transaction.viewingId_, + transaction.viewing_id, _1, _2, _3); @@ -250,7 +254,7 @@ void PhaseTwo::PrepareBatch( void PhaseTwo::AssignPrepareBallots( const std::string& viewing_id, const std::vector& surveyors, - braveledger_bat_helper::Ballots* ballots) { + ledger::Ballots* ballots) { for (size_t j = 0; j < surveyors.size(); j++) { std::string error; braveledger_bat_helper::getJSONValue("error", surveyors[j], &error); @@ -269,9 +273,9 @@ void PhaseTwo::AssignPrepareBallots( } for (auto& ballot : *ballots) { - if (ballot.surveyorId_ == surveyor_id && - ballot.viewingId_ == viewing_id) { - ballot.prepareBallot_ = surveyors[j]; + if (ballot.surveyor_id == surveyor_id && + ballot.viewing_id == viewing_id) { + ballot.prepare_ballot = surveyors[j]; } } } @@ -297,7 +301,7 @@ void PhaseTwo::PrepareBatchCallback( return; } - braveledger_bat_helper::Ballots ballots = ledger_->GetBallots(); + ledger::Ballots ballots = ledger_->GetBallots(); AssignPrepareBallots(viewing_id, surveyors, &ballots); @@ -306,25 +310,24 @@ void PhaseTwo::PrepareBatchCallback( } void PhaseTwo::Proof() { - braveledger_bat_helper::BatchProofs batch_proofs; + ledger::BatchProofs batch_proofs; - braveledger_bat_helper::Transactions transactions = - ledger_->GetTransactions(); - braveledger_bat_helper::Ballots ballots = ledger_->GetBallots(); + ledger::Transactions transactions = ledger_->GetTransactions(); + ledger::Ballots ballots = ledger_->GetBallots(); for (int i = ballots.size() - 1; i >= 0; i--) { for (size_t k = 0; k < transactions.size(); k++) { - if (transactions[k].viewingId_ == ballots[i].viewingId_) { - if (ballots[i].prepareBallot_.empty()) { + if (transactions[k].viewing_id == ballots[i].viewing_id) { + if (ballots[i].prepare_ballot.empty()) { // TODO(nejczdovc) what should we do here return; } - if (ballots[i].proofBallot_.empty()) { - braveledger_bat_helper::BATCH_PROOF batch_proof_el; - batch_proof_el.transaction_ = transactions[k]; - batch_proof_el.ballot_ = ballots[i]; - batch_proofs.push_back(batch_proof_el); + if (ballots[i].proof_ballot.empty()) { + ledger::BatchProofProperties batch_proof; + batch_proof.transaction = transactions[k]; + batch_proof.ballot = ballots[i]; + batch_proofs.push_back(batch_proof); } } } @@ -352,27 +355,27 @@ void PhaseTwo::Proof() { } std::vector PhaseTwo::ProofBatch( - const braveledger_bat_helper::BatchProofs& batch_proofs) { + const ledger::BatchProofs& batch_proofs) { std::vector proofs; for (size_t i = 0; i < batch_proofs.size(); i++) { - braveledger_bat_helper::SURVEYOR_ST surveyor; - bool success = braveledger_bat_helper::loadFromJson( - &surveyor, - batch_proofs[i].ballot_.prepareBallot_); + ledger::SurveyorProperties surveyor; + const ledger::SurveyorState surveyor_state; + bool success = surveyor_state.FromJson( + batch_proofs[i].ballot.prepare_ballot, &surveyor); if (!success) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Failed to load surveyor state: " << - batch_proofs[i].ballot_.prepareBallot_; + batch_proofs[i].ballot.prepare_ballot; continue; } std::string signature_to_send; - size_t delimeter_pos = surveyor.signature_.find(','); + size_t delimeter_pos = surveyor.signature.find(','); if (std::string::npos != delimeter_pos && - delimeter_pos + 1 <= surveyor.signature_.length()) { - signature_to_send = surveyor.signature_.substr(delimeter_pos + 1); + delimeter_pos + 1 <= surveyor.signature.length()) { + signature_to_send = surveyor.signature.substr(delimeter_pos + 1); if (signature_to_send.length() > 1 && signature_to_send[0] == ' ') { signature_to_send.erase(0, 1); @@ -384,16 +387,16 @@ std::vector PhaseTwo::ProofBatch( } std::string msg_key[1] = {"publisher"}; - std::string msg_value[1] = {batch_proofs[i].ballot_.publisher_}; + std::string msg_value[1] = {batch_proofs[i].ballot.publisher}; std::string msg = braveledger_bat_helper::stringify(msg_key, msg_value, 1); const char* proof = submitMessage( msg.c_str(), - batch_proofs[i].transaction_.masterUserToken_.c_str(), - batch_proofs[i].transaction_.registrarVK_.c_str(), + batch_proofs[i].transaction.master_user_token.c_str(), + batch_proofs[i].transaction.registrar_vk.c_str(), signature_to_send.c_str(), - surveyor.surveyorId_.c_str(), - surveyor.surveyVK_.c_str()); + surveyor.surveyor_id.c_str(), + surveyor.survey_vk.c_str()); std::string annon_proof; if (proof != nullptr) { @@ -410,23 +413,23 @@ std::vector PhaseTwo::ProofBatch( } void PhaseTwo::AssignProofs( - const braveledger_bat_helper::BatchProofs& batch_proofs, + const ledger::BatchProofs& batch_proofs, const std::vector& proofs, - braveledger_bat_helper::Ballots* ballots) { + ledger::Ballots* ballots) { for (size_t i = 0; i < batch_proofs.size(); i++) { for (auto& ballot : *ballots) { - if (ballot.surveyorId_ == batch_proofs[i].ballot_.surveyorId_ && - ballot.viewingId_ == batch_proofs[i].ballot_.viewingId_) { - ballot.proofBallot_ = proofs[i]; + if (ballot.surveyor_id == batch_proofs[i].ballot.surveyor_id && + ballot.viewing_id == batch_proofs[i].ballot.viewing_id) { + ballot.proof_ballot = proofs[i]; } } } } void PhaseTwo::ProofBatchCallback( - const braveledger_bat_helper::BatchProofs& batch_proofs, + const ledger::BatchProofs& batch_proofs, const std::vector& proofs) { - braveledger_bat_helper::Ballots ballots = ledger_->GetBallots(); + ledger::Ballots ballots = ledger_->GetBallots(); AssignProofs(batch_proofs, proofs, &ballots); @@ -441,10 +444,9 @@ void PhaseTwo::ProofBatchCallback( } void PhaseTwo::PrepareVoteBatch() { - braveledger_bat_helper::Transactions transactions = - ledger_->GetTransactions(); - braveledger_bat_helper::Ballots ballots = ledger_->GetBallots(); - braveledger_bat_helper::BatchVotes batch = ledger_->GetBatch(); + ledger::Transactions transactions = ledger_->GetTransactions(); + ledger::Ballots ballots = ledger_->GetBallots(); + ledger::PublisherVotes publisher_votes = ledger_->GetPublisherVotes(); if (ballots.size() == 0) { contribution_->SetTimer(&last_vote_batch_timer_id_); @@ -452,28 +454,30 @@ void PhaseTwo::PrepareVoteBatch() { } for (int i = ballots.size() - 1; i >= 0; i--) { - if (ballots[i].prepareBallot_.empty() || ballots[i].proofBallot_.empty()) { + if (ballots[i].prepare_ballot.empty() || ballots[i].proof_ballot.empty()) { // TODO(nejczdovc) what to do in this case continue; } bool transaction_exit = false; for (size_t k = 0; k < transactions.size(); k++) { - if (transactions[k].viewingId_ == ballots[i].viewingId_) { + if (transactions[k].viewing_id == ballots[i].viewing_id) { bool ballot_exit = false; - for (size_t j = 0; j < transactions[k].ballots_.size(); j++) { - if (transactions[k].ballots_[j].publisher_ == ballots[i].publisher_) { - transactions[k].ballots_[j].offset_++; + for (size_t j = 0; j < transactions[k].transaction_ballots.size(); + j++) { + if (transactions[k].transaction_ballots[j].publisher == + ballots[i].publisher) { + transactions[k].transaction_ballots[j].count++; ballot_exit = true; break; } } if (!ballot_exit) { - braveledger_bat_helper::TRANSACTION_BALLOT_ST transactionBallot; - transactionBallot.publisher_ = ballots[i].publisher_; - transactionBallot.offset_++; - transactions[k].ballots_.push_back(transactionBallot); + ledger::TransactionBallotProperties transactionBallot; + transactionBallot.publisher = ballots[i].publisher; + transactionBallot.count++; + transactions[k].transaction_ballots.push_back(transactionBallot); } transaction_exit = true; break; @@ -486,22 +490,22 @@ void PhaseTwo::PrepareVoteBatch() { } bool exist_batch = false; - braveledger_bat_helper::BATCH_VOTES_INFO_ST batchVotesInfoSt; - batchVotesInfoSt.surveyorId_ = ballots[i].surveyorId_; - batchVotesInfoSt.proof_ = ballots[i].proofBallot_; + ledger::PublisherVoteProperties publisher_vote; + publisher_vote.surveyor_id = ballots[i].surveyor_id; + publisher_vote.proof = ballots[i].proof_ballot; - for (size_t k = 0; k < batch.size(); k++) { - if (batch[k].publisher_ == ballots[i].publisher_) { + for (size_t k = 0; k < publisher_votes.size(); k++) { + if (publisher_votes[k].publisher == ballots[i].publisher) { exist_batch = true; - batch[k].batchVotesInfo_.push_back(batchVotesInfoSt); + publisher_votes[k].batch_votes.push_back(publisher_vote); } } if (!exist_batch) { - braveledger_bat_helper::BATCH_VOTES_ST batchVotesSt; - batchVotesSt.publisher_ = ballots[i].publisher_; - batchVotesSt.batchVotesInfo_.push_back(batchVotesInfoSt); - batch.push_back(batchVotesSt); + ledger::PublisherVotesProperties new_publisher_votes; + new_publisher_votes.publisher = ballots[i].publisher; + new_publisher_votes.batch_votes.push_back(publisher_vote); + publisher_votes.push_back(new_publisher_votes); } ballots.erase(ballots.begin() + i); @@ -509,34 +513,36 @@ void PhaseTwo::PrepareVoteBatch() { ledger_->SetTransactions(transactions); ledger_->SetBallots(ballots); - ledger_->SetBatch(batch); + ledger_->SetPublisherVotes(publisher_votes); contribution_->SetTimer(&last_vote_batch_timer_id_); } void PhaseTwo::VoteBatch() { - braveledger_bat_helper::BatchVotes batch = ledger_->GetBatch(); - if (batch.size() == 0) { + ledger::PublisherVotes publisher_votes = ledger_->GetPublisherVotes(); + if (publisher_votes.size() == 0) { return; } - braveledger_bat_helper::BATCH_VOTES_ST batch_votes = batch[0]; - std::vector vote_batch; + ledger::PublisherVotesProperties publisher_votes_properties = + publisher_votes[0]; + ledger::BatchVotes batch_votes; - if (batch_votes.batchVotesInfo_.size() > VOTE_BATCH_SIZE) { - vote_batch.assign(batch_votes.batchVotesInfo_.begin(), - batch_votes.batchVotesInfo_.begin() + VOTE_BATCH_SIZE); + if (publisher_votes_properties.batch_votes.size() > VOTE_BATCH_SIZE) { + batch_votes.assign(publisher_votes_properties.batch_votes.begin(), + publisher_votes_properties.batch_votes.begin() + VOTE_BATCH_SIZE); } else { - vote_batch = batch_votes.batchVotesInfo_; + batch_votes = publisher_votes_properties.batch_votes; } - std::string payload = braveledger_bat_helper::stringifyBatch(vote_batch); + const ledger::PublisherVoteState publisher_vote_state; + std::string payload = publisher_vote_state.ToJson(batch_votes); std::string url = braveledger_request_util::BuildUrl( - (std::string)SURVEYOR_BATCH_VOTING , - PREFIX_V2); + (std::string)SURVEYOR_BATCH_VOTING, + PREFIX_V2); auto callback = std::bind(&PhaseTwo::VoteBatchCallback, this, - batch_votes.publisher_, + publisher_votes_properties.publisher, _1, _2, _3); @@ -568,13 +574,13 @@ void PhaseTwo::VoteBatchCallback( return; } - braveledger_bat_helper::BatchVotes batch = ledger_->GetBatch(); + ledger::PublisherVotes publisher_votes = ledger_->GetPublisherVotes(); - for (size_t i = 0; i < batch.size(); i++) { - if (batch[i].publisher_ == publisher) { + for (size_t i = 0; i < publisher_votes.size(); i++) { + if (publisher_votes[i].publisher == publisher) { size_t sizeToCheck = VOTE_BATCH_SIZE; - if (batch[i].batchVotesInfo_.size() < VOTE_BATCH_SIZE) { - sizeToCheck = batch[i].batchVotesInfo_.size(); + if (publisher_votes[i].batch_votes.size() < VOTE_BATCH_SIZE) { + sizeToCheck = publisher_votes[i].batch_votes.size(); } for (int j = sizeToCheck - 1; j >= 0; j--) { @@ -588,24 +594,24 @@ void PhaseTwo::VoteBatchCallback( continue; } - if (surveyor_id == batch[i].batchVotesInfo_[j].surveyorId_) { - batch[i].batchVotesInfo_.erase( - batch[i].batchVotesInfo_.begin() + j); + if (surveyor_id == publisher_votes[i].batch_votes[j].surveyor_id) { + publisher_votes[i].batch_votes.erase( + publisher_votes[i].batch_votes.begin() + j); break; } } } - if (batch[i].batchVotesInfo_.size() == 0) { - batch.erase(batch.begin() + i); + if (publisher_votes[i].batch_votes.size() == 0) { + publisher_votes.erase(publisher_votes.begin() + i); } break; } } - ledger_->SetBatch(batch); + ledger_->SetPublisherVotes(publisher_votes); - if (batch.size() > 0) { + if (publisher_votes.size() > 0) { contribution_->SetTimer(&last_vote_batch_timer_id_); } } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.h index cb3a21dc3e62..fd0ed5118dfc 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two.h @@ -13,8 +13,12 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/contribution/contribution.h" +#include "bat/ledger/internal/properties/ballot_properties.h" +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" +#include "bat/ledger/internal/properties/winner_properties.h" +#include "bat/ledger/internal/properties/batch_proof_properties.h" namespace bat_ledger { class LedgerImpl; @@ -47,30 +51,30 @@ class PhaseTwo { bool GetStatisticalVotingWinner( double dart, - const braveledger_bat_helper::Directions& list, - braveledger_bat_helper::WINNERS_ST* winner); + const ledger::ReconcileDirections& list, + ledger::WinnerProperties* winner); - braveledger_bat_helper::Winners GetStatisticalVotingWinners( + ledger::Winners GetStatisticalVotingWinners( uint32_t total_votes, - const braveledger_bat_helper::Directions& list); + const ledger::ReconcileDirections& list); void GetContributeWinners( const unsigned int ballots, const std::string& viewing_id, - const braveledger_bat_helper::Directions& list); + const ledger::ReconcileDirections& list); void GetTipsWinners(const unsigned int ballots, const std::string& viewing_id); - void VotePublishers(const braveledger_bat_helper::Winners& winners, + void VotePublishers(const ledger::Winners& winners, const std::string& viewing_id); void VotePublisher(const std::string& publisher, const std::string& viewing_id); void PrepareBatch( - const braveledger_bat_helper::BALLOT_ST& ballot, - const braveledger_bat_helper::TRANSACTION_ST& transaction); + const ledger::BallotProperties& ballot, + const ledger::TransactionProperties& transaction); void PrepareBatchCallback( const std::string& viewing_id, @@ -81,20 +85,20 @@ class PhaseTwo { static void AssignPrepareBallots( const std::string& viewing_id, const std::vector& surveyors, - braveledger_bat_helper::Ballots* ballots); + ledger::Ballots* ballots); std::vector ProofBatch( - const braveledger_bat_helper::BatchProofs& batch_proofs); + const ledger::BatchProofs& batch_proofs); void PrepareVoteBatch(); static void AssignProofs( - const braveledger_bat_helper::BatchProofs& batch_proofs, + const ledger::BatchProofs& batch_proofs, const std::vector& proofs, - braveledger_bat_helper::Ballots* ballots); + ledger::Ballots* ballots); void ProofBatchCallback( - const braveledger_bat_helper::BatchProofs& batch_proofs, + const ledger::BatchProofs& batch_proofs, const std::vector& proofs); void VoteBatchCallback( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc index b96caad5c777..2abd38fba307 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/phase_two_unittest.cc @@ -7,9 +7,9 @@ #include #include -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/contribution/phase_two.h" #include "bat/ledger/internal/logging.h" +#include "bat/ledger/internal/properties/ballot_properties.h" #include "bat/ledger/ledger.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,27 +19,27 @@ namespace braveledger_contribution { class PhaseTwoTest : public testing::Test { protected: - void PopulateDirectionsList(braveledger_bat_helper::Directions* list) { - braveledger_bat_helper::RECONCILE_DIRECTION publisher; + void PopulateDirectionsList(ledger::ReconcileDirections* list) { + ledger::ReconcileDirectionProperties publisher; - publisher.publisher_key_ = "publisher1"; - publisher.amount_percent_ = 2.0; + publisher.publisher_key = "publisher1"; + publisher.amount_percent = 2.0; list->push_back(publisher); - publisher.publisher_key_ = "publisher2"; - publisher.amount_percent_ = 13.0; + publisher.publisher_key = "publisher2"; + publisher.amount_percent = 13.0; list->push_back(publisher); - publisher.publisher_key_ = "publisher3"; - publisher.amount_percent_ = 14.0; + publisher.publisher_key = "publisher3"; + publisher.amount_percent = 14.0; list->push_back(publisher); - publisher.publisher_key_ = "publisher4"; - publisher.amount_percent_ = 23.0; + publisher.publisher_key = "publisher4"; + publisher.amount_percent = 23.0; list->push_back(publisher); - publisher.publisher_key_ = "publisher5"; - publisher.amount_percent_ = 38.0; + publisher.publisher_key = "publisher5"; + publisher.amount_percent = 38.0; list->push_back(publisher); } }; @@ -48,7 +48,7 @@ TEST_F(PhaseTwoTest, GetStatisticalVotingWinners) { auto phase_two = std::make_unique(nullptr, nullptr); - braveledger_bat_helper::Directions list; + ledger::ReconcileDirections list; PopulateDirectionsList(&list); struct { @@ -69,11 +69,11 @@ TEST_F(PhaseTwoTest, GetStatisticalVotingWinners) { }; for (size_t i = 0; i < base::size(cases); i++) { - braveledger_bat_helper::WINNERS_ST winner; + ledger::WinnerProperties winner; bool result = phase_two->GetStatisticalVotingWinner( cases[i].dart, list, &winner); EXPECT_TRUE(result); - EXPECT_STREQ(winner.direction_.publisher_key_.c_str(), cases[i].publisher); + EXPECT_STREQ(winner.direction.publisher_key.c_str(), cases[i].publisher); } } @@ -88,18 +88,18 @@ TEST_F(PhaseTwoTest, AssignPrepareBallotsRespectsViewingID) { }; // Create ballots with different viewing IDs but the same surveyor ID. - braveledger_bat_helper::Ballots ballots(2); - ballots[0].viewingId_ = "00000000-0000-0000-0000-000000000000"; - ballots[0].surveyorId_ = shared_surveyor_id; - ballots[1].viewingId_ = "ffffffff-ffff-ffff-ffff-ffffffffffff"; - ballots[1].surveyorId_ = shared_surveyor_id; + ledger::Ballots ballots(2); + ballots[0].viewing_id = "00000000-0000-0000-0000-000000000000"; + ballots[0].surveyor_id = shared_surveyor_id; + ballots[1].viewing_id = "ffffffff-ffff-ffff-ffff-ffffffffffff"; + ballots[1].surveyor_id = shared_surveyor_id; // Check that only ballot[0] with the matching viewing ID is updated. Ballot 1 // should remain unmodified. PhaseTwo::AssignPrepareBallots("00000000-0000-0000-0000-000000000000", surveyors, &ballots); - ASSERT_FALSE(ballots[0].prepareBallot_.empty()); - ASSERT_TRUE(ballots[1].prepareBallot_.empty()); + ASSERT_FALSE(ballots[0].prepare_ballot.empty()); + ASSERT_TRUE(ballots[1].prepare_ballot.empty()); } // Surveyor IDs may be reused between transactions. Ensure that proofs for @@ -110,19 +110,19 @@ TEST_F(PhaseTwoTest, AssignProofsRespectsViewingID) { const std::string shared_surveyor_id = "Ad5pNzrwhWokTOR8/hC83LWJfEy8aY7mFwPQWe6CpRF"; - braveledger_bat_helper::Ballots ballots(2); - ballots[0].viewingId_ = "00000000-0000-0000-0000-000000000000"; - ballots[0].surveyorId_ = shared_surveyor_id; - ballots[1].viewingId_ = "ffffffff-ffff-ffff-ffff-ffffffffffff"; - ballots[1].surveyorId_ = shared_surveyor_id; + ledger::Ballots ballots(2); + ballots[0].viewing_id = "00000000-0000-0000-0000-000000000000"; + ballots[0].surveyor_id = shared_surveyor_id; + ballots[1].viewing_id = "ffffffff-ffff-ffff-ffff-ffffffffffff"; + ballots[1].surveyor_id = shared_surveyor_id; - braveledger_bat_helper::BatchProofs batch_proofs(2); - batch_proofs[0].ballot_ = ballots[0]; - batch_proofs[1].ballot_ = ballots[1]; + ledger::BatchProofs batch_proofs(2); + batch_proofs[0].ballot = ballots[0]; + batch_proofs[1].ballot = ballots[1]; PhaseTwo::AssignProofs(batch_proofs, proofs, &ballots); - ASSERT_EQ(ballots[0].proofBallot_, proofs[0]); - ASSERT_EQ(ballots[1].proofBallot_, proofs[1]); + ASSERT_EQ(ballots[0].proof_ballot, proofs[0]); + ASSERT_EQ(ballots[1].proof_ballot, proofs[1]); } } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.h index 52bf2536f1ea..212d69f4cb60 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/unverified.h @@ -14,7 +14,6 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/contribution/contribution.h" namespace bat_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 fa83ab9b7948..35566ee39682 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 @@ -19,13 +19,12 @@ #include "bat/ads/notification_info.h" #include "bat/confirmations/confirmations.h" #include "bat/ledger/internal/media/media.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/publisher/publisher.h" +#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/bat_state.h" #include "bat/ledger/internal/promotion/promotion.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/helper.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" #include "bat/ledger/internal/static_values.h" #include "net/http/http_status_code.h" @@ -134,7 +133,7 @@ void LedgerImpl::CreateWallet(const std::string& safetynet_token, bat_wallet_->CreateWalletIfNecessary(safetynet_token, std::move(on_wallet)); } -braveledger_bat_helper::CURRENT_RECONCILE LedgerImpl::GetReconcileById( +ledger::CurrentReconcileProperties LedgerImpl::GetReconcileById( const std::string& viewingId) { return bat_state_->GetReconcileById(viewingId); } @@ -320,7 +319,7 @@ void LedgerImpl::OnLedgerStateLoaded( } void LedgerImpl::SetConfirmationsWalletInfo( - const braveledger_bat_helper::WALLET_INFO_ST& wallet_info) { + const ledger::WalletInfoProperties& wallet_info) { if (!bat_confirmations_) { confirmations::_environment = ledger::_environment; confirmations::_is_debug = ledger::is_debug; @@ -631,7 +630,7 @@ void LedgerImpl::ReconcileComplete( void LedgerImpl::OnWalletProperties( ledger::Result result, - const braveledger_bat_helper::WALLET_PROPERTIES_ST& properties) { + const ledger::WalletProperties& properties) { ledger::WalletPropertiesPtr wallet; if (result == ledger::Result::LEDGER_OK) { @@ -879,13 +878,13 @@ void LedgerImpl::ResetReconcileStamp() { } bool LedgerImpl::UpdateReconcile( - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile) { + const ledger::CurrentReconcileProperties& reconcile) { return bat_state_->UpdateReconcile(reconcile); } void LedgerImpl::AddReconcile( const std::string& viewing_id, - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile) { + const ledger::CurrentReconcileProperties& reconcile) { bat_state_->AddReconcile(viewing_id, reconcile); } @@ -925,29 +924,28 @@ void LedgerImpl::SetPreFlight(const std::string& pre_flight) { bat_state_->SetPreFlight(pre_flight); } -const braveledger_bat_helper::WALLET_INFO_ST& -LedgerImpl::GetWalletInfo() const { +const ledger::WalletInfoProperties& LedgerImpl::GetWalletInfo() const { return bat_state_->GetWalletInfo(); } void LedgerImpl::SetWalletInfo( - const braveledger_bat_helper::WALLET_INFO_ST& info) { + const ledger::WalletInfoProperties& info) { bat_state_->SetWalletInfo(info); SetConfirmationsWalletInfo(info); } const confirmations::WalletInfo LedgerImpl::GetConfirmationsWalletInfo( - const braveledger_bat_helper::WALLET_INFO_ST& info) const { + const ledger::WalletInfoProperties& info) const { confirmations::WalletInfo wallet_info; - wallet_info.payment_id = info.paymentId_; + wallet_info.payment_id = info.payment_id; - if (info.keyInfoSeed_.empty()) { + if (info.key_info_seed.empty()) { return wallet_info; } - auto seed = braveledger_bat_helper::getHKDF(info.keyInfoSeed_); + auto seed = braveledger_bat_helper::getHKDF(info.key_info_seed); std::vector publicKey = {}; std::vector secretKey = {}; braveledger_bat_helper::getPublicKeyFromSeed(seed, &publicKey, &secretKey); @@ -974,13 +972,12 @@ void LedgerImpl::GetRewardsInternalsInfo( info->boot_stamp = bat_state_->GetBootStamp(); // Retrieve the key info seed and validate it. - const braveledger_bat_helper::WALLET_INFO_ST wallet_info = - bat_state_->GetWalletInfo(); - if (wallet_info.keyInfoSeed_.size() != SEED_LENGTH) { + const ledger::WalletInfoProperties wallet_info = bat_state_->GetWalletInfo(); + if (wallet_info.key_info_seed.size() != SEED_LENGTH) { info->is_key_info_seed_valid = false; } else { std::vector secret_key = - braveledger_bat_helper::getHKDF(wallet_info.keyInfoSeed_); + braveledger_bat_helper::getHKDF(wallet_info.key_info_seed); std::vector public_key; std::vector new_secret_key; info->is_key_info_seed_valid = braveledger_bat_helper::getPublicKeyFromSeed( @@ -988,16 +985,15 @@ void LedgerImpl::GetRewardsInternalsInfo( } // Retrieve the current reconciles. - const braveledger_bat_helper::CurrentReconciles current_reconciles = - GetCurrentReconciles(); + const ledger::CurrentReconciles current_reconciles = GetCurrentReconciles(); for (const auto& reconcile : current_reconciles) { ledger::ReconcileInfoPtr reconcile_info = ledger::ReconcileInfo::New(); - reconcile_info->viewing_id = reconcile.second.viewingId_; - reconcile_info->amount = reconcile.second.amount_; - reconcile_info->retry_step = reconcile.second.retry_step_; - reconcile_info->retry_level = reconcile.second.retry_level_; + reconcile_info->viewing_id = reconcile.second.viewing_id; + reconcile_info->amount = reconcile.second.amount; + reconcile_info->retry_step = reconcile.second.retry_step; + reconcile_info->retry_level = reconcile.second.retry_level; info->current_reconciles.insert( - std::make_pair(reconcile.second.viewingId_, std::move(reconcile_info))); + std::make_pair(reconcile.second.viewing_id, std::move(reconcile_info))); } callback(std::move(info)); @@ -1007,13 +1003,12 @@ void LedgerImpl::StartMonthlyContribution() { bat_contribution_->StartMonthlyContribution(); } -const braveledger_bat_helper::WALLET_PROPERTIES_ST& -LedgerImpl::GetWalletProperties() const { +const ledger::WalletProperties& LedgerImpl::GetWalletProperties() const { return bat_state_->GetWalletProperties(); } void LedgerImpl::SetWalletProperties( - braveledger_bat_helper::WALLET_PROPERTIES_ST* properties) { + ledger::WalletProperties* properties) { bat_state_->SetWalletProperties(properties); } @@ -1025,30 +1020,30 @@ void LedgerImpl::SetDays(unsigned int days) { bat_state_->SetDays(days); } -const braveledger_bat_helper::Transactions& -LedgerImpl::GetTransactions() const { +const ledger::Transactions& LedgerImpl::GetTransactions() const { return bat_state_->GetTransactions(); } void LedgerImpl::SetTransactions( - const braveledger_bat_helper::Transactions& transactions) { + const ledger::Transactions& transactions) { bat_state_->SetTransactions(transactions); } -const braveledger_bat_helper::Ballots& LedgerImpl::GetBallots() const { +const ledger::Ballots& LedgerImpl::GetBallots() const { return bat_state_->GetBallots(); } -void LedgerImpl::SetBallots(const braveledger_bat_helper::Ballots& ballots) { +void LedgerImpl::SetBallots(const ledger::Ballots& ballots) { bat_state_->SetBallots(ballots); } -const braveledger_bat_helper::BatchVotes& LedgerImpl::GetBatch() const { - return bat_state_->GetBatch(); +const ledger::PublisherVotes& LedgerImpl::GetPublisherVotes() const { + return bat_state_->GetPublisherVotes(); } -void LedgerImpl::SetBatch(const braveledger_bat_helper::BatchVotes& votes) { - bat_state_->SetBatch(votes); +void LedgerImpl::SetPublisherVotes( + const ledger::PublisherVotes& publisher_votes) { + bat_state_->SetPublisherVotes(publisher_votes); } const std::string& LedgerImpl::GetCurrency() const { @@ -1108,8 +1103,7 @@ bool LedgerImpl::AddReconcileStep( return bat_state_->AddReconcileStep(viewing_id, step, level); } -const braveledger_bat_helper::CurrentReconciles& -LedgerImpl::GetCurrentReconciles() const { +const ledger::CurrentReconciles& LedgerImpl::GetCurrentReconciles() const { return bat_state_->GetCurrentReconciles(); } 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 fbdfb03a9fee..11024312b51b 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 @@ -17,12 +17,15 @@ #include "base/memory/scoped_refptr.h" #include "bat/confirmations/confirmations_client.h" #include "bat/ledger/internal/contribution/contribution.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/logging.h" +#include "bat/ledger/internal/properties/ballot_properties.h" +#include "bat/ledger/internal/properties/publisher_votes_properties.h" +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/internal/wallet/wallet.h" -#include "bat/ledger/ledger.h" #include "bat/ledger/ledger_callback_handler.h" #include "bat/ledger/ledger_client.h" +#include "bat/ledger/ledger.h" namespace base { class SequencedTaskRunner; @@ -167,7 +170,7 @@ class LedgerImpl : public ledger::Ledger, void LoadNicewareList(ledger::GetNicewareListCallback callback); void SetConfirmationsWalletInfo( - const braveledger_bat_helper::WALLET_INFO_ST& wallet_info); + const ledger::WalletInfoProperties& wallet_info); void LoadLedgerState(ledger::OnLoadCallback callback); @@ -177,7 +180,7 @@ class LedgerImpl : public ledger::Ledger, ledger::InitializeCallback callback); void OnWalletProperties(ledger::Result result, - const braveledger_bat_helper::WALLET_PROPERTIES_ST&); + const ledger::WalletProperties&); void FetchWalletProperties( ledger::OnWalletPropertiesCallback callback) const override; @@ -267,7 +270,7 @@ class LedgerImpl : public ledger::Ledger, ledger::ReportType type, const std::string& probi) override; - virtual braveledger_bat_helper::CURRENT_RECONCILE GetReconcileById( + virtual ledger::CurrentReconcileProperties GetReconcileById( const std::string& viewingId); void RemoveReconcileById(const std::string& viewingId); @@ -308,11 +311,11 @@ class LedgerImpl : public ledger::Ledger, void ResetReconcileStamp(); bool UpdateReconcile( - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile); + const ledger::CurrentReconcileProperties& reconcile); void AddReconcile( const std::string& viewing_id, - const braveledger_bat_helper::CURRENT_RECONCILE& reconcile); + const ledger::CurrentReconcileProperties& reconcile); const std::string& GetPaymentId() const; @@ -332,37 +335,36 @@ class LedgerImpl : public ledger::Ledger, void SetPreFlight(const std::string& pre_flight); - const braveledger_bat_helper::WALLET_INFO_ST& GetWalletInfo() const; + const ledger::WalletInfoProperties& GetWalletInfo() const; - void SetWalletInfo(const braveledger_bat_helper::WALLET_INFO_ST& info); + void SetWalletInfo(const ledger::WalletInfoProperties& info); const confirmations::WalletInfo GetConfirmationsWalletInfo( - const braveledger_bat_helper::WALLET_INFO_ST& info) const; + const ledger::WalletInfoProperties& info) const; - const braveledger_bat_helper::WALLET_PROPERTIES_ST& - GetWalletProperties() const; + const ledger::WalletProperties& GetWalletProperties() const; void SetWalletProperties( - braveledger_bat_helper::WALLET_PROPERTIES_ST* properties); + ledger::WalletProperties* properties); unsigned int GetDays() const; void SetDays(unsigned int days); - const braveledger_bat_helper::Transactions& GetTransactions() const; + const ledger::Transactions& GetTransactions() const; void SetTransactions( - const braveledger_bat_helper::Transactions& transactions); + const ledger::Transactions& transactions); - const braveledger_bat_helper::Ballots& GetBallots() const; + const ledger::Ballots& GetBallots() const; void SetBallots( - const braveledger_bat_helper::Ballots& ballots); + const ledger::Ballots& ballots); - const braveledger_bat_helper::BatchVotes& GetBatch() const; + const ledger::PublisherVotes& GetPublisherVotes() const; - void SetBatch( - const braveledger_bat_helper::BatchVotes& votes); + void SetPublisherVotes( + const ledger::PublisherVotes& publisher_votes); const std::string& GetCurrency() const; @@ -393,7 +395,7 @@ class LedgerImpl : public ledger::Ledger, ledger::ContributionRetry step, int level = -1); - const braveledger_bat_helper::CurrentReconciles& GetCurrentReconciles() const; + const ledger::CurrentReconciles& GetCurrentReconciles() const; double GetDefaultContributionAmount() override; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h index 9418ade79c82..5efd9f16eb8c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h @@ -144,7 +144,7 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD1(LoadNicewareList, void(ledger::GetNicewareListCallback)); MOCK_METHOD1(SetConfirmationsWalletInfo, - void(const braveledger_bat_helper::WALLET_INFO_ST&)); + void(const ledger::WalletInfoProperties&)); MOCK_METHOD1(LoadLedgerState, void(ledger::OnLoadCallback)); @@ -155,7 +155,7 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD2(OnWalletProperties, void(ledger::Result, - const braveledger_bat_helper::WALLET_PROPERTIES_ST&)); + const ledger::WalletProperties&)); MOCK_CONST_METHOD1(FetchWalletProperties, void(const ledger::OnWalletPropertiesCallback)); @@ -237,7 +237,7 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD1(GetReconcileById, - braveledger_bat_helper::CURRENT_RECONCILE(const std::string&)); + ledger::CurrentReconcileProperties(const std::string&)); MOCK_METHOD1(RemoveReconcileById, void(const std::string&)); @@ -284,11 +284,11 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD0(ResetReconcileStamp, void()); MOCK_METHOD1(UpdateReconcile, - bool(const braveledger_bat_helper::CURRENT_RECONCILE&)); + bool(const ledger::CurrentReconcileProperties&)); MOCK_METHOD2(AddReconcile, void(const std::string&, - const braveledger_bat_helper::CURRENT_RECONCILE&)); + const ledger::CurrentReconcileProperties&)); MOCK_CONST_METHOD0(GetPaymentId, const std::string&()); @@ -309,38 +309,38 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD1(SetPreFlight, void(const std::string&)); MOCK_CONST_METHOD0(GetWalletInfo, - const braveledger_bat_helper::WALLET_INFO_ST&()); + const ledger::WalletInfoProperties&()); MOCK_METHOD1(SetWalletInfo, - void(const braveledger_bat_helper::WALLET_INFO_ST&)); + void(const ledger::WalletInfoProperties&)); MOCK_METHOD1(GetConfirmationsWalletInfo, const confirmations::WalletInfo( - const braveledger_bat_helper::WALLET_INFO_ST&)); + const ledger::WalletInfoProperties&)); MOCK_CONST_METHOD0(GetWalletProperties, - const braveledger_bat_helper::WALLET_PROPERTIES_ST&()); + const ledger::WalletProperties&()); MOCK_METHOD1(SetWalletProperties, - void(braveledger_bat_helper::WALLET_PROPERTIES_ST*)); + void(ledger::WalletProperties*)); MOCK_CONST_METHOD0(GetDays, unsigned int()); MOCK_METHOD1(SetDays, void(unsigned int)); MOCK_CONST_METHOD0(GetTransactions, - const braveledger_bat_helper::Transactions&()); + const ledger::Transactions&()); MOCK_METHOD1(SetTransactions, - void(const braveledger_bat_helper::Transactions&)); + void(const ledger::Transactions&)); - MOCK_CONST_METHOD0(GetBallots, const braveledger_bat_helper::Ballots&()); + MOCK_CONST_METHOD0(GetBallots, const ledger::Ballots&()); - MOCK_METHOD1(SetBallots, void(const braveledger_bat_helper::Ballots&)); + MOCK_METHOD1(SetBallots, void(const ledger::Ballots&)); - MOCK_CONST_METHOD0(GetBatch, const braveledger_bat_helper::BatchVotes&()); + MOCK_CONST_METHOD0(GetBatch, const ledger::BatchVotes&()); - MOCK_METHOD1(SetBatch, void(const braveledger_bat_helper::BatchVotes&)); + MOCK_METHOD1(SetBatch, void(const ledger::BatchVotes&)); MOCK_CONST_METHOD0(GetCurrency, const std::string&()); @@ -377,7 +377,7 @@ class MockLedgerImpl : public LedgerImpl { int)); MOCK_CONST_METHOD0(GetCurrentReconciles, - const braveledger_bat_helper::CurrentReconciles&()); + const ledger::CurrentReconciles&()); MOCK_METHOD0(GetDefaultContributionAmount, double()); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/media/github.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/media/github.cc index a837a7425a24..8c238c4c0c83 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/media/github.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/media/github.cc @@ -14,6 +14,7 @@ #include "base/strings/utf_string_conversions.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/github.h" +#include "bat/ledger/internal/static_values.h" #include "net/http/http_status_code.h" using std::placeholders::_1; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.cc index 3eb263162d8a..2219e422e1d5 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.cc @@ -8,6 +8,7 @@ #include "bat/ledger/internal/media/media.h" #include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/static_values.h" using std::placeholders::_1; using std::placeholders::_2; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.h b/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.h index 3389216c6178..86bb0669792c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/media/media.h @@ -10,7 +10,6 @@ #include #include -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/media/reddit.h" #include "bat/ledger/internal/media/twitch.h" #include "bat/ledger/internal/media/twitter.h" diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/media/reddit.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/media/reddit.cc index 613c433a385a..4cea027ba5b1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/media/reddit.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/media/reddit.cc @@ -12,6 +12,7 @@ #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/helper.h" #include "bat/ledger/internal/media/reddit.h" +#include "bat/ledger/internal/static_values.h" #include "net/http/http_status_code.h" #include "url/url_canon.h" #include "url/gurl.h" diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/media/twitter.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/media/twitter.cc index 25edd0e17496..a9d9c8976218 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/media/twitter.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/media/twitter.cc @@ -14,6 +14,7 @@ #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/helper.h" #include "bat/ledger/internal/media/twitter.h" +#include "bat/ledger/internal/static_values.h" #include "net/base/url_util.h" #include "net/http/http_status_code.h" #include "url/gurl.h" diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/media/vimeo.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/media/vimeo.cc index 50d3fe4177a0..247a16cc16e4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/media/vimeo.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/media/vimeo.cc @@ -10,9 +10,9 @@ #include "base/json/json_reader.h" #include "base/strings/stringprintf.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/vimeo.h" +#include "bat/ledger/internal/static_values.h" #include "net/http/http_status_code.h" using std::placeholders::_1; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/media/youtube.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/media/youtube.cc index a535bca8d010..bf6d2ef5894f 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/media/youtube.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/media/youtube.cc @@ -7,6 +7,7 @@ #include #include +#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/media/helper.h" #include "bat/ledger/internal/media/youtube.h" 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 1b0b18c50e36..fcab302320a0 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 @@ -14,9 +14,9 @@ #include "base/time/time.h" #include "bat/ledger/internal/bat_util.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/state_keys.h" #include "bat/ledger/internal/static_values.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/internal/request/promotion_requests.h" #include "bat/ledger/internal/request/request_util.h" #include "bat/ledger/internal/common/bind_util.h" @@ -63,7 +63,7 @@ void Promotion::Fetch(ledger::FetchPromotionCallback callback) { if (wallet_payment_id.empty() || passphrase.empty()) { ledger::PromotionList empty_list; callback(ledger::Result::CORRUPTED_WALLET, std::move(empty_list)); - braveledger_bat_helper::WALLET_PROPERTIES_ST properties; + ledger::WalletProperties properties; ledger_->OnWalletProperties(ledger::Result::CORRUPTED_WALLET, properties); return; } @@ -384,13 +384,13 @@ void Promotion::ClaimTokens( std::string json; base::JSONWriter::Write(body, &json); - braveledger_bat_helper::WALLET_INFO_ST wallet_info = ledger_->GetWalletInfo(); + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); const auto headers = braveledger_request_util::BuildSignHeaders( "post /v1/promotions/" + promotion->id, json, ledger_->GetPaymentId(), - wallet_info.keyInfoSeed_); + wallet_info.key_info_seed); const std::string url = braveledger_request_util::ClaimTokensUrl(promotion->id); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.cc new file mode 100644 index 000000000000..4568bf17bd5d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.cc @@ -0,0 +1,39 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/ballot_properties.h" + +namespace ledger { + +BallotProperties::BallotProperties() = default; + +BallotProperties::BallotProperties( + const BallotProperties& properties) { + viewing_id = properties.viewing_id; + surveyor_id = properties.surveyor_id; + publisher = properties.publisher; + count = properties.count; + prepare_ballot = properties.prepare_ballot; + proof_ballot = properties.proof_ballot; +} + +BallotProperties::~BallotProperties() = default; + +bool BallotProperties::operator==( + const BallotProperties& rhs) const { + return viewing_id == rhs.viewing_id && + surveyor_id == rhs.surveyor_id && + publisher == rhs.publisher && + count == rhs.count && + prepare_ballot == rhs.prepare_ballot && + proof_ballot == rhs.proof_ballot; +} + +bool BallotProperties::operator!=( + const BallotProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.h new file mode 100644 index 000000000000..04d88c2e42c9 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/ballot_properties.h @@ -0,0 +1,39 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_BALLOT_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_BALLOT_PROPERTIES_H_ + +#include +#include +#include + +namespace ledger { + +struct BallotProperties { + BallotProperties(); + BallotProperties( + const BallotProperties& properties); + ~BallotProperties(); + + bool operator==( + const BallotProperties& rhs) const; + + bool operator!=( + const BallotProperties& rhs) const; + + std::string viewing_id; + std::string surveyor_id; + std::string publisher; + uint32_t count; + std::string prepare_ballot; + std::string proof_ballot; +}; + +typedef std::vector Ballots; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_BALLOT_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.cc new file mode 100644 index 000000000000..a8ac6ee695e4 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.cc @@ -0,0 +1,31 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/batch_proof_properties.h" + +namespace ledger { + +BatchProofProperties::BatchProofProperties() = default; + +BatchProofProperties::BatchProofProperties( + const BatchProofProperties& properties) { + transaction = properties.transaction; + ballot = properties.ballot; +} + +BatchProofProperties::~BatchProofProperties() = default; + +bool BatchProofProperties::operator==( + const BatchProofProperties& rhs) const { + return transaction == rhs.transaction && + ballot == rhs.ballot; +} + +bool BatchProofProperties::operator!=( + const BatchProofProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.h new file mode 100644 index 000000000000..e20b0eb76eab --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/batch_proof_properties.h @@ -0,0 +1,36 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_BATCH_PROOF_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_BATCH_PROOF_PROPERTIES_H_ + +#include + +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "bat/ledger/internal/properties/ballot_properties.h" + +namespace ledger { + +struct BatchProofProperties { + BatchProofProperties(); + BatchProofProperties( + const BatchProofProperties& properties); + ~BatchProofProperties(); + + bool operator==( + const BatchProofProperties& rhs) const; + + bool operator!=( + const BatchProofProperties& rhs) const; + + TransactionProperties transaction; + BallotProperties ballot; +}; + +typedef std::vector BatchProofs; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_BATCH_PROOF_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.cc new file mode 100644 index 000000000000..5fbe7dbb22be --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.cc @@ -0,0 +1,78 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/client_properties.h" +#include "bat/ledger/internal/static_values.h" + +namespace ledger { + +ClientProperties::ClientProperties() + : boot_timestamp(0), + reconcile_timestamp(0), + settings(AD_FREE_SETTINGS), + fee_amount(0), + user_changed_fee(false), + days(0), + auto_contribute(false), + rewards_enabled(false) {} + +ClientProperties::ClientProperties( + const ClientProperties& properties) { + wallet = properties.wallet; + wallet_info = properties.wallet_info; + boot_timestamp = properties.boot_timestamp; + reconcile_timestamp = properties.reconcile_timestamp; + persona_id = properties.persona_id; + user_id = properties.user_id; + registrar_vk = properties.registrar_vk; + master_user_token = properties.master_user_token; + pre_flight = properties.pre_flight; + fee_currency = properties.fee_currency; + settings = properties.settings; + fee_amount = properties.fee_amount; + user_changed_fee = properties.user_changed_fee; + days = properties.days; + transactions = properties.transactions; + ballots = properties.ballots; + publisher_votes = properties.publisher_votes; + auto_contribute = properties.auto_contribute; + rewards_enabled = properties.rewards_enabled; + current_reconciles = properties.current_reconciles; + inline_tips = properties.inline_tips; +} + +ClientProperties::~ClientProperties() = default; + +bool ClientProperties::operator==( + const ClientProperties& rhs) const { + return wallet.Equals(rhs.wallet) && + wallet_info == rhs.wallet_info && + boot_timestamp == rhs.boot_timestamp && + reconcile_timestamp == rhs.reconcile_timestamp && + persona_id == rhs.persona_id && + user_id == rhs.user_id && + registrar_vk == rhs.registrar_vk && + master_user_token == rhs.master_user_token && + pre_flight == rhs.pre_flight && + fee_currency == rhs.fee_currency && + settings == rhs.settings && + fee_amount == rhs.fee_amount && + user_changed_fee == rhs.user_changed_fee && + days == rhs.days && + transactions == rhs.transactions && + ballots == rhs.ballots && + publisher_votes == rhs.publisher_votes && + auto_contribute == rhs.auto_contribute && + rewards_enabled == rhs.rewards_enabled && + current_reconciles == rhs.current_reconciles && + inline_tips == rhs.inline_tips; +} + +bool ClientProperties::operator!=( + const ClientProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.h new file mode 100644 index 000000000000..7f91ce3230cb --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/client_properties.h @@ -0,0 +1,59 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_CLIENT_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_CLIENT_PROPERTIES_H_ + +#include +#include +#include + +#include "bat/ledger/internal/properties/ballot_properties.h" +#include "bat/ledger/internal/properties/publisher_votes_properties.h" +#include "bat/ledger/internal/properties/current_reconcile_properties.h" +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" +#include "bat/ledger/mojom_structs.h" + +namespace ledger { + +struct ClientProperties { + ClientProperties(); + ClientProperties( + const ClientProperties& properties); + ~ClientProperties(); + + bool operator==( + const ClientProperties& rhs) const; + + bool operator!=( + const ClientProperties& rhs) const; + + WalletInfoProperties wallet_info; + WalletProperties wallet; + uint64_t boot_timestamp; + uint64_t reconcile_timestamp; + std::string persona_id; + std::string user_id; + std::string registrar_vk; + std::string master_user_token; + std::string pre_flight; + std::string fee_currency; + std::string settings; + double fee_amount; + bool user_changed_fee; + uint32_t days; + Transactions transactions; + Ballots ballots; + PublisherVotes publisher_votes; + CurrentReconciles current_reconciles; + bool auto_contribute; + bool rewards_enabled; + std::map inline_tips; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_CLIENT_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.cc new file mode 100644 index 000000000000..c3708f199787 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.cc @@ -0,0 +1,65 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/current_reconcile_properties.h" + +namespace ledger { + +CurrentReconcileProperties::CurrentReconcileProperties() + : timestamp(0), + fee(.0), + retry_step(ContributionRetry::STEP_NO), + retry_level(0) {} + +CurrentReconcileProperties::CurrentReconcileProperties( + const CurrentReconcileProperties& properties) { + viewing_id = properties.viewing_id; + anonize_viewing_id = properties.anonize_viewing_id; + registrar_vk = properties.registrar_vk; + pre_flight = properties.pre_flight; + master_user_token = properties.master_user_token; + surveyor_id = properties.surveyor_id; + timestamp = properties.timestamp; + rates = properties.rates; + amount = properties.amount; + currency = properties.currency; + fee = properties.fee; + directions = properties.directions; + type = properties.type; + retry_step = properties.retry_step; + retry_level = properties.retry_level; + destination = properties.destination; + proof = properties.proof; +} + +CurrentReconcileProperties::~CurrentReconcileProperties() = default; + +bool CurrentReconcileProperties::operator==( + const CurrentReconcileProperties& rhs) const { + return viewing_id == rhs.viewing_id && + anonize_viewing_id == rhs.anonize_viewing_id && + registrar_vk == rhs.registrar_vk && + pre_flight == rhs.pre_flight && + master_user_token == rhs.master_user_token && + surveyor_id == rhs.surveyor_id && + timestamp == rhs.timestamp && + rates == rhs.rates && + amount == rhs.amount && + currency == rhs.currency && + fee == rhs.fee && + directions == rhs.directions && + type == rhs.type && + retry_step == rhs.retry_step && + retry_level == rhs.retry_level && + destination == rhs.destination && + proof == rhs.proof; +} + +bool CurrentReconcileProperties::operator!=( + const CurrentReconcileProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.h new file mode 100644 index 000000000000..1375d5edbfc6 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/current_reconcile_properties.h @@ -0,0 +1,53 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_CURRENT_RECONCILE_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_CURRENT_RECONCILE_PROPERTIES_H_ + +#include +#include +#include + +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" +#include "bat/ledger/mojom_structs.h" + +namespace ledger { + +struct CurrentReconcileProperties { + CurrentReconcileProperties(); + CurrentReconcileProperties( + const CurrentReconcileProperties& properties); + ~CurrentReconcileProperties(); + + bool operator==( + const CurrentReconcileProperties& rhs) const; + + bool operator!=( + const CurrentReconcileProperties& rhs) const; + + std::string viewing_id; + std::string anonize_viewing_id; + std::string registrar_vk; + std::string pre_flight; + std::string master_user_token; + std::string surveyor_id; + uint64_t timestamp; + std::map rates; + std::string amount; + std::string currency; + double fee; + ReconcileDirections directions; + RewardsType type; + ContributionRetry retry_step; + int32_t retry_level; + std::string destination; + std::string proof; +}; + +typedef std::map CurrentReconciles; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_CURRENT_RECONCILE_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.cc new file mode 100644 index 000000000000..0fee86913279 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.cc @@ -0,0 +1,52 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/publisher_properties.h" + +namespace ledger { + +PublisherProperties::PublisherProperties() + : duration(0), + score(0), + visits(0), + percent(0), + weight(0), + status(0) {} + +PublisherProperties::PublisherProperties( + const PublisherProperties& properties) { + id = properties.id; + duration = properties.duration; + score = properties.score; + visits = properties.visits; + percent = properties.percent; + weight = properties.weight; + status = properties.status; +} + +PublisherProperties::~PublisherProperties() = default; + +bool PublisherProperties::operator==( + const PublisherProperties& rhs) const { + return id == rhs.id && + duration == rhs.duration && + score == rhs.score && + visits == rhs.visits && + percent == rhs.percent && + weight == rhs.weight && + status == rhs.status; +} + +bool PublisherProperties::operator!=( + const PublisherProperties& rhs) const { + return !(*this == rhs); +} + +bool PublisherProperties::operator<( + const PublisherProperties& rhs) const { + return score > rhs.score; +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.h new file mode 100644 index 000000000000..4e709d9621e8 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_properties.h @@ -0,0 +1,43 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_PUBLISHER_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_PUBLISHER_PROPERTIES_H_ + +#include +#include +#include + +namespace ledger { + +struct PublisherProperties { + PublisherProperties(); + PublisherProperties( + const PublisherProperties& properties); + ~PublisherProperties(); + + bool operator==( + const PublisherProperties& rhs) const; + + bool operator!=( + const PublisherProperties& rhs) const; + + bool operator<( + const PublisherProperties& rhs) const; + + std::string id; + uint64_t duration; + double score; + uint32_t visits; + uint32_t percent; + double weight; + uint32_t status; +}; + +typedef std::vector Publishers; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_PUBLISHER_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_settings_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_settings_properties.cc new file mode 100644 index 000000000000..aed38fd1c567 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_settings_properties.cc @@ -0,0 +1,55 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/publisher_settings_properties.h" +#include "bat/ledger/internal/static_values.h" + +namespace ledger { + +PublisherSettingsProperties::PublisherSettingsProperties() + : min_page_time_before_logging_a_visit( + braveledger_ledger::_default_min_page_time_before_logging_a_visit), + min_visits_for_publisher_relevancy(1), + allow_non_verified_sites_in_list(true), + allow_contribution_to_videos(true), + migrate_score_2(false) {} + +PublisherSettingsProperties::PublisherSettingsProperties( + const PublisherSettingsProperties& properties) { + min_page_time_before_logging_a_visit = + properties.min_page_time_before_logging_a_visit; + min_visits_for_publisher_relevancy = + properties.min_visits_for_publisher_relevancy; + allow_non_verified_sites_in_list = + properties.allow_non_verified_sites_in_list; + allow_contribution_to_videos = properties.allow_contribution_to_videos; + monthly_balances = properties.monthly_balances; + migrate_score_2 = properties.migrate_score_2; + processed_pending_publishers = properties.processed_pending_publishers; +} + +PublisherSettingsProperties::~PublisherSettingsProperties() = default; + +bool PublisherSettingsProperties::operator==( + const PublisherSettingsProperties& rhs) const { + return + min_page_time_before_logging_a_visit == + rhs.min_page_time_before_logging_a_visit && + min_visits_for_publisher_relevancy == + rhs.min_visits_for_publisher_relevancy && + allow_non_verified_sites_in_list == + rhs.allow_non_verified_sites_in_list && + allow_contribution_to_videos == rhs.allow_contribution_to_videos && + monthly_balances == rhs.monthly_balances && + migrate_score_2 == rhs.migrate_score_2 && + processed_pending_publishers == rhs.processed_pending_publishers; +} + +bool PublisherSettingsProperties::operator!=( + const PublisherSettingsProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_settings_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_settings_properties.h new file mode 100644 index 000000000000..9e454c73d0d3 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_settings_properties.h @@ -0,0 +1,41 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_PUBLISHER_SETTINGS_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_PUBLISHER_SETTINGS_PROPERTIES_H_ + +#include +#include +#include +#include + +#include "bat/ledger/internal/properties/report_balance_properties.h" + +namespace ledger { + +struct PublisherSettingsProperties { + PublisherSettingsProperties(); + PublisherSettingsProperties( + const PublisherSettingsProperties& properties); + ~PublisherSettingsProperties(); + + bool operator==( + const PublisherSettingsProperties& rhs) const; + + bool operator!=( + const PublisherSettingsProperties& rhs) const; + + uint64_t min_page_time_before_logging_a_visit; + uint32_t min_visits_for_publisher_relevancy; + bool allow_non_verified_sites_in_list; + bool allow_contribution_to_videos; + std::map monthly_balances; + bool migrate_score_2; + std::vector processed_pending_publishers; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_PUBLISHER_SETTINGS_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.cc new file mode 100644 index 000000000000..e70ff1e166fe --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.cc @@ -0,0 +1,31 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/publisher_vote_properties.h" + +namespace ledger { + +PublisherVoteProperties::PublisherVoteProperties() = default; + +PublisherVoteProperties::PublisherVoteProperties( + const PublisherVoteProperties& properties) { + surveyor_id = properties.surveyor_id; + proof = properties.proof; +} + +PublisherVoteProperties::~PublisherVoteProperties() = default; + +bool PublisherVoteProperties::operator==( + const PublisherVoteProperties& rhs) const { + return surveyor_id == rhs.surveyor_id && + proof == rhs.proof; +} + +bool PublisherVoteProperties::operator!=( + const PublisherVoteProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.h new file mode 100644 index 000000000000..3081bd594563 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_vote_properties.h @@ -0,0 +1,34 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_PUBLISHER_VOTE_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_PUBLISHER_VOTE_PROPERTIES_H_ + +#include +#include + +namespace ledger { + +struct PublisherVoteProperties { + PublisherVoteProperties(); + PublisherVoteProperties( + const PublisherVoteProperties& properties); + ~PublisherVoteProperties(); + + bool operator==( + const PublisherVoteProperties& rhs) const; + + bool operator!=( + const PublisherVoteProperties& rhs) const; + + std::string surveyor_id; + std::string proof; +}; + +typedef std::vector BatchVotes; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_PUBLISHER_VOTE_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.cc new file mode 100644 index 000000000000..3413cf91d7e2 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.cc @@ -0,0 +1,31 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/publisher_votes_properties.h" + +namespace ledger { + +PublisherVotesProperties::PublisherVotesProperties() = default; + +PublisherVotesProperties::PublisherVotesProperties( + const PublisherVotesProperties& properties) { + publisher = properties.publisher; + batch_votes = properties.batch_votes; +} + +PublisherVotesProperties::~PublisherVotesProperties() = default; + +bool PublisherVotesProperties::operator==( + const PublisherVotesProperties& rhs) const { + return publisher == rhs.publisher && + batch_votes == rhs.batch_votes; +} + +bool PublisherVotesProperties::operator!=( + const PublisherVotesProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.h new file mode 100644 index 000000000000..51b0c0b40d97 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/publisher_votes_properties.h @@ -0,0 +1,36 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_PUBLISHER_VOTES_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_PUBLISHER_VOTES_PROPERTIES_H_ + +#include +#include + +#include "bat/ledger/internal/properties/publisher_vote_properties.h" + +namespace ledger { + +struct PublisherVotesProperties { + PublisherVotesProperties(); + PublisherVotesProperties( + const PublisherVotesProperties& properties); + ~PublisherVotesProperties(); + + bool operator==( + const PublisherVotesProperties& rhs) const; + + bool operator!=( + const PublisherVotesProperties& rhs) const; + + std::string publisher; + BatchVotes batch_votes; +}; + +typedef std::vector PublisherVotes; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_PUBLISHER_VOTES_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.cc new file mode 100644 index 000000000000..7ea04295d512 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.cc @@ -0,0 +1,32 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" + +namespace ledger { + +ReconcileDirectionProperties::ReconcileDirectionProperties() + : amount_percent(0.0) {} + +ReconcileDirectionProperties::ReconcileDirectionProperties( + const ReconcileDirectionProperties& properties) { + publisher_key = properties.publisher_key; + amount_percent = properties.amount_percent; +} + +ReconcileDirectionProperties::~ReconcileDirectionProperties() = default; + +bool ReconcileDirectionProperties::operator==( + const ReconcileDirectionProperties& rhs) const { + return publisher_key == rhs.publisher_key && + amount_percent == rhs.amount_percent; +} + +bool ReconcileDirectionProperties::operator!=( + const ReconcileDirectionProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.h new file mode 100644 index 000000000000..d98b2cfb585c --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_direction_properties.h @@ -0,0 +1,34 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_RECONCILE_DIRECTION_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_RECONCILE_DIRECTION_PROPERTIES_H_ + +#include +#include + +namespace ledger { + +struct ReconcileDirectionProperties { + ReconcileDirectionProperties(); + ReconcileDirectionProperties( + const ReconcileDirectionProperties& properties); + ~ReconcileDirectionProperties(); + + bool operator==( + const ReconcileDirectionProperties& rhs) const; + + bool operator!=( + const ReconcileDirectionProperties& rhs) const; + + std::string publisher_key; + double amount_percent; +}; + +typedef std::vector ReconcileDirections; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_RECONCILE_DIRECTION_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.cc new file mode 100644 index 000000000000..6bf5e375dde5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.cc @@ -0,0 +1,41 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/reconcile_request_properties.h" + +namespace ledger { + +ReconcileRequestProperties::ReconcileRequestProperties() = default; + +ReconcileRequestProperties::ReconcileRequestProperties( + const ReconcileRequestProperties& properties) { + type = properties.type; + signed_tx_headers_digest = properties.signed_tx_headers_digest; + signed_tx_headers_signature = properties.signed_tx_headers_signature; + signed_tx_body = properties.signed_tx_body; + signed_tx_octets = properties.signed_tx_octets; + viewing_id = properties.viewing_id; + surveyor_id = properties.surveyor_id; +} + +ReconcileRequestProperties::~ReconcileRequestProperties() = default; + +bool ReconcileRequestProperties::operator==( + const ReconcileRequestProperties& rhs) const { + return type == rhs.type && + signed_tx_headers_digest == rhs.signed_tx_headers_digest && + signed_tx_headers_signature == rhs.signed_tx_headers_signature && + signed_tx_body == rhs.signed_tx_body && + signed_tx_octets == rhs.signed_tx_octets && + viewing_id == rhs.viewing_id && + surveyor_id == rhs.surveyor_id; +} + +bool ReconcileRequestProperties::operator!=( + const ReconcileRequestProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.h new file mode 100644 index 000000000000..8cb8d06c1cbe --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/reconcile_request_properties.h @@ -0,0 +1,38 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_RECONCILE_REQUEST_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_RECONCILE_REQUEST_PROPERTIES_H_ + +#include + +#include "bat/ledger/internal/properties/unsigned_tx_properties.h" + +namespace ledger { + +struct ReconcileRequestProperties { + ReconcileRequestProperties(); + ReconcileRequestProperties( + const ReconcileRequestProperties& properties); + ~ReconcileRequestProperties(); + + bool operator==( + const ReconcileRequestProperties& rhs) const; + + bool operator!=( + const ReconcileRequestProperties& rhs) const; + + std::string type; + std::string signed_tx_headers_digest; + std::string signed_tx_headers_signature; + UnsignedTxProperties signed_tx_body; + std::string signed_tx_octets; + std::string viewing_id; + std::string surveyor_id; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_RECONCILE_REQUEST_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/report_balance_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/report_balance_properties.cc new file mode 100644 index 000000000000..25bfaa027d2f --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/report_balance_properties.cc @@ -0,0 +1,54 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/report_balance_properties.h" + +namespace ledger { + +ReportBalanceProperties::ReportBalanceProperties() + : opening_balance("0"), + closing_balance("0"), + deposits("0"), + grants("0"), + ad_earnings("0"), + auto_contributions("0"), + recurring_donations("0"), + one_time_donations("0"), + total("0") {} + +ReportBalanceProperties::ReportBalanceProperties( + const ReportBalanceProperties& properties) { + opening_balance = properties.opening_balance; + closing_balance = properties.closing_balance; + deposits = properties.deposits; + grants = properties.grants; + ad_earnings = properties.ad_earnings; + auto_contributions = properties.auto_contributions; + recurring_donations = properties.recurring_donations; + one_time_donations = properties.one_time_donations; + total = properties.total; +} + +ReportBalanceProperties::~ReportBalanceProperties() = default; + +bool ReportBalanceProperties::operator==( + const ReportBalanceProperties& rhs) const { + return opening_balance == rhs.opening_balance && + closing_balance == rhs.closing_balance && + deposits == rhs.deposits && + grants == rhs.grants && + ad_earnings == rhs.ad_earnings && + auto_contributions == rhs.auto_contributions && + recurring_donations == rhs.recurring_donations && + one_time_donations == rhs.one_time_donations && + total == rhs.total; +} + +bool ReportBalanceProperties::operator!=( + const ReportBalanceProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/report_balance_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/report_balance_properties.h new file mode 100644 index 000000000000..826a6a00055e --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/report_balance_properties.h @@ -0,0 +1,38 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_REPORT_BALANCE_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_REPORT_BALANCE_PROPERTIES_H_ + +#include + +namespace ledger { + +struct ReportBalanceProperties { + ReportBalanceProperties(); + ReportBalanceProperties( + const ReportBalanceProperties& properties); + ~ReportBalanceProperties(); + + bool operator==( + const ReportBalanceProperties& rhs) const; + + bool operator!=( + const ReportBalanceProperties& rhs) const; + + std::string opening_balance; + std::string closing_balance; + std::string deposits; + std::string grants; + std::string ad_earnings; + std::string auto_contributions; + std::string recurring_donations; + std::string one_time_donations; + std::string total; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_REPORT_BALANCE_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.cc new file mode 100644 index 000000000000..570191de99a0 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.cc @@ -0,0 +1,37 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/surveyor_properties.h" + +namespace ledger { + +SurveyorProperties::SurveyorProperties() = default; + +SurveyorProperties::SurveyorProperties( + const SurveyorProperties& properties) { + signature = properties.signature; + surveyor_id = properties.surveyor_id; + survey_vk = properties.survey_vk; + registrar_vk = properties.registrar_vk; + survey_sk = properties.survey_sk; +} + +SurveyorProperties::~SurveyorProperties() = default; + +bool SurveyorProperties::operator==( + const SurveyorProperties& rhs) const { + return signature == rhs.signature && + surveyor_id == rhs.surveyor_id && + survey_vk == rhs.survey_vk && + registrar_vk == rhs.registrar_vk && + survey_sk == rhs.survey_sk; +} + +bool SurveyorProperties::operator!=( + const SurveyorProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.h new file mode 100644 index 000000000000..51a709727ecf --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/surveyor_properties.h @@ -0,0 +1,34 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_SURVEYOR_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_SURVEYOR_PROPERTIES_H_ + +#include + +namespace ledger { + +struct SurveyorProperties { + SurveyorProperties(); + SurveyorProperties( + const SurveyorProperties& properties); + ~SurveyorProperties(); + + bool operator==( + const SurveyorProperties& rhs) const; + + bool operator!=( + const SurveyorProperties& rhs) const; + + std::string signature; + std::string surveyor_id; + std::string survey_vk; + std::string registrar_vk; + std::string survey_sk; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_SURVEYOR_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.cc new file mode 100644 index 000000000000..74a9b9a13c59 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.cc @@ -0,0 +1,32 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/transaction_ballot_properties.h" + +namespace ledger { + +TransactionBallotProperties::TransactionBallotProperties() + : count(0) {} + +TransactionBallotProperties::TransactionBallotProperties( + const TransactionBallotProperties& properties) { + publisher = properties.publisher; + count = properties.count; +} + +TransactionBallotProperties::~TransactionBallotProperties() = default; + +bool TransactionBallotProperties::operator==( + const TransactionBallotProperties& rhs) const { + return publisher == rhs.publisher && + count == rhs.count; +} + +bool TransactionBallotProperties::operator!=( + const TransactionBallotProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.h new file mode 100644 index 000000000000..2fc1041b07dd --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_ballot_properties.h @@ -0,0 +1,35 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_TRANSACTION_BALLOT_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_TRANSACTION_BALLOT_PROPERTIES_H_ + +#include +#include +#include + +namespace ledger { + +struct TransactionBallotProperties { + TransactionBallotProperties(); + TransactionBallotProperties( + const TransactionBallotProperties& properties); + ~TransactionBallotProperties(); + + bool operator==( + const TransactionBallotProperties& rhs) const; + + bool operator!=( + const TransactionBallotProperties& rhs) const; + + std::string publisher; + uint32_t count; +}; + +typedef std::vector TransactionBallots; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_TRANSACTION_BALLOT_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.cc new file mode 100644 index 000000000000..0f5077051142 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.cc @@ -0,0 +1,51 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/transaction_properties.h" + +namespace ledger { + +TransactionProperties::TransactionProperties() + : vote_count(0) {} + +TransactionProperties::TransactionProperties( + const TransactionProperties& properties) { + viewing_id = properties.viewing_id; + surveyor_id = properties.surveyor_id; + contribution_rates = properties.contribution_rates; + contribution_probi = properties.contribution_probi; + submission_timestamp = properties.submission_timestamp; + contribution_rates = properties.contribution_rates; + anonize_viewing_id = properties.anonize_viewing_id; + registrar_vk = properties.registrar_vk; + master_user_token = properties.master_user_token; + surveyor_ids = properties.surveyor_ids; + vote_count = properties.vote_count; + transaction_ballots = properties.transaction_ballots; +} + +TransactionProperties::~TransactionProperties() = default; + +bool TransactionProperties::operator==( + const TransactionProperties& rhs) const { + return viewing_id == rhs.viewing_id && + surveyor_id == rhs.surveyor_id && + contribution_rates == rhs.contribution_rates && + contribution_probi == rhs.contribution_probi && + submission_timestamp == rhs.submission_timestamp && + anonize_viewing_id == rhs.anonize_viewing_id && + registrar_vk == rhs.registrar_vk && + master_user_token == rhs.master_user_token && + surveyor_ids == rhs.surveyor_ids && + vote_count == rhs.vote_count && + transaction_ballots == rhs.transaction_ballots; +} + +bool TransactionProperties::operator!=( + const TransactionProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.h new file mode 100644 index 000000000000..94cc3f1b8349 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/transaction_properties.h @@ -0,0 +1,47 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_TRANSACTION_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_TRANSACTION_PROPERTIES_H_ + +#include +#include +#include +#include + +#include "bat/ledger/internal/properties/transaction_ballot_properties.h" + +namespace ledger { + +struct TransactionProperties { + TransactionProperties(); + TransactionProperties( + const TransactionProperties& properties); + ~TransactionProperties(); + + bool operator==( + const TransactionProperties& rhs) const; + + bool operator!=( + const TransactionProperties& rhs) const; + + std::string viewing_id; + std::string surveyor_id; + std::map contribution_rates; + std::string contribution_probi; + std::string submission_timestamp; + std::string anonize_viewing_id; + std::string registrar_vk; + std::string master_user_token; + std::vector surveyor_ids; + uint32_t vote_count; + TransactionBallots transaction_ballots; +}; + +typedef std::vector Transactions; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_TRANSACTION_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/unsigned_tx_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/unsigned_tx_properties.cc new file mode 100644 index 000000000000..d41c1067aab1 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/unsigned_tx_properties.cc @@ -0,0 +1,33 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/unsigned_tx_properties.h" + +namespace ledger { + +UnsignedTxProperties::UnsignedTxProperties() = default; + +UnsignedTxProperties::UnsignedTxProperties( + const UnsignedTxProperties& properties) { + amount = properties.amount; + currency = properties.currency; + destination = properties.destination; +} + +UnsignedTxProperties::~UnsignedTxProperties() = default; + +bool UnsignedTxProperties::operator==( + const UnsignedTxProperties& rhs) const { + return amount == rhs.amount && + currency == rhs.currency && + destination == rhs.destination; +} + +bool UnsignedTxProperties::operator!=( + const UnsignedTxProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/unsigned_tx_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/unsigned_tx_properties.h new file mode 100644 index 000000000000..9c1d56b5d423 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/unsigned_tx_properties.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_UNSIGNED_TX_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_UNSIGNED_TX_PROPERTIES_H_ + +#include + +namespace ledger { + +struct UnsignedTxProperties { + UnsignedTxProperties(); + UnsignedTxProperties( + const UnsignedTxProperties& properties); + ~UnsignedTxProperties(); + + bool operator==( + const UnsignedTxProperties& rhs) const; + + bool operator!=( + const UnsignedTxProperties& rhs) const; + + std::string amount; + std::string currency; + std::string destination; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_UNSIGNED_TX_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/wallet_info_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/wallet_info_properties.cc new file mode 100644 index 000000000000..a1b476e16e17 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/wallet_info_properties.cc @@ -0,0 +1,33 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/wallet_info_properties.h" + +namespace ledger { + +WalletInfoProperties::WalletInfoProperties() = default; + +WalletInfoProperties::WalletInfoProperties( + const WalletInfoProperties& properties) { + payment_id = properties.payment_id; + address_card_id = properties.address_card_id; + key_info_seed = properties.key_info_seed; +} + +WalletInfoProperties::~WalletInfoProperties() = default; + +bool WalletInfoProperties::operator==( + const WalletInfoProperties& rhs) const { + return payment_id == rhs.payment_id && + address_card_id == rhs.address_card_id && + key_info_seed == rhs.key_info_seed; +} + +bool WalletInfoProperties::operator!=( + const WalletInfoProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/wallet_info_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/wallet_info_properties.h new file mode 100644 index 000000000000..24f5368b6090 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/wallet_info_properties.h @@ -0,0 +1,34 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_WALLET_INFO_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_WALLET_INFO_PROPERTIES_H_ + +#include +#include +#include + +namespace ledger { + +struct WalletInfoProperties { + WalletInfoProperties(); + WalletInfoProperties( + const WalletInfoProperties& properties); + ~WalletInfoProperties(); + + bool operator==( + const WalletInfoProperties& rhs) const; + + bool operator!=( + const WalletInfoProperties& rhs) const; + + std::string payment_id; + std::string address_card_id; + std::vector key_info_seed; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_WALLET_INFO_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.cc new file mode 100644 index 000000000000..d0bec517b794 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.cc @@ -0,0 +1,32 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/properties/winner_properties.h" + +namespace ledger { + +WinnerProperties::WinnerProperties() + : vote_count(0) {} + +WinnerProperties::WinnerProperties( + const WinnerProperties& properties) { + direction = properties.direction; + vote_count = properties.vote_count; +} + +WinnerProperties::~WinnerProperties() = default; + +bool WinnerProperties::operator==( + const WinnerProperties& rhs) const { + return direction == rhs.direction && + vote_count == rhs.vote_count; +} + +bool WinnerProperties::operator!=( + const WinnerProperties& rhs) const { + return !(*this == rhs); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.h b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.h new file mode 100644 index 000000000000..9bf0ade3490c --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/properties/winner_properties.h @@ -0,0 +1,36 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_PROPERTIES_WINNER_PROPERTIES_H_ +#define BRAVELEDGER_PROPERTIES_WINNER_PROPERTIES_H_ + +#include +#include + +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" + +namespace ledger { + +struct WinnerProperties { + WinnerProperties(); + WinnerProperties( + const WinnerProperties& properties); + ~WinnerProperties(); + + bool operator==( + const WinnerProperties& rhs) const; + + bool operator!=( + const WinnerProperties& rhs) const; + + ReconcileDirectionProperties direction; + uint32_t vote_count; +}; + +typedef std::vector Winners; + +} // namespace ledger + +#endif // BRAVELEDGER_PROPERTIES_WINNER_PROPERTIES_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.cc index 0f1032c51948..a0d89ddbf5eb 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.cc @@ -11,12 +11,13 @@ #include "base/strings/stringprintf.h" #include "bat/ledger/global_constants.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/bignum.h" #include "bat/ledger/internal/ledger_impl.h" +#include "bat/ledger/internal/properties/publisher_settings_properties.h" +#include "bat/ledger/internal/properties/report_balance_properties.h" #include "bat/ledger/internal/publisher/publisher.h" #include "bat/ledger/internal/publisher/publisher_server_list.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" +#include "bat/ledger/internal/state/publisher_settings_state.h" #include "bat/ledger/internal/static_values.h" #include "mojo/public/cpp/bindings/map.h" @@ -40,9 +41,9 @@ namespace braveledger_publisher { Publisher::Publisher(bat_ledger::LedgerImpl* ledger): ledger_(ledger), - state_(new braveledger_bat_helper::PUBLISHER_STATE_ST), + state_(new ledger::PublisherSettingsProperties), server_list_(std::make_unique(ledger)) { - calcScoreConsts(state_->min_publisher_duration_); + calcScoreConsts(state_->min_page_time_before_logging_a_visit); } Publisher::~Publisher() { @@ -443,44 +444,44 @@ void Publisher::OnRestorePublishers( // In seconds void Publisher::setPublisherMinVisitTime(const uint64_t& duration) { - state_->min_publisher_duration_ = duration; + state_->min_page_time_before_logging_a_visit = duration; calcScoreConsts(duration); SynopsisNormalizer(); saveState(); } void Publisher::setPublisherMinVisits(const unsigned int visits) { - state_->min_visits_ = visits; + state_->min_visits_for_publisher_relevancy = visits; SynopsisNormalizer(); saveState(); } void Publisher::setPublisherAllowNonVerified(const bool& allow) { - state_->allow_non_verified_ = allow; + state_->allow_non_verified_sites_in_list = allow; SynopsisNormalizer(); saveState(); } void Publisher::setPublisherAllowVideos(const bool& allow) { - state_->allow_videos_ = allow; + state_->allow_contribution_to_videos = allow; SynopsisNormalizer(); saveState(); } uint64_t Publisher::getPublisherMinVisitTime() const { - return state_->min_publisher_duration_; + return state_->min_page_time_before_logging_a_visit; } unsigned int Publisher::GetPublisherMinVisits() const { - return state_->min_visits_; + return state_->min_visits_for_publisher_relevancy; } bool Publisher::getPublisherAllowNonVerified() const { - return state_->allow_non_verified_; + return state_->allow_non_verified_sites_in_list; } bool Publisher::getPublisherAllowVideos() const { - return state_->allow_videos_; + return state_->allow_contribution_to_videos; } bool Publisher::GetMigrateScore() const { @@ -626,37 +627,37 @@ bool Publisher::IsExcluded( } void Publisher::clearAllBalanceReports() { - if (state_->monthly_balances_.empty()) { + if (state_->monthly_balances.empty()) { return; } - state_->monthly_balances_.clear(); + state_->monthly_balances.clear(); saveState(); } void Publisher::setBalanceReport(ledger::ActivityMonth month, int year, const ledger::BalanceReportInfo& report_info) { - braveledger_bat_helper::REPORT_BALANCE_ST report_balance; - report_balance.opening_balance_ = report_info.opening_balance; - report_balance.closing_balance_ = report_info.closing_balance; - report_balance.grants_ = report_info.grants; - report_balance.deposits_ = report_info.deposits; - report_balance.earning_from_ads_ = report_info.earning_from_ads; - report_balance.recurring_donation_ = report_info.recurring_donation; - report_balance.one_time_donation_ = report_info.one_time_donation; - report_balance.auto_contribute_ = report_info.auto_contribute; + ledger::ReportBalanceProperties report_balance; + report_balance.opening_balance = report_info.opening_balance; + report_balance.closing_balance = report_info.closing_balance; + report_balance.grants = report_info.grants; + report_balance.deposits = report_info.deposits; + report_balance.ad_earnings = report_info.earning_from_ads; + report_balance.recurring_donations = report_info.recurring_donation; + report_balance.one_time_donations = report_info.one_time_donation; + report_balance.auto_contributions = report_info.auto_contribute; std::string total = "0"; - total = braveledger_bat_bignum::sum(total, report_balance.grants_); - total = braveledger_bat_bignum::sum(total, report_balance.earning_from_ads_); - total = braveledger_bat_bignum::sum(total, report_balance.deposits_); - total = braveledger_bat_bignum::sub(total, report_balance.auto_contribute_); + total = braveledger_bat_bignum::sum(total, report_balance.grants); + total = braveledger_bat_bignum::sum(total, report_balance.ad_earnings); + total = braveledger_bat_bignum::sum(total, report_balance.deposits); + total = braveledger_bat_bignum::sub(total, report_balance.auto_contributions); total = braveledger_bat_bignum::sub(total, - report_balance.recurring_donation_); - total = braveledger_bat_bignum::sub(total, report_balance.one_time_donation_); + report_balance.recurring_donations); + total = braveledger_bat_bignum::sub(total, report_balance.one_time_donations); - report_balance.total_ = total; - state_->monthly_balances_[GetBalanceReportName(month, year)] = report_balance; + report_balance.total = total; + state_->monthly_balances[GetBalanceReportName(month, year)] = report_balance; saveState(); } @@ -673,12 +674,12 @@ bool Publisher::GetBalanceReportInternal(ledger::ActivityMonth month, int year, ledger::BalanceReportInfo* report_info) { std::string name = GetBalanceReportName(month, year); - auto iter = state_->monthly_balances_.find(name); + auto iter = state_->monthly_balances.find(name); if (!report_info) { return false; } - if (iter == state_->monthly_balances_.end()) { + if (iter == state_->monthly_balances.end()) { ledger::BalanceReportInfo new_report_info; new_report_info.opening_balance = "0"; new_report_info.closing_balance = "0"; @@ -692,19 +693,19 @@ bool Publisher::GetBalanceReportInternal(ledger::ActivityMonth month, setBalanceReport(month, year, new_report_info); bool successGet = GetBalanceReportInternal(month, year, report_info); if (successGet) { - iter = state_->monthly_balances_.find(name); + iter = state_->monthly_balances.find(name); } else { return false; } } - report_info->opening_balance = iter->second.opening_balance_; - report_info->closing_balance = iter->second.closing_balance_; - report_info->grants = iter->second.grants_; - report_info->earning_from_ads = iter->second.earning_from_ads_; - report_info->auto_contribute = iter->second.auto_contribute_; - report_info->recurring_donation = iter->second.recurring_donation_; - report_info->one_time_donation = iter->second.one_time_donation_; + report_info->opening_balance = iter->second.opening_balance; + report_info->closing_balance = iter->second.closing_balance; + report_info->grants = iter->second.grants; + report_info->earning_from_ads = iter->second.ad_earnings; + report_info->auto_contribute = iter->second.auto_contributions; + report_info->recurring_donation = iter->second.recurring_donations; + report_info->one_time_donation = iter->second.one_time_donations; return true; } @@ -712,16 +713,16 @@ bool Publisher::GetBalanceReportInternal(ledger::ActivityMonth month, std::map Publisher::GetAllBalanceReports() { std::map newReports; - for (auto const& report : state_->monthly_balances_) { + for (auto const& report : state_->monthly_balances) { ledger::BalanceReportInfoPtr newReport = ledger::BalanceReportInfo::New(); - const braveledger_bat_helper::REPORT_BALANCE_ST oldReport = report.second; - newReport->opening_balance = oldReport.opening_balance_; - newReport->closing_balance = oldReport.closing_balance_; - newReport->grants = oldReport.grants_; - newReport->earning_from_ads = oldReport.earning_from_ads_; - newReport->auto_contribute = oldReport.auto_contribute_; - newReport->recurring_donation = oldReport.recurring_donation_; - newReport->one_time_donation = oldReport.one_time_donation_; + const ledger::ReportBalanceProperties oldReport = report.second; + newReport->opening_balance = oldReport.opening_balance; + newReport->closing_balance = oldReport.closing_balance; + newReport->grants = oldReport.grants; + newReport->earning_from_ads = oldReport.ad_earnings; + newReport->auto_contribute = oldReport.auto_contributions; + newReport->recurring_donation = oldReport.recurring_donations; + newReport->one_time_donation = oldReport.one_time_donations; newReports[report.first] = std::move(newReport); } @@ -730,18 +731,19 @@ Publisher::GetAllBalanceReports() { } void Publisher::saveState() { - std::string data; - braveledger_bat_helper::saveToJsonString(*state_, &data); + const ledger::PublisherSettingsState publisher_settings_state; + const std::string data = publisher_settings_state.ToJson(*state_); ledger_->SavePublisherState(data, this); } bool Publisher::loadState(const std::string& data) { - braveledger_bat_helper::PUBLISHER_STATE_ST state; - if (!braveledger_bat_helper::loadFromJson(&state, data.c_str())) + ledger::PublisherSettingsProperties state; + const ledger::PublisherSettingsState publisher_settings_state; + if (!publisher_settings_state.FromJson(data.c_str(), &state)) return false; - state_.reset(new braveledger_bat_helper::PUBLISHER_STATE_ST(state)); - calcScoreConsts(state_->min_publisher_duration_); + state_.reset(new ledger::PublisherSettingsProperties(state)); + calcScoreConsts(state_->min_page_time_before_logging_a_visit); return true; } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h index eb33dd2bcb4b..cc0601dc581a 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher.h @@ -12,7 +12,8 @@ #include #include "base/gtest_prod_util.h" -#include "bat/ledger/internal/bat_helper.h" +#include "bat/ledger/internal/properties/publisher_properties.h" +#include "bat/ledger/internal/properties/publisher_settings_properties.h" #include "bat/ledger/ledger.h" #include "bat/ledger/ledger_callback_handler.h" @@ -20,8 +21,8 @@ namespace bat_ledger { class LedgerImpl; } -namespace braveledger_bat_helper { -struct PUBLISHER_STATE_ST; +namespace ledger { +struct PublisherSettings; } namespace braveledger_publisher { @@ -217,7 +218,7 @@ class Publisher : public ledger::LedgerCallbackHandler { void SetMigrateScore(bool value); bool isPublisherVisible( - const braveledger_bat_helper::PUBLISHER_ST& publisher_st); + const ledger::PublisherProperties& publisher_st); void OnSaveVisitInternal( ledger::Result result, @@ -243,7 +244,7 @@ class Publisher : public ledger::LedgerCallbackHandler { ledger::PublisherStatus ParsePublisherStatus(const std::string& status); bat_ledger::LedgerImpl* ledger_; // NOT OWNED - std::unique_ptr state_; + std::unique_ptr state_; std::unique_ptr server_list_; double a_; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher_server_list.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher_server_list.cc index b07748a63a83..f7b7da2c172b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher_server_list.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/publisher/publisher_server_list.cc @@ -9,11 +9,11 @@ #include "base/json/json_reader.h" #include "base/time/time.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/publisher/publisher_server_list.h" #include "bat/ledger/internal/state_keys.h" #include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/static_values.h" #include "bat/ledger/option_keys.h" #include "brave_base/random.h" #include "net/http/http_status_code.h" diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/rapidjson_bat_helper.h b/vendor/bat-native-ledger/src/bat/ledger/internal/rapidjson_bat_helper.h index 0d067044d0fc..87017043cde1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/rapidjson_bat_helper.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/rapidjson_bat_helper.h @@ -15,33 +15,8 @@ namespace braveledger_bat_helper { -struct BALLOT_ST; -struct PUBLISHER_ST; -struct PUBLISHER_STATE_ST; -struct RECONCILE_DIRECTION; -struct CURRENT_RECONCILE; -struct CLIENT_STATE_ST; -struct TRANSACTION_BALLOT_ST; -struct TRANSACTION_ST; -struct WALLET_INFO_ST; -struct WALLET_PROPERTIES_ST; - using JsonWriter = rapidjson::Writer; -void saveToJson(JsonWriter* writer, const BALLOT_ST&); -void saveToJson(JsonWriter* writer, const PUBLISHER_ST&); -void saveToJson(JsonWriter* writer, const PUBLISHER_STATE_ST&); -void saveToJson(JsonWriter* writer, const RECONCILE_DIRECTION&); -void saveToJson(JsonWriter* writer, const CURRENT_RECONCILE&); -void saveToJson(JsonWriter* writer, const CLIENT_STATE_ST&); -void saveToJson(JsonWriter* writer, const TRANSACTION_BALLOT_ST&); -void saveToJson(JsonWriter* writer, const TRANSACTION_ST&); -void saveToJson(JsonWriter* writer, const WALLET_INFO_ST&); -void saveToJson(JsonWriter* writer, const ledger::ReconcileInfo&); -void saveToJson(JsonWriter* writer, const ledger::RewardsInternalsInfo&); -void saveToJson(JsonWriter* writer, const ledger::WalletProperties&); -void saveToJson(JsonWriter* writer, const WALLET_PROPERTIES_ST&); - template void saveToJsonString(const T& t, std::string* json) { rapidjson::StringBuffer buffer; 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 0fda0bf3a542..4496c70d6144 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 @@ -8,7 +8,6 @@ #include "base/strings/stringprintf.h" #include "bat/ledger/ledger.h" #include "bat/ledger/internal/static_values.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/request/request_util.h" #include "bat/ledger/internal/common/security_helper.h" diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.cc new file mode 100644 index 000000000000..ed4b79b45042 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.cc @@ -0,0 +1,160 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/ballot_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kCountKey[] = "offset"; +const char kPrepareBallotKey[] = "prepareBallot"; +const char kPublisherKey[] = "publisher"; +const char kSurveyorIdKey[] = "surveyorId"; +const char kViewingIdKey[] = "viewingId"; + +} // namespace + +BallotState::BallotState() = default; + +BallotState::~BallotState() = default; + +bool BallotState::FromJson( + const std::string& json, + BallotProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool BallotState::FromDict( + const base::DictionaryValue* dictionary, + BallotProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + BallotProperties ballot_properties; + + // Viewing Id + const auto* viewing_id = dictionary->FindStringKey(kViewingIdKey); + if (!viewing_id) { + NOTREACHED(); + return false; + } + ballot_properties.viewing_id = *viewing_id; + + // Surveyor Id + const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); + if (!surveyor_id) { + NOTREACHED(); + return false; + } + ballot_properties.surveyor_id = *surveyor_id; + + // Publisher + const auto* publisher = dictionary->FindStringKey(kPublisherKey); + if (!publisher) { + NOTREACHED(); + return false; + } + ballot_properties.publisher = *publisher; + + // Offset (There is no support for unsigned int. Writing JSON with such types + // violates the spec. As we need an unsigned int, we need to a double and cast + // to an unsigned int) + const auto count = dictionary->FindDoubleKey(kCountKey); + if (!count) { + NOTREACHED(); + return false; + } + ballot_properties.count = static_cast(*count); + + // Prepare Ballot + const auto* prepare_ballot = dictionary->FindStringKey(kPrepareBallotKey); + if (!prepare_ballot) { + NOTREACHED(); + return false; + } + ballot_properties.prepare_ballot = *prepare_ballot; + + *properties = ballot_properties; + + return true; +} + +bool BallotState::ToJson( + JsonWriter* writer, + const BallotProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kViewingIdKey); + writer->String(properties.viewing_id.c_str()); + + writer->String(kSurveyorIdKey); + writer->String(properties.surveyor_id.c_str()); + + writer->String(kPublisherKey); + writer->String(properties.publisher.c_str()); + + writer->String(kCountKey); + writer->Uint(properties.count); + + writer->String(kPrepareBallotKey); + writer->String(properties.prepare_ballot.c_str()); + + writer->EndObject(); + + return true; +} + +std::string BallotState::ToJson( + const BallotProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.h new file mode 100644 index 000000000000..4aa3ab5c26a5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_BALLOT_STATE_H_ +#define BRAVELEDGER_STATE_BALLOT_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/ballot_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class BallotState + : public state::Reader, + public state::Writer { + public: + BallotState(); + ~BallotState(); + + bool FromJson( + const std::string& json, + BallotProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + BallotProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const BallotProperties& properties) const override; + + std::string ToJson( + const BallotProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_BALLOT_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc new file mode 100644 index 000000000000..85de9c0be184 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/ballot_state_unittest.cc @@ -0,0 +1,54 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/ballot_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=BallotStateTest.* + +namespace ledger { + +TEST(BallotStateTest, ToJsonSerialization) { + // Arrange + BallotProperties ballot_properties; + ballot_properties.viewing_id = "ViewingId"; + ballot_properties.surveyor_id = "SurveyorId"; + ballot_properties.publisher = "Publisher"; + ballot_properties.count = std::numeric_limits::max(); + ballot_properties.prepare_ballot = "PrepareBallot"; + + // Act + const BallotState ballot_state; + const std::string json = ballot_state.ToJson(ballot_properties); + + // Assert + BallotProperties expected_ballot_properties; + ballot_state.FromJson(json, &expected_ballot_properties); + EXPECT_EQ(expected_ballot_properties, ballot_properties); +} + +TEST(BallotStateTest, FromJsonDeserialization) { + // Arrange + BallotProperties ballot_properties; + ballot_properties.viewing_id = "ViewingId"; + ballot_properties.surveyor_id = "SurveyorId"; + ballot_properties.publisher = "Publisher"; + ballot_properties.count = std::numeric_limits::max(); + ballot_properties.prepare_ballot = "PrepareBallot"; + + const std::string json = "{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"}"; // NOLINT + + // Act + BallotProperties expected_ballot_properties; + const BallotState ballot_state; + ballot_state.FromJson(json, &expected_ballot_properties); + + // Assert + EXPECT_EQ(expected_ballot_properties, ballot_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.cc new file mode 100644 index 000000000000..f57f8a920937 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.cc @@ -0,0 +1,537 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include +#include + +#include "bat/ledger/internal/state/client_state.h" +#include "bat/ledger/internal/state/ballot_state.h" +#include "bat/ledger/internal/state/publisher_votes_state.h" +#include "bat/ledger/internal/state/transaction_state.h" +#include "bat/ledger/internal/state/current_reconcile_state.h" +#include "bat/ledger/internal/state/wallet_info_state.h" +#include "bat/ledger/internal/state/wallet_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAutoContributeKey[] = "auto_contribute"; +const char kBallotsKey[] = "ballots"; +const char kPublisherVotesKey[] = "batch"; +const char kBootTimestampKey[] = "bootStamp"; +const char kCurrentReconcilesKey[] = "current_reconciles"; +const char kDaysKey[] = "days"; +const char kFeeAmountKey[] = "fee_amount"; +const char kFeeCurrencyKey[] = "fee_currency"; +const char kInlineTipsKey[] = "inlineTip"; +const char kMasterUserTokenKey[] = "masterUserToken"; +const char kPersonaIdKey[] = "personaId"; +const char kPreFlightKey[] = "preFlight"; +const char kReconcileTimestampKey[] = "reconcileStamp"; +const char kRegistrarVkKey[] = "registrarVK"; +const char kRewardsEnabledKey[] = "rewards_enabled"; +const char kSettingsKey[] = "settings"; +const char kTransactionsKey[] = "transactions"; +const char kUserChangedFeeKey[] = "user_changed_fee"; +const char kUserIdKey[] = "userId"; +const char kWalletInfoKey[] = "walletInfo"; +const char kWalletKey[] = "walletProperties"; + +} // namespace + +ClientState::ClientState() = default; + +ClientState::~ClientState() = default; + +bool ClientState::FromJson( + const std::string& json, + ClientProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool ClientState::FromDict( + const base::DictionaryValue* dictionary, + ClientProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + ClientProperties client_properties; + + // Wallet Info + const auto* wallet_info_value = dictionary->FindKey(kWalletInfoKey); + if (!wallet_info_value || !wallet_info_value->is_dict()) { + NOTREACHED(); + return false; + } + + const base::DictionaryValue* wallet_info_dictionary = nullptr; + wallet_info_value->GetAsDictionary(&wallet_info_dictionary); + if (!wallet_info_dictionary) { + NOTREACHED(); + return false; + } + + const WalletInfoState wallet_info_state; + WalletInfoProperties wallet_info; + if (wallet_info_state.FromDict(wallet_info_dictionary, &wallet_info)) { + client_properties.wallet_info = wallet_info; + } + + // Boot Timestamp (There is no support for uint64_t. Writing JSON with such + // types violates the spec. As we need a uint64_t, we need to use an unsigned + // int and cast to a uint64_t) + const auto boot_timestamp = dictionary->FindDoubleKey(kBootTimestampKey); + if (!boot_timestamp) { + NOTREACHED(); + return false; + } + client_properties.boot_timestamp = static_cast(*boot_timestamp); + + // Reconcile Timestamp (There is no support for uint64_t. Writing JSON with + // such types violates the spec. As we need a uint64_t, we need to use an + // unsigned int and cast to a uint64_t) + const auto reconcile_timestamp = + dictionary->FindDoubleKey(kReconcileTimestampKey); + if (!reconcile_timestamp) { + NOTREACHED(); + return false; + } + client_properties.reconcile_timestamp = + static_cast(*reconcile_timestamp); + + // Persona Id + const auto* persona_id = dictionary->FindStringKey(kPersonaIdKey); + if (!persona_id) { + NOTREACHED(); + return false; + } + client_properties.persona_id = *persona_id; + + // User Id + const auto* user_id = dictionary->FindStringKey(kUserIdKey); + if (!user_id) { + NOTREACHED(); + return false; + } + client_properties.user_id = *user_id; + + // Registrar VK + const auto* registrar_vk = dictionary->FindStringKey(kRegistrarVkKey); + if (!registrar_vk) { + NOTREACHED(); + return false; + } + client_properties.registrar_vk = *registrar_vk; + + // Master User Token + const auto* master_user_token = + dictionary->FindStringKey(kMasterUserTokenKey); + if (!master_user_token) { + NOTREACHED(); + return false; + } + client_properties.master_user_token = *master_user_token; + + // Pre Flight + const auto* pre_flight = dictionary->FindStringKey(kPreFlightKey); + if (!pre_flight) { + NOTREACHED(); + return false; + } + client_properties.pre_flight = *pre_flight; + + // Fee Currency + const auto* fee_currency = dictionary->FindStringKey(kFeeCurrencyKey); + if (!fee_currency) { + NOTREACHED(); + return false; + } + client_properties.fee_currency = *fee_currency; + + // Settings + const auto* settings = dictionary->FindStringKey(kSettingsKey); + if (!settings) { + NOTREACHED(); + return false; + } + client_properties.settings = *settings; + + // Fee Amount + const auto fee_amount = dictionary->FindDoubleKey(kFeeAmountKey); + if (!fee_amount) { + NOTREACHED(); + return false; + } + client_properties.fee_amount = *fee_amount; + + // User Changed Fee + const auto user_changed_fee = dictionary->FindBoolKey(kUserChangedFeeKey); + if (!user_changed_fee) { + NOTREACHED(); + return false; + } + client_properties.user_changed_fee = *user_changed_fee; + + // Days (There is no support for unsigned int. Writing JSON with such types + // violates the spec. As we need an unsigned int, we need to a double and cast + // to an unsigned int) + const auto days = dictionary->FindDoubleKey(kDaysKey); + if (!days) { + NOTREACHED(); + return false; + } + client_properties.days = static_cast(*days); + + // Auto Contribute + const auto auto_contribute = dictionary->FindBoolKey(kAutoContributeKey); + if (!auto_contribute) { + NOTREACHED(); + return false; + } + client_properties.auto_contribute = *auto_contribute; + + // Rewards Enabled + const auto rewards_enabled = dictionary->FindBoolKey(kRewardsEnabledKey); + if (!rewards_enabled) { + NOTREACHED(); + return false; + } + client_properties.rewards_enabled = *rewards_enabled; + + // Transactions + const auto* transaction_list = dictionary->FindListKey(kTransactionsKey); + if (!transaction_list) { + NOTREACHED(); + return false; + } + + const TransactionState transaction_state; + for (const auto& transaction_value : transaction_list->GetList()) { + if (!transaction_value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* transaction_dictionary = nullptr; + transaction_value.GetAsDictionary(&transaction_dictionary); + if (!transaction_dictionary) { + NOTREACHED(); + continue; + } + + TransactionProperties transaction; + if (!transaction_state.FromDict(transaction_dictionary, &transaction)) { + continue; + } + + client_properties.transactions.push_back(transaction); + } + + // Ballots + const auto* ballot_list = dictionary->FindListKey(kBallotsKey); + if (!ballot_list) { + NOTREACHED(); + return false; + } + + const BallotState ballot_state; + for (const auto& ballot_value : ballot_list->GetList()) { + if (!ballot_value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* ballot_dictionary = nullptr; + ballot_value.GetAsDictionary(&ballot_dictionary); + if (!ballot_dictionary) { + NOTREACHED(); + continue; + } + + BallotProperties ballot; + if (!ballot_state.FromDict(ballot_dictionary, &ballot)) { + continue; + } + + client_properties.ballots.push_back(ballot); + } + + // Publisher Votes + const auto* publisher_votes_list = + dictionary->FindListKey(kPublisherVotesKey); + if (!publisher_votes_list) { + NOTREACHED(); + return false; + } + + const PublisherVotesState publisher_votes_state; + for (const auto& publisher_votes_value : publisher_votes_list->GetList()) { + if (!publisher_votes_value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* publisher_votes_dictionary = nullptr; + publisher_votes_value.GetAsDictionary(&publisher_votes_dictionary); + if (!publisher_votes_dictionary) { + NOTREACHED(); + continue; + } + + PublisherVotesProperties publisher_votes; + if (!publisher_votes_state.FromDict(publisher_votes_dictionary, + &publisher_votes)) { + continue; + } + + client_properties.publisher_votes.push_back(publisher_votes); + } + + // Current Reconciles + const auto* current_reconciles_value = + dictionary->FindKey(kCurrentReconcilesKey); + if (current_reconciles_value) { + if (!current_reconciles_value->is_dict()) { + NOTREACHED(); + return false; + } + + const CurrentReconcileState current_reconcile_state; + for (const auto& current_reconcile_value : + current_reconciles_value->DictItems()) { + const auto& key = current_reconcile_value.first; + const auto& value = current_reconcile_value.second; + + if (!value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* current_reconcile_dictionary = nullptr; + value.GetAsDictionary(¤t_reconcile_dictionary); + if (!current_reconcile_dictionary) { + NOTREACHED(); + continue; + } + + CurrentReconcileProperties current_reconcile; + if (!current_reconcile_state.FromDict(current_reconcile_dictionary, + ¤t_reconcile)) { + continue; + } + + client_properties.current_reconciles.insert({key, current_reconcile}); + } + } + + // Wallet + const auto* wallet_value = dictionary->FindKey(kWalletKey); + if (!wallet_value || !wallet_value->is_dict()) { + NOTREACHED(); + return false; + } + + const base::DictionaryValue* wallet_dictionary = nullptr; + wallet_value->GetAsDictionary(&wallet_dictionary); + if (!wallet_dictionary) { + NOTREACHED(); + return false; + } + + WalletProperties wallet; + const WalletState wallet_state; + if (!wallet_state.FromDict(wallet_dictionary, &wallet)) { + return false; + } + client_properties.wallet = wallet; + + // Inline Tips + const auto* inline_tips_value = dictionary->FindKey(kInlineTipsKey); + if (inline_tips_value) { + if (!inline_tips_value->is_dict()) { + NOTREACHED(); + return false; + } + + for (const auto& inline_tip_value : inline_tips_value->DictItems()) { + const auto& key = inline_tip_value.first; + const auto& value = inline_tip_value.second; + + if (!value.is_bool()) { + NOTREACHED(); + continue; + } + + client_properties.inline_tips.insert({key, value.GetBool()}); + } + } + + *properties = client_properties; + + return true; +} + +bool ClientState::ToJson( + JsonWriter* writer, + const ClientProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kWalletInfoKey); + const WalletInfoState wallet_info_state; + wallet_info_state.ToJson(writer, properties.wallet_info); + + writer->String(kBootTimestampKey); + writer->Uint64(properties.boot_timestamp); + + writer->String(kReconcileTimestampKey); + writer->Uint64(properties.reconcile_timestamp); + + writer->String(kPersonaIdKey); + writer->String(properties.persona_id.c_str()); + + writer->String(kUserIdKey); + writer->String(properties.user_id.c_str()); + + writer->String(kRegistrarVkKey); + writer->String(properties.registrar_vk.c_str()); + + writer->String(kMasterUserTokenKey); + writer->String(properties.master_user_token.c_str()); + + writer->String(kPreFlightKey); + writer->String(properties.pre_flight.c_str()); + + writer->String(kFeeCurrencyKey); + writer->String(properties.fee_currency.c_str()); + + writer->String(kSettingsKey); + writer->String(properties.settings.c_str()); + + writer->String(kFeeAmountKey); + writer->Double(properties.fee_amount); + + writer->String(kUserChangedFeeKey); + writer->Bool(properties.user_changed_fee); + + writer->String(kDaysKey); + writer->Uint(properties.days); + + writer->String(kRewardsEnabledKey); + writer->Bool(properties.rewards_enabled); + + writer->String(kAutoContributeKey); + writer->Bool(properties.auto_contribute); + + writer->String(kTransactionsKey); + writer->StartArray(); + const TransactionState transaction_state; + for (const auto& transaction : properties.transactions) { + transaction_state.ToJson(writer, transaction); + } + writer->EndArray(); + + writer->String(kBallotsKey); + writer->StartArray(); + const BallotState ballot_state; + for (const auto& ballot : properties.ballots) { + if (!ballot_state.ToJson(writer, ballot)) { + NOTREACHED(); + continue; + } + } + writer->EndArray(); + + writer->String(kPublisherVotesKey); + writer->StartArray(); + const PublisherVotesState publisher_votes_state; + for (const auto& publisher_vote : properties.publisher_votes) { + if (!publisher_votes_state.ToJson(writer, publisher_vote)) { + NOTREACHED(); + continue; + } + } + writer->EndArray(); + + writer->String(kCurrentReconcilesKey); + writer->StartObject(); + const CurrentReconcileState current_reconcile_state; + for (const auto& current_reconcile : properties.current_reconciles) { + writer->Key(current_reconcile.first.c_str()); + if (!current_reconcile_state.ToJson(writer, current_reconcile.second)) { + NOTREACHED(); + continue; + } + } + writer->EndObject(); + + writer->String(kWalletKey); + const WalletState wallet_state; + wallet_state.ToJson(writer, properties.wallet); + + writer->String(kInlineTipsKey); + writer->StartObject(); + for (const auto &inline_tip : properties.inline_tips) { + writer->String(inline_tip.first.c_str()); + writer->Bool(inline_tip.second); + } + writer->EndObject(); + + writer->EndObject(); + + return true; +} + +std::string ClientState::ToJson( + const ClientProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.h new file mode 100644 index 000000000000..6efb0a4b7ff4 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_CLIENT_STATE_H_ +#define BRAVELEDGER_STATE_CLIENT_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/client_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class ClientState + : public state::Reader, + public state::Writer { + public: + ClientState(); + ~ClientState(); + + bool FromJson( + const std::string& json, + ClientProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + ClientProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const ClientProperties& properties) const override; + + std::string ToJson( + const ClientProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_CLIENT_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc new file mode 100644 index 000000000000..a92cce4838ca --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/client_state_unittest.cc @@ -0,0 +1,353 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include +#include + +#include "bat/ledger/internal/state/client_state.h" +#include "base/base64.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=ClientStateTest.* + +namespace ledger { + +class ClientStateTest : public ::testing::Test { + protected: + ClientStateTest() { + // You can do set-up work for each test here + } + + ~ClientStateTest() override { + // You can do clean-up work that doesn't throw exceptions here + } + + // If the constructor and destructor are not enough for setting up and + // cleaning up each test, you can use the following methods + + void SetUp() override { + // Code here will be called immediately after the constructor (right before + // each test) + } + + void TearDown() override { + // Code here will be called immediately after each test (right before the + // destructor) + } + + // Objects declared here can be used by all tests in the test case + WalletInfoProperties GetWalletInfoProperties() const { + WalletInfoProperties wallet_info_properties; + wallet_info_properties.payment_id = "PaymentId"; + wallet_info_properties.address_card_id = "AddressCardId"; + + std::string key_info_seed; + std::string base64_key_info_seed = + "/kBv0C7wS4EBY3EIa780pYLrhryP3IWCfElIehufOFw="; + base::Base64Decode(base64_key_info_seed, &key_info_seed); + wallet_info_properties.key_info_seed.assign(key_info_seed.begin(), + key_info_seed.end()); + + return wallet_info_properties; + } + + WalletProperties GetWalletProperties() const { + WalletProperties wallet_properties; + wallet_properties.fee_amount = std::numeric_limits::max(); + wallet_properties.parameters_choices = { + 5.0, + 10.0, + 15.0, + 20.0, + 25.0, + 50.0, + 100.0 + }; + + return wallet_properties; + } + + Transactions GetTransactions( + const int count) const { + TransactionProperties transaction_properties; + transaction_properties.viewing_id = "ViewingId"; + transaction_properties.surveyor_id = "SurveyorId"; + transaction_properties.contribution_probi = "ContributionProbi"; + transaction_properties.submission_timestamp = "SubmissionTimestamp"; + transaction_properties.anonize_viewing_id = "AnonizeViewingId"; + transaction_properties.registrar_vk = "RegistrarVk"; + transaction_properties.master_user_token = "MasterUserToken"; + transaction_properties.surveyor_ids = { "SurveyorId" }; + transaction_properties.vote_count = + std::numeric_limits::max(); + transaction_properties.contribution_rates = { + { "BAT", 1.0 }, + { "ETH", 2.0 }, + { "LTC", 3.0 }, + { "BTC", 4.0 }, + { "USD", 5.0 }, + { "EUR", 6.0 } + }; + + TransactionBallotProperties transaction_ballot_properties; + transaction_ballot_properties.publisher = "Publisher"; + transaction_ballot_properties.count = + std::numeric_limits::max(); + transaction_properties.transaction_ballots.push_back( + transaction_ballot_properties); + + Transactions transactions; + for (int i = 0; i < count; i++) { + transactions.push_back(transaction_properties); + } + + return transactions; + } + + Ballots GetBallots( + const int count) const { + BallotProperties ballot_properties; + ballot_properties.viewing_id = "ViewingId"; + ballot_properties.surveyor_id = "SurveyorId"; + ballot_properties.publisher = "Publisher"; + ballot_properties.count = std::numeric_limits::max(); + ballot_properties.prepare_ballot = "PrepareBallot"; + + Ballots ballots; + for (int i = 0; i < count; i++) { + ballots.push_back(ballot_properties); + } + + return ballots; + } + + PublisherVotes GetPublisherVotes( + const int count) const { + PublisherVotesProperties publisher_votes_properties; + publisher_votes_properties.publisher = "Publisher"; + + PublisherVoteProperties publisher_vote_properties; + publisher_vote_properties.surveyor_id = "SurveyorId"; + publisher_vote_properties.proof = "Proof"; + publisher_votes_properties.batch_votes.push_back(publisher_vote_properties); + + PublisherVotes publisher_votes; + for (int i = 0; i < count; i++) { + publisher_votes.push_back(publisher_votes_properties); + } + + return publisher_votes; + } + + CurrentReconciles GetCurrentReconciles( + const int count) const { + CurrentReconcileProperties current_reconcile_properties; + current_reconcile_properties.viewing_id = "ViewingId"; + current_reconcile_properties.anonize_viewing_id = "AnonizeViewingId"; + current_reconcile_properties.registrar_vk = "RegistrarVk"; + current_reconcile_properties.pre_flight = "PreFlight"; + current_reconcile_properties.master_user_token = "MasterUserToken"; + current_reconcile_properties.surveyor_id = "SurveyorId"; + + current_reconcile_properties.timestamp = + std::numeric_limits::max(); + current_reconcile_properties.rates = { + { "BAT", 1.0 }, + { "ETH", 2.0 }, + { "LTC", 3.0 }, + { "BTC", 4.0 }, + { "USD", 5.0 }, + { "EUR", 6.0 } + }; + current_reconcile_properties.amount = "Amount"; + current_reconcile_properties.currency = "Currency"; + current_reconcile_properties.fee = std::numeric_limits::max(); + + ReconcileDirectionProperties reconcile_direction_properties; + reconcile_direction_properties.publisher_key = "PublisherKey"; + reconcile_direction_properties.amount_percent = + std::numeric_limits::max(); + current_reconcile_properties.directions.push_back( + reconcile_direction_properties); + + current_reconcile_properties.type = RewardsType::ONE_TIME_TIP; + current_reconcile_properties.retry_step = ContributionRetry::STEP_RECONCILE; + current_reconcile_properties.retry_level = + std::numeric_limits::max(); + current_reconcile_properties.destination = "Destination"; + current_reconcile_properties.proof = "Proof"; + + CurrentReconciles current_reconciles; + for (int i = 0; i < count; i++) { + const std::string key = std::to_string(i); + current_reconciles.insert({key, current_reconcile_properties}); + } + + return current_reconciles; + } + + std::map GetInlineTips( + const int count) const { + std::map inline_tips; + for (int i = 0; i < count; i++) { + const std::string key = std::to_string(i); + inline_tips.insert({key, true}); + } + + return inline_tips; + } +}; + +TEST_F(ClientStateTest, ToJsonSerializationWithMinValues) { + // Arrange + ClientProperties client_properties; + client_properties.wallet_info = GetWalletInfoProperties(); + client_properties.wallet = GetWalletProperties(); + client_properties.boot_timestamp = + std::numeric_limits::min(); + client_properties.reconcile_timestamp = + std::numeric_limits::min(); + client_properties.persona_id = "PersonaId"; + client_properties.user_id = "UserId"; + client_properties.registrar_vk = "RegistrarVk"; + client_properties.master_user_token = "MasterUserToken"; + client_properties.pre_flight = "PreFlight"; + client_properties.fee_currency = "FeeCurrency"; + client_properties.settings = "Settings"; + client_properties.fee_amount = std::numeric_limits::min(); + client_properties.user_changed_fee = true; + client_properties.days = std::numeric_limits::min(); + client_properties.transactions = GetTransactions(1); + client_properties.ballots = GetBallots(1); + client_properties.publisher_votes = GetPublisherVotes(1); + client_properties.current_reconciles = GetCurrentReconciles(1); + client_properties.auto_contribute = true; + client_properties.rewards_enabled = true; + client_properties.inline_tips = GetInlineTips(1); + + // Act + const ClientState client_state; + const std::string json = client_state.ToJson(client_properties); + + // Assert + ClientProperties expected_client_properties; + client_state.FromJson(json, &expected_client_properties); + EXPECT_EQ(expected_client_properties, client_properties); +} + +TEST_F(ClientStateTest, FromJsonDeserializationWithMinValues) { + // Arrange + ClientProperties client_properties; + client_properties.wallet_info = GetWalletInfoProperties(); + client_properties.wallet = GetWalletProperties(); + client_properties.boot_timestamp = + std::numeric_limits::min(); + client_properties.reconcile_timestamp = + std::numeric_limits::min(); + client_properties.persona_id = "PersonaId"; + client_properties.user_id = "UserId"; + client_properties.registrar_vk = "RegistrarVk"; + client_properties.master_user_token = "MasterUserToken"; + client_properties.pre_flight = "PreFlight"; + client_properties.fee_currency = "FeeCurrency"; + client_properties.settings = "Settings"; + client_properties.fee_amount = std::numeric_limits::min(); + client_properties.user_changed_fee = true; + client_properties.days = std::numeric_limits::min(); + client_properties.transactions = GetTransactions(1); + client_properties.ballots = GetBallots(1); + client_properties.publisher_votes = GetPublisherVotes(1); + client_properties.current_reconciles = GetCurrentReconciles(1); + client_properties.auto_contribute = true; + client_properties.rewards_enabled = true; + client_properties.inline_tips = GetInlineTips(1); + + const std::string json = "{\"walletInfo\":{\"paymentId\":\"PaymentId\",\"addressCARD_ID\":\"AddressCardId\",\"keyInfoSeed\":\"/kBv0C7wS4EBY3EIa780pYLrhryP3IWCfElIehufOFw=\"},\"bootStamp\":0,\"reconcileStamp\":0,\"personaId\":\"PersonaId\",\"userId\":\"UserId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"preFlight\":\"PreFlight\",\"fee_currency\":\"FeeCurrency\",\"settings\":\"Settings\",\"fee_amount\":2.2250738585072014e-308,\"user_changed_fee\":true,\"days\":0,\"rewards_enabled\":true,\"auto_contribute\":true,\"transactions\":[{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"contribution_probi\":\"ContributionProbi\",\"submissionStamp\":\"SubmissionTimestamp\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"surveyorIds\":[\"SurveyorId\"],\"votes\":4294967295,\"ballots\":[{\"publisher\":\"Publisher\",\"offset\":4294967295}]}],\"ballots\":[{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"}],\"batch\":[{\"publisher\":\"Publisher\",\"batchVotesInfo\":[{\"surveyorId\":\"SurveyorId\",\"proof\":\"Proof\"}]}],\"current_reconciles\":{\"0\":{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"}},\"walletProperties\":{\"fee_amount\":1.7976931348623157e308,\"parameters\":{\"adFree\":{\"fee\":{\"BAT\":1.7976931348623157e308},\"choices\":{\"BAT\":[5.0,10.0,15.0,20.0,25.0,50.0,100.0]}}}},\"inlineTip\":{\"0\":true}}"; // NOLINT + + // Act + ClientProperties expected_client_properties; + const ClientState client_state; + client_state.FromJson(json, &expected_client_properties); + + // Assert + EXPECT_EQ(expected_client_properties, client_properties); +} + +TEST_F(ClientStateTest, ToJsonSerializationWithMaxValues) { + // Arrange + ClientProperties client_properties; + client_properties.wallet_info = GetWalletInfoProperties(); + client_properties.wallet = GetWalletProperties(); + client_properties.boot_timestamp = + std::numeric_limits::max(); + client_properties.reconcile_timestamp = + std::numeric_limits::max(); + client_properties.persona_id = "PersonaId"; + client_properties.user_id = "UserId"; + client_properties.registrar_vk = "RegistrarVk"; + client_properties.master_user_token = "MasterUserToken"; + client_properties.pre_flight = "PreFlight"; + client_properties.fee_currency = "FeeCurrency"; + client_properties.settings = "Settings"; + client_properties.fee_amount = std::numeric_limits::max(); + client_properties.user_changed_fee = true; + client_properties.days = std::numeric_limits::max(); + client_properties.transactions = GetTransactions(3); + client_properties.ballots = GetBallots(7); + client_properties.publisher_votes = GetPublisherVotes(1); + client_properties.current_reconciles = GetCurrentReconciles(5); + client_properties.auto_contribute = true; + client_properties.rewards_enabled = true; + client_properties.inline_tips = GetInlineTips(9); + + // Act + const ClientState client_state; + const std::string json = client_state.ToJson(client_properties); + + // Assert + ClientProperties expected_client_properties; + client_state.FromJson(json, &expected_client_properties); + EXPECT_EQ(expected_client_properties, client_properties); +} + +TEST_F(ClientStateTest, FromJsonDeserializationWithMaxValues) { + // Arrange + ClientProperties client_properties; + client_properties.wallet_info = GetWalletInfoProperties(); + client_properties.wallet = GetWalletProperties(); + client_properties.boot_timestamp = + std::numeric_limits::max(); + client_properties.reconcile_timestamp = + std::numeric_limits::max(); + client_properties.persona_id = "PersonaId"; + client_properties.user_id = "UserId"; + client_properties.registrar_vk = "RegistrarVk"; + client_properties.master_user_token = "MasterUserToken"; + client_properties.pre_flight = "PreFlight"; + client_properties.fee_currency = "FeeCurrency"; + client_properties.settings = "Settings"; + client_properties.fee_amount = std::numeric_limits::max(); + client_properties.user_changed_fee = true; + client_properties.days = std::numeric_limits::max(); + client_properties.transactions = GetTransactions(3); + client_properties.ballots = GetBallots(7); + client_properties.publisher_votes = GetPublisherVotes(1); + client_properties.current_reconciles = GetCurrentReconciles(5); + client_properties.auto_contribute = true; + client_properties.rewards_enabled = true; + client_properties.inline_tips = GetInlineTips(9); + + const std::string json = "{\"walletInfo\":{\"paymentId\":\"PaymentId\",\"addressCARD_ID\":\"AddressCardId\",\"keyInfoSeed\":\"/kBv0C7wS4EBY3EIa780pYLrhryP3IWCfElIehufOFw=\"},\"bootStamp\":4294967295,\"reconcileStamp\":4294967295,\"personaId\":\"PersonaId\",\"userId\":\"UserId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"preFlight\":\"PreFlight\",\"fee_currency\":\"FeeCurrency\",\"settings\":\"Settings\",\"fee_amount\":1.7976931348623157e308,\"user_changed_fee\":true,\"days\":4294967295,\"rewards_enabled\":true,\"auto_contribute\":true,\"transactions\":[{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"contribution_probi\":\"ContributionProbi\",\"submissionStamp\":\"SubmissionTimestamp\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"surveyorIds\":[\"SurveyorId\"],\"votes\":4294967295,\"ballots\":[{\"publisher\":\"Publisher\",\"offset\":4294967295}]},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"contribution_probi\":\"ContributionProbi\",\"submissionStamp\":\"SubmissionTimestamp\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"surveyorIds\":[\"SurveyorId\"],\"votes\":4294967295,\"ballots\":[{\"publisher\":\"Publisher\",\"offset\":4294967295}]},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"contribution_probi\":\"ContributionProbi\",\"submissionStamp\":\"SubmissionTimestamp\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"surveyorIds\":[\"SurveyorId\"],\"votes\":4294967295,\"ballots\":[{\"publisher\":\"Publisher\",\"offset\":4294967295}]}],\"ballots\":[{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"},{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"publisher\":\"Publisher\",\"offset\":4294967295,\"prepareBallot\":\"PrepareBallot\"}],\"batch\":[{\"publisher\":\"Publisher\",\"batchVotesInfo\":[{\"surveyorId\":\"SurveyorId\",\"proof\":\"Proof\"}]}],\"current_reconciles\":{\"0\":{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"},\"1\":{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"},\"2\":{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"},\"3\":{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"},\"4\":{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"}},\"walletProperties\":{\"fee_amount\":1.7976931348623157e308,\"parameters\":{\"adFree\":{\"fee\":{\"BAT\":1.7976931348623157e308},\"choices\":{\"BAT\":[5.0,10.0,15.0,20.0,25.0,50.0,100.0]}}}},\"inlineTip\":{\"0\":true,\"1\":true,\"2\":true,\"3\":true,\"4\":true,\"5\":true,\"6\":true,\"7\":true,\"8\":true}}"; // NOLINT + + // Act + ClientProperties expected_client_properties; + const ClientState client_state; + client_state.FromJson(json, &expected_client_properties); + + // Assert + EXPECT_EQ(expected_client_properties, client_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.cc new file mode 100644 index 000000000000..e477fc96b499 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.cc @@ -0,0 +1,382 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/current_reconcile_state.h" +#include "bat/ledger/internal/state/reconcile_direction_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAmountKey[] = "amount"; +const char kAnonizeViewingIdKey[] = "anonizeViewingId"; +const char kCategoryKey[] = "category"; +const char kCurrencyKey[] = "currency"; +const char kDestinationKey[] = "destination"; +const char kDirectionsKey[] = "directions"; +const char kFeeKey[] = "fee"; +const char kIdKey[] = "id"; +const char kListKey[] = "list"; +const char kMasterUserTokenKey[] = "masterUserToken"; +const char kPreFlightKey[] = "preFlight"; +const char kProofKey[] = "proof"; +const char kRatesKey[] = "rates"; +const char kRegistrarVkKey[] = "registrarVK"; +const char kRetryLevelKey[] = "retry_level"; +const char kRetryStepKey[] = "retry_step"; +const char kSurveyorIdKey[] = "surveyorId"; +const char kSurveyorInfoKey[] = "surveyorInfo"; +const char kTimestampKey[] = "timestamp"; +const char kTypeKey[] = "type"; +const char kViewingIdKey[] = "viewingId"; +const char kWeightKey[] = "weight"; + +} // namespace + +CurrentReconcileState::CurrentReconcileState() = default; + +CurrentReconcileState::~CurrentReconcileState() = default; + +bool CurrentReconcileState::FromJson( + const std::string& json, + CurrentReconcileProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool CurrentReconcileState::FromDict( + const base::DictionaryValue* dictionary, + CurrentReconcileProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + CurrentReconcileProperties current_reconcile_properties; + + // Viewing Id + const auto* viewing_id = dictionary->FindStringKey(kViewingIdKey); + if (!viewing_id) { + NOTREACHED(); + return false; + } + current_reconcile_properties.viewing_id = *viewing_id; + + // Anonize Viewing Id + const auto* anonize_viewing_id = + dictionary->FindStringKey(kAnonizeViewingIdKey); + if (anonize_viewing_id) { + current_reconcile_properties.anonize_viewing_id = *anonize_viewing_id; + } + + // Registrar Vk + const auto* registrar_vk = dictionary->FindStringKey(kRegistrarVkKey); + if (registrar_vk) { + current_reconcile_properties.registrar_vk = *registrar_vk; + } + + // Pre Flight + const auto* pre_flight = dictionary->FindStringKey(kPreFlightKey); + if (pre_flight) { + current_reconcile_properties.pre_flight = *pre_flight; + } + + // Master User Token + const auto* master_user_token = + dictionary->FindStringKey(kMasterUserTokenKey); + if (master_user_token) { + current_reconcile_properties.master_user_token = *master_user_token; + } + + // Timestamp (There is no support for uint64_t. Writing JSON with such types + // violates the spec. As we need a uint64_t, we need to use an unsigned int + // and cast to a uint64_t) + const auto timestamp = dictionary->FindDoubleKey(kTimestampKey); + if (timestamp) { + current_reconcile_properties.timestamp = static_cast(*timestamp); + } + + // Amount + const auto* amount = dictionary->FindStringKey(kAmountKey); + if (amount) { + current_reconcile_properties.amount = *amount; + } + + // Currency + const auto* currency = dictionary->FindStringKey(kCurrencyKey); + if (currency) { + current_reconcile_properties.currency = *currency; + } + + // Fee + const auto fee = dictionary->FindDoubleKey(kFeeKey); + if (!fee) { + NOTREACHED(); + return false; + } + current_reconcile_properties.fee = *fee; + + // Type + const auto type = dictionary->FindIntKey(kTypeKey); + if (type) { + current_reconcile_properties.type = static_cast(*type); + } else { + const auto category = dictionary->FindIntKey(kCategoryKey); + if (!category) { + NOTREACHED(); + return false; + } + + // Transition from legacy Category to Type + current_reconcile_properties.type = static_cast(*category); + } + + // Surveyor Info + const auto* surveyor_info_dictionary = + dictionary->FindDictKey(kSurveyorInfoKey); + if (surveyor_info_dictionary) { + const auto* surveyor_id = + surveyor_info_dictionary->FindStringKey(kSurveyorIdKey); + if (!surveyor_id) { + NOTREACHED(); + return false; + } + + current_reconcile_properties.surveyor_id = *surveyor_id; + } + + // Rates + const auto* rates = dictionary->FindDictKey(kRatesKey); + if (rates) { + for (const auto& rate : rates->DictItems()) { + const std::string currency_code = rate.first; + + const auto& exchange_rate_value = rate.second; + const double exchange_rate = exchange_rate_value.GetDouble(); + + current_reconcile_properties.rates.insert({currency_code, exchange_rate}); + } + } + + // Reconcile Directions + const auto* reconcile_directions_list = + dictionary->FindListKey(kDirectionsKey); + if (reconcile_directions_list) { + const ReconcileDirectionState reconcile_direction_state; + for (const auto& reconcile_direction_value : + reconcile_directions_list->GetList()) { + if (!reconcile_direction_value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* reconcile_direction_dictionary = nullptr; + reconcile_direction_value.GetAsDictionary( + &reconcile_direction_dictionary); + if (!reconcile_direction_dictionary) { + NOTREACHED(); + continue; + } + + ReconcileDirectionProperties reconcile_direction; + if (!reconcile_direction_state.FromDict(reconcile_direction_dictionary, + &reconcile_direction)) { + continue; + } + + current_reconcile_properties.directions.push_back(reconcile_direction); + } + } + + // Transition legacy list to reconcile directions + const auto* list_list = dictionary->FindListKey(kListKey); + if (list_list) { + for (const auto& list_value : list_list->GetList()) { + if (!list_value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* list_dictionary = nullptr; + list_value.GetAsDictionary(&list_dictionary); + if (!list_dictionary) { + NOTREACHED(); + continue; + } + + ReconcileDirectionProperties reconcile_direction; + + const auto* id = list_dictionary->FindStringKey(kIdKey); + if (!id) { + NOTREACHED(); + continue; + } + reconcile_direction.publisher_key = *id; + + const auto weight = list_dictionary->FindDoubleKey(kWeightKey); + if (!weight) { + NOTREACHED(); + continue; + } + reconcile_direction.amount_percent = *weight; + + current_reconcile_properties.directions.push_back(reconcile_direction); + } + } + + // Retry Step + const auto retry_step = dictionary->FindIntKey(kRetryStepKey); + if (retry_step) { + current_reconcile_properties.retry_step = + static_cast(*retry_step); + } + + // Retry Level + const auto retry_level = dictionary->FindIntKey(kRetryLevelKey); + if (retry_level) { + current_reconcile_properties.retry_level = *retry_level; + } + + // Destination + const auto* destination = dictionary->FindStringKey(kDestinationKey); + if (destination) { + current_reconcile_properties.destination = *destination; + } + + // Proof + const auto* proof = dictionary->FindStringKey(kProofKey); + if (proof) { + current_reconcile_properties.proof = *proof; + } + + *properties = current_reconcile_properties; + + return true; +} + +bool CurrentReconcileState::ToJson( + JsonWriter* writer, + const CurrentReconcileProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kViewingIdKey); + writer->String(properties.viewing_id.c_str()); + + writer->String(kAnonizeViewingIdKey); + writer->String(properties.anonize_viewing_id.c_str()); + + writer->String(kRegistrarVkKey); + writer->String(properties.registrar_vk.c_str()); + + writer->String(kPreFlightKey); + writer->String(properties.pre_flight.c_str()); + + writer->String(kMasterUserTokenKey); + writer->String(properties.master_user_token.c_str()); + + writer->String(kSurveyorInfoKey); + writer->StartObject(); + writer->String(kSurveyorIdKey); + writer->String(properties.surveyor_id.c_str()); + writer->EndObject(); + + writer->String(kTimestampKey); + writer->Uint64(properties.timestamp); + + writer->String(kAmountKey); + writer->String(properties.amount.c_str()); + + writer->String(kCurrencyKey); + writer->String(properties.currency.c_str()); + + writer->String(kFeeKey); + writer->Double(properties.fee); + + writer->String(kTypeKey); + writer->Int(static_cast(properties.type)); + + writer->String(kRatesKey); + writer->StartObject(); + for (const auto &rate : properties.rates) { + writer->String(rate.first.c_str()); + writer->Double(rate.second); + } + writer->EndObject(); + + writer->String(kDirectionsKey); + writer->StartArray(); + const ReconcileDirectionState reconcile_direction_state; + for (const auto& direction : properties.directions) { + reconcile_direction_state.ToJson(writer, direction); + } + writer->EndArray(); + + writer->String(kRetryStepKey); + writer->Int(static_cast(properties.retry_step)); + + writer->String(kRetryLevelKey); + writer->Int(properties.retry_level); + + writer->String(kDestinationKey); + writer->String(properties.destination.c_str()); + + writer->String(kProofKey); + writer->String(properties.proof.c_str()); + + writer->EndObject(); + + return true; +} + +std::string CurrentReconcileState::ToJson( + const CurrentReconcileProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.h new file mode 100644 index 000000000000..6f6bf9bcdbe5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_CURRENT_RECONCILE_STATE_H_ +#define BRAVELEDGER_STATE_CURRENT_RECONCILE_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/current_reconcile_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class CurrentReconcileState + : public state::Reader, + public state::Writer { + public: + CurrentReconcileState(); + ~CurrentReconcileState(); + + bool FromJson( + const std::string& json, + CurrentReconcileProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + CurrentReconcileProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const CurrentReconcileProperties& properties) const override; + + std::string ToJson( + const CurrentReconcileProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_CURRENT_RECONCILE_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc new file mode 100644 index 000000000000..e81ee5cc48e5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/current_reconcile_state_unittest.cc @@ -0,0 +1,120 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/current_reconcile_state.h" +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=CurrentReconcileStateTest.* + +namespace ledger { + +// TODO(tmancey): Test transition from legacy list to reconcile directions + +TEST(CurrentReconcileStateTest, ToJsonSerialization) { + // Arrange + CurrentReconcileProperties current_reconcile_properties; + current_reconcile_properties.viewing_id = "ViewingId"; + current_reconcile_properties.anonize_viewing_id = "AnonizeViewingId"; + current_reconcile_properties.registrar_vk = "RegistrarVk"; + current_reconcile_properties.pre_flight = "PreFlight"; + current_reconcile_properties.master_user_token = "MasterUserToken"; + current_reconcile_properties.surveyor_id = "SurveyorId"; + + current_reconcile_properties.timestamp = + std::numeric_limits::max(); + current_reconcile_properties.rates = { + { "BAT", 1.0 }, + { "ETH", 2.0 }, + { "LTC", 3.0 }, + { "BTC", 4.0 }, + { "USD", 5.0 }, + { "EUR", 6.0 } + }; + current_reconcile_properties.amount = "Amount"; + current_reconcile_properties.currency = "Currency"; + current_reconcile_properties.fee = std::numeric_limits::max(); + + ReconcileDirectionProperties reconcile_direction_properties; + reconcile_direction_properties.publisher_key = "PublisherKey"; + reconcile_direction_properties.amount_percent = + std::numeric_limits::max(); + current_reconcile_properties.directions.push_back( + reconcile_direction_properties); + + current_reconcile_properties.type = RewardsType::ONE_TIME_TIP; + current_reconcile_properties.retry_step = ContributionRetry::STEP_RECONCILE; + current_reconcile_properties.retry_level = + std::numeric_limits::max(); + current_reconcile_properties.destination = "Destination"; + current_reconcile_properties.proof = "Proof"; + + // Act + const CurrentReconcileState current_reconcile_state; + const std::string json = + current_reconcile_state.ToJson(current_reconcile_properties); + + // Assert + CurrentReconcileProperties expected_current_reconcile_properties; + current_reconcile_state.FromJson(json, + &expected_current_reconcile_properties); + EXPECT_EQ(expected_current_reconcile_properties, + current_reconcile_properties); +} + +TEST(CurrentReconcileStateTest, FromJsonDeserialization) { + // Arrange + CurrentReconcileProperties current_reconcile_properties; + current_reconcile_properties.viewing_id = "ViewingId"; + current_reconcile_properties.anonize_viewing_id = "AnonizeViewingId"; + current_reconcile_properties.registrar_vk = "RegistrarVk"; + current_reconcile_properties.pre_flight = "PreFlight"; + current_reconcile_properties.master_user_token = "MasterUserToken"; + current_reconcile_properties.surveyor_id = "SurveyorId"; + + current_reconcile_properties.timestamp = + std::numeric_limits::max(); + current_reconcile_properties.rates = { + { "BAT", 1.0 }, + { "ETH", 2.0 }, + { "LTC", 3.0 }, + { "BTC", 4.0 }, + { "USD", 5.0 }, + { "EUR", 6.0 } + }; + current_reconcile_properties.amount = "Amount"; + current_reconcile_properties.currency = "Currency"; + current_reconcile_properties.fee = std::numeric_limits::max(); + + ReconcileDirectionProperties reconcile_direction_properties; + reconcile_direction_properties.publisher_key = "PublisherKey"; + reconcile_direction_properties.amount_percent = + std::numeric_limits::max(); + current_reconcile_properties.directions.push_back( + reconcile_direction_properties); + + current_reconcile_properties.type = RewardsType::ONE_TIME_TIP; + current_reconcile_properties.retry_step = ContributionRetry::STEP_RECONCILE; + current_reconcile_properties.retry_level = + std::numeric_limits::max(); + current_reconcile_properties.destination = "Destination"; + current_reconcile_properties.proof = "Proof"; + + const std::string json = "{\"viewingId\":\"ViewingId\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"preFlight\":\"PreFlight\",\"masterUserToken\":\"MasterUserToken\",\"surveyorInfo\":{\"surveyorId\":\"SurveyorId\"},\"timestamp\":4294967295,\"amount\":\"Amount\",\"currency\":\"Currency\",\"fee\":1.7976931348623157e308,\"type\":8,\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"directions\":[{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"PublisherKey\"}],\"retry_step\":1,\"retry_level\":2147483647,\"destination\":\"Destination\",\"proof\":\"Proof\"}"; // NOLINT + + // Act + CurrentReconcileProperties expected_current_reconcile_properties; + const CurrentReconcileState current_reconcile_state; + current_reconcile_state.FromJson(json, + &expected_current_reconcile_properties); + + // Assert + EXPECT_EQ(expected_current_reconcile_properties, + current_reconcile_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state.cc new file mode 100644 index 000000000000..c8b73c0c9484 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state.cc @@ -0,0 +1,257 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/publisher_settings_state.h" +#include "bat/ledger/internal/state/report_balance_state.h" +#include "base/json/json_reader.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAllowNonVerifiedSitesInListKey[] = "allow_non_verified"; +const char kAllowContributionToVideosKey[] = "allow_videos"; +const char kMigrateScore2Key[] = "migrate_score_2"; +// There is a spelling error with min_pubslisher_duration, however we cannot +// change this otherwise we will break legacy installs. This will be resolved as +// part of https://github.com/brave/brave-browser/issues/7024 +const char kMinPageTimeBeforeLoggingAVisitKey[] = "min_pubslisher_duration"; +const char kMinVisitsForPublisherRelevancy[] = "min_visits"; +const char kMonthlyBalancesKey[] = "monthly_balances"; +const char kProcessedPendingPublishersKey[] = "processed_pending_publishers"; + +} // namespace + +PublisherSettingsState::PublisherSettingsState() = default; + +PublisherSettingsState::~PublisherSettingsState() = default; + +bool PublisherSettingsState::FromJson( + const std::string& json, + PublisherSettingsProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool PublisherSettingsState::FromDict( + const base::DictionaryValue* dictionary, + PublisherSettingsProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + PublisherSettingsProperties publisher_settings_properties; + + // Min Publisher Duration (There is no support for uint64_t. Writing JSON with + // such types violates the spec. As we need a uint64_t, we need to use a + // double and cast to a uint64_t) + const auto min_page_time_before_logging_a_visit = + dictionary->FindDoubleKey(kMinPageTimeBeforeLoggingAVisitKey); + if (!min_page_time_before_logging_a_visit) { + NOTREACHED(); + return false; + } + publisher_settings_properties.min_page_time_before_logging_a_visit = + static_cast(*min_page_time_before_logging_a_visit); + + // Min Visits (There is no support for unsigned int. Writing JSON with such + // types violates the spec. As we need an unsigned int, we need to a double + // and cast to an unsigned int) + const auto min_visits_for_publisher_relevancy = + dictionary->FindDoubleKey(kMinVisitsForPublisherRelevancy); + if (!min_visits_for_publisher_relevancy) { + NOTREACHED(); + return false; + } + publisher_settings_properties.min_visits_for_publisher_relevancy = + static_cast(*min_visits_for_publisher_relevancy); + + // Allow Non Verified + const auto allow_non_verified_sites_in_list = + dictionary->FindBoolKey(kAllowNonVerifiedSitesInListKey); + if (!allow_non_verified_sites_in_list) { + NOTREACHED(); + return false; + } + publisher_settings_properties.allow_non_verified_sites_in_list = + *allow_non_verified_sites_in_list; + + // Allow Videos + const auto allow_contribution_to_videos = + dictionary->FindBoolKey(kAllowContributionToVideosKey); + if (!allow_contribution_to_videos) { + NOTREACHED(); + return false; + } + publisher_settings_properties.allow_contribution_to_videos = + *allow_contribution_to_videos; + + // Monthly Balances + const auto* monthly_balances_list = + dictionary->FindListKey(kMonthlyBalancesKey); + if (!monthly_balances_list) { + NOTREACHED(); + return false; + } + + const ReportBalanceState report_balance_state; + for (const auto& monthly_balance_value : monthly_balances_list->GetList()) { + if (!monthly_balance_value.is_dict()) { + NOTREACHED(); + continue; + } + + for (const auto& item : monthly_balance_value.DictItems()) { + const auto& key = item.first; + const auto& value = item.second; + + if (!value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* monthly_balance_dictionary = nullptr; + value.GetAsDictionary(&monthly_balance_dictionary); + if (!monthly_balance_dictionary) { + NOTREACHED(); + continue; + } + + ReportBalanceProperties report_balance; + if (!report_balance_state.FromDict(monthly_balance_dictionary, + &report_balance)) { + continue; + } + + publisher_settings_properties.monthly_balances.insert( + {key, report_balance}); + } + } + + // Migrate Score 2 + const auto migrate_score_2 = dictionary->FindBoolKey(kMigrateScore2Key); + if (migrate_score_2) { + publisher_settings_properties.migrate_score_2 = *migrate_score_2; + } else { + publisher_settings_properties.migrate_score_2 = true; + } + + // Processed Pending Publishers + const auto* processed_pending_publishers_list = + dictionary->FindListKey(kProcessedPendingPublishersKey); + if (processed_pending_publishers_list) { + for (const auto& processed_pending_publisher_value : + processed_pending_publishers_list->GetList()) { + if (!processed_pending_publisher_value.is_string()) { + NOTREACHED(); + continue; + } + + const std::string processed_pending_publisher = + processed_pending_publisher_value.GetString(); + + publisher_settings_properties.processed_pending_publishers.push_back( + processed_pending_publisher); + } + } + + *properties = publisher_settings_properties; + + return true; +} + +bool PublisherSettingsState::ToJson( + JsonWriter* writer, + const PublisherSettingsProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kMinPageTimeBeforeLoggingAVisitKey); + writer->Uint(properties.min_page_time_before_logging_a_visit); + + writer->String(kMinVisitsForPublisherRelevancy); + writer->Uint(properties.min_visits_for_publisher_relevancy); + + writer->String(kAllowNonVerifiedSitesInListKey); + writer->Bool(properties.allow_non_verified_sites_in_list); + + writer->String(kAllowContributionToVideosKey); + writer->Bool(properties.allow_contribution_to_videos); + + writer->String(kMonthlyBalancesKey); + writer->StartArray(); + const ReportBalanceState report_balance_state; + for (const auto& monthly_balance : properties.monthly_balances) { + writer->StartObject(); + writer->String(monthly_balance.first.c_str()); + report_balance_state.ToJson(writer, monthly_balance.second); + writer->EndObject(); + } + writer->EndArray(); + + writer->String(kMigrateScore2Key); + writer->Bool(properties.migrate_score_2); + + writer->String(kProcessedPendingPublishersKey); + writer->StartArray(); + for (const auto &processed_pending_publisher : + properties.processed_pending_publishers) { + writer->String(processed_pending_publisher.c_str()); + } + writer->EndArray(); + + writer->EndObject(); + + return true; +} + +std::string PublisherSettingsState::ToJson( + const PublisherSettingsProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state.h new file mode 100644 index 000000000000..e5ac4712cee5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_PUBLISHER_SETTINGS_STATE_H_ +#define BRAVELEDGER_STATE_PUBLISHER_SETTINGS_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/publisher_settings_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class PublisherSettingsState + : public state::Reader, + public state::Writer { + public: + PublisherSettingsState(); + ~PublisherSettingsState(); + + bool FromJson( + const std::string& json, + PublisherSettingsProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + PublisherSettingsProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const PublisherSettingsProperties& properties) const override; + + std::string ToJson( + const PublisherSettingsProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_PUBLISHER_SETTINGS_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state_unittest.cc new file mode 100644 index 000000000000..0f80fa09d842 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_settings_state_unittest.cc @@ -0,0 +1,98 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/publisher_settings_state.h" +#include "bat/ledger/internal/properties/report_balance_properties.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PublisherSettingsStateTest.* + +namespace ledger { + +TEST(PublisherSettingsStateTest, ToJsonSerialization) { + // Arrange + PublisherSettingsProperties publisher_settings_properties; + publisher_settings_properties.min_page_time_before_logging_a_visit = + std::numeric_limits::max(); + publisher_settings_properties.min_visits_for_publisher_relevancy = + std::numeric_limits::max(); + publisher_settings_properties.allow_non_verified_sites_in_list = true; + publisher_settings_properties.allow_contribution_to_videos = true; + + ReportBalanceProperties report_balance_properties; + report_balance_properties.opening_balance = "OpeningBalance"; + report_balance_properties.closing_balance = "ClosingBalance"; + report_balance_properties.deposits = "Deposits"; + report_balance_properties.grants = "Grants"; + report_balance_properties.ad_earnings = "AdEarnings"; + report_balance_properties.auto_contributions = "AutoContributions"; + report_balance_properties.recurring_donations = "RecurringDonations"; + report_balance_properties.one_time_donations = "OneTimeDonations"; + report_balance_properties.total = "Total"; + publisher_settings_properties.monthly_balances.insert({ + { "Date", report_balance_properties } + }); + + publisher_settings_properties.migrate_score_2 = true; + publisher_settings_properties.processed_pending_publishers.push_back( + "ProcessedPendingPublisher"); + + // Act + const PublisherSettingsState publisher_settings_state; + const std::string json = + publisher_settings_state.ToJson(publisher_settings_properties); + + // Assert + PublisherSettingsProperties expected_publisher_settings_properties; + publisher_settings_state.FromJson(json, + &expected_publisher_settings_properties); + EXPECT_EQ(expected_publisher_settings_properties, + publisher_settings_properties); +} + +TEST(PublisherSettingsStateTest, FromJsonDeserialization) { + // Arrange + PublisherSettingsProperties publisher_settings_properties; + publisher_settings_properties.min_page_time_before_logging_a_visit = + std::numeric_limits::max(); + publisher_settings_properties.min_visits_for_publisher_relevancy = + std::numeric_limits::max(); + publisher_settings_properties.allow_non_verified_sites_in_list = true; + publisher_settings_properties.allow_contribution_to_videos = true; + + ReportBalanceProperties report_balance_properties; + report_balance_properties.opening_balance = "OpeningBalance"; + report_balance_properties.closing_balance = "ClosingBalance"; + report_balance_properties.deposits = "Deposits"; + report_balance_properties.grants = "Grants"; + report_balance_properties.ad_earnings = "AdEarnings"; + report_balance_properties.auto_contributions = "AutoContributions"; + report_balance_properties.recurring_donations = "RecurringDonations"; + report_balance_properties.one_time_donations = "OneTimeDonations"; + report_balance_properties.total = "Total"; + publisher_settings_properties.monthly_balances.insert({ + { "Date", report_balance_properties } + }); + + publisher_settings_properties.migrate_score_2 = true; + publisher_settings_properties.processed_pending_publishers.push_back( + "ProcessedPendingPublisher"); + + const std::string json = "{\"min_pubslisher_duration\":4294967295,\"min_visits\":4294967295,\"allow_non_verified\":true,\"allow_videos\":true,\"monthly_balances\":[{\"Date\":{\"opening_balance\":\"OpeningBalance\",\"closing_balance\":\"ClosingBalance\",\"deposits\":\"Deposits\",\"grants\":\"Grants\",\"earning_from_ads\":\"AdEarnings\",\"auto_contribute\":\"AutoContributions\",\"recurring_donation\":\"RecurringDonations\",\"one_time_donation\":\"OneTimeDonations\",\"total\":\"Total\"}}],\"migrate_score_2\":true,\"processed_pending_publishers\":[\"ProcessedPendingPublisher\"]}"; // NOLINT + + // Act + PublisherSettingsProperties expected_publisher_settings_properties; + const PublisherSettingsState publisher_settings_state; + publisher_settings_state.FromJson(json, + &expected_publisher_settings_properties); + + // Assert + EXPECT_EQ(expected_publisher_settings_properties, + publisher_settings_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.cc new file mode 100644 index 000000000000..e9ce8160a1ea --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.cc @@ -0,0 +1,206 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/publisher_state.h" +#include "bat/ledger/mojom_structs.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kDurationKey[] = "duration"; +const char kIdKey[] = "id"; +const char kPercentKey[] = "percent"; +const char kScoreKey[] = "score"; +const char kStatusKey[] = "status"; +const char kVerifiedKey[] = "verified"; +const char kVisitsKey[] = "visits"; +const char kWeightKey[] = "weight"; + +} // namespace + +PublisherState::PublisherState() = default; + +PublisherState::~PublisherState() = default; + +bool PublisherState::FromJson( + const std::string& json, + PublisherProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool PublisherState::FromDict( + const base::DictionaryValue* dictionary, + PublisherProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + PublisherProperties publisher_properties; + + // Id + const auto* id = dictionary->FindStringKey(kIdKey); + if (!id) { + NOTREACHED(); + return false; + } + publisher_properties.id = *id; + + // Duration (There is no support for uint64_t. Writing JSON with such types + // violates the spec. As we need a uint64_t, we need to use an unsigned int + // and cast to a uint64_t) + const auto duration = dictionary->FindDoubleKey(kDurationKey); + if (!duration) { + NOTREACHED(); + return false; + } + publisher_properties.duration = static_cast(*duration); + + // Score + auto score = dictionary->FindDoubleKey(kScoreKey); + if (!score) { + NOTREACHED(); + return false; + } + publisher_properties.score = *score; + + // Visits (There is no support for unsigned int. Writing JSON with such types + // violates the spec. As we need an unsigned int, we need to a double and cast + // to an unsigned int) + const auto visits = dictionary->FindDoubleKey(kVisitsKey); + if (!visits) { + NOTREACHED(); + return false; + } + publisher_properties.visits = static_cast(*visits); + + // Percent (There is no support for unsigned int. Writing JSON with such types + // violates the spec. As we need an unsigned int, we need to a double and cast + // to an unsigned int) + const auto percent = dictionary->FindDoubleKey(kPercentKey); + if (!percent) { + NOTREACHED(); + return false; + } + publisher_properties.percent = static_cast(*percent); + + // Weight + const auto weight = dictionary->FindDoubleKey(kWeightKey); + if (!weight) { + NOTREACHED(); + return false; + } + publisher_properties.weight = *weight; + + // Verified + const auto verified = dictionary->FindBoolKey(kVerifiedKey); + if (!verified) { + // Status (There is no support for unsigned int. Writing JSON with such + // types violates the spec. As we need an unsigned int, we need to a double + // and cast to an unsigned int) + const auto status = dictionary->FindDoubleKey(kStatusKey); + if (!status) { + NOTREACHED(); + return false; + } + + publisher_properties.status = static_cast(*status); + } else { + // Transition legacy verified flag to PublisherStatus enum + if (*verified) { + publisher_properties.status = static_cast( + PublisherStatus::VERIFIED); + } else { + publisher_properties.status = static_cast( + PublisherStatus::NOT_VERIFIED); + } + } + + *properties = publisher_properties; + + return true; +} + +bool PublisherState::ToJson( + JsonWriter* writer, + const PublisherProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kIdKey); + writer->String(properties.id.c_str()); + + writer->String(kDurationKey); + writer->Uint64(properties.duration); + + writer->String(kScoreKey); + writer->Double(properties.score); + + writer->String(kVisitsKey); + writer->Uint(properties.visits); + + writer->String(kPercentKey); + writer->Uint(properties.percent); + + writer->String(kWeightKey); + writer->Double(properties.weight); + + writer->String(kStatusKey); + writer->Uint(properties.status); + + writer->EndObject(); + + return true; +} + +std::string PublisherState::ToJson( + const PublisherProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.h new file mode 100644 index 000000000000..d74923821eee --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_PUBLISHER_STATE_H_ +#define BRAVELEDGER_STATE_PUBLISHER_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/publisher_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class PublisherState + : public state::Reader, + public state::Writer { + public: + PublisherState(); + ~PublisherState(); + + bool FromJson( + const std::string& json, + PublisherProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + PublisherProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const PublisherProperties& properties) const override; + + std::string ToJson( + const PublisherProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_PUBLISHER_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc new file mode 100644 index 000000000000..7ac6208f2d9a --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_state_unittest.cc @@ -0,0 +1,58 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/publisher_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PublisherStateTest.* + +namespace ledger { + +TEST(PublisherStateTest, ToJsonSerialization) { + // Arrange + PublisherProperties publisher_properties; + publisher_properties.id = "Id"; + publisher_properties.duration = std::numeric_limits::max(); + publisher_properties.score = std::numeric_limits::max(); + publisher_properties.visits = std::numeric_limits::max(); + publisher_properties.percent = std::numeric_limits::max(); + publisher_properties.weight = std::numeric_limits::max(); + publisher_properties.status = std::numeric_limits::max(); + + // Act + const PublisherState publisher_state; + const std::string json = publisher_state.ToJson(publisher_properties); + + // Assert + PublisherProperties expected_publisher_properties; + publisher_state.FromJson(json, &expected_publisher_properties); + EXPECT_EQ(expected_publisher_properties, publisher_properties); +} + +TEST(PublisherStateTest, FromJsonDeserialization) { + // Arrange + PublisherProperties publisher_properties; + publisher_properties.id = "Id"; + publisher_properties.duration = std::numeric_limits::max(); + publisher_properties.score = std::numeric_limits::max(); + publisher_properties.visits = std::numeric_limits::max(); + publisher_properties.percent = std::numeric_limits::max(); + publisher_properties.weight = std::numeric_limits::max(); + publisher_properties.status = std::numeric_limits::max(); + + const std::string json = "{\"id\":\"Id\",\"duration\":4294967295,\"score\":1.7976931348623157e308,\"visits\":4294967295,\"percent\":4294967295,\"weight\":1.7976931348623157e308,\"status\":4294967295}"; // NOLINT + + // Act + PublisherProperties expected_publisher_properties; + const PublisherState publisher_state; + publisher_state.FromJson(json, &expected_publisher_properties); + + // Assert + EXPECT_EQ(expected_publisher_properties, publisher_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.cc new file mode 100644 index 000000000000..5ea018923197 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.cc @@ -0,0 +1,139 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/publisher_vote_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kProofKey[] = "proof"; +const char kSurveyorIdKey[] = "surveyorId"; + +} // namespace + +PublisherVoteState::PublisherVoteState() = default; + +PublisherVoteState::~PublisherVoteState() = default; + +bool PublisherVoteState::FromJson( + const std::string& json, + PublisherVoteProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool PublisherVoteState::FromDict( + const base::DictionaryValue* dictionary, + PublisherVoteProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + PublisherVoteProperties vote_properties; + + // Surveyor Id + const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); + if (!surveyor_id) { + NOTREACHED(); + return false; + } + vote_properties.surveyor_id = *surveyor_id; + + // Proof + const auto* proof = dictionary->FindStringKey(kProofKey); + if (!proof) { + NOTREACHED(); + return false; + } + vote_properties.proof = *proof; + + *properties = vote_properties; + + return true; +} + +bool PublisherVoteState::ToJson( + JsonWriter* writer, + const PublisherVoteProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String("surveyorId"); + writer->String(properties.surveyor_id.c_str()); + + writer->String("proof"); + writer->String(properties.proof.c_str()); + + writer->EndObject(); + + return true; +} + +std::string PublisherVoteState::ToJson( + const PublisherVoteProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +std::string PublisherVoteState::ToJson( + const BatchVotes& batch_votes) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + writer.StartArray(); + for (const auto& batch_vote : batch_votes) { + if (!ToJson(&writer, batch_vote)) { + NOTREACHED(); + continue; + } + } + writer.EndArray(); + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.h new file mode 100644 index 000000000000..0d9e11e3a91e --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state.h @@ -0,0 +1,49 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_PUBLISHER_VOTE_STATE_H_ +#define BRAVELEDGER_STATE_PUBLISHER_VOTE_STATE_H_ + +#include +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/publisher_vote_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class PublisherVoteState + : public state::Reader, + public state::Writer { + public: + PublisherVoteState(); + ~PublisherVoteState(); + + bool FromJson( + const std::string& json, + PublisherVoteProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + PublisherVoteProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const PublisherVoteProperties& properties) const override; + + std::string ToJson( + const PublisherVoteProperties& properties) const override; + + std::string ToJson( + const BatchVotes& batch_votes) const; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_PUBLISHER_VOTE_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc new file mode 100644 index 000000000000..03c1e1d32a8b --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_vote_state_unittest.cc @@ -0,0 +1,46 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/publisher_vote_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=VoteStateTest.* + +namespace ledger { + +TEST(VoteStateTest, ToJsonSerialization) { + // Arrange + PublisherVoteProperties vote_properties; + vote_properties.surveyor_id = "SurveyorId"; + vote_properties.proof = "Proof"; + + // Act + const PublisherVoteState vote_state; + const std::string json = vote_state.ToJson(vote_properties); + + // Assert + PublisherVoteProperties expected_vote_properties; + vote_state.FromJson(json, &expected_vote_properties); + EXPECT_EQ(expected_vote_properties, vote_properties); +} + +TEST(VoteStateTest, FromJsonDeserialization) { + // Arrange + PublisherVoteProperties vote_properties; + vote_properties.surveyor_id = "SurveyorId"; + vote_properties.proof = "Proof"; + + const std::string json = "{\"surveyorId\":\"SurveyorId\",\"proof\":\"Proof\"}"; // NOLINT + + // Act + PublisherVoteProperties expected_vote_properties; + const PublisherVoteState vote_state; + vote_state.FromJson(json, &expected_vote_properties); + + // Assert + EXPECT_EQ(expected_vote_properties, vote_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.cc new file mode 100644 index 000000000000..e2635ff46ff6 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.cc @@ -0,0 +1,151 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/publisher_votes_state.h" +#include "bat/ledger/internal/state/publisher_vote_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kPublisherKey[] = "publisher"; +const char kBatchVotesKey[] = "batchVotesInfo"; + +} // namespace + +PublisherVotesState::PublisherVotesState() = default; + +PublisherVotesState::~PublisherVotesState() = default; + +bool PublisherVotesState::FromJson( + const std::string& json, + PublisherVotesProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool PublisherVotesState::FromDict( + const base::DictionaryValue* dictionary, + PublisherVotesProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + PublisherVotesProperties publisher_votes_properties; + + // Publisher + const auto* publisher = dictionary->FindStringKey(kPublisherKey); + if (!publisher) { + NOTREACHED(); + return false; + } + publisher_votes_properties.publisher = *publisher; + + // Batch Votes + const auto* batch_votes_list = dictionary->FindListKey(kBatchVotesKey); + if (!batch_votes_list) { + NOTREACHED(); + return false; + } + + const PublisherVoteState publisher_vote_state; + for (const auto& batch_votes_value : batch_votes_list->GetList()) { + if (!batch_votes_value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* batch_votes_dictionary = nullptr; + batch_votes_value.GetAsDictionary(&batch_votes_dictionary); + if (!batch_votes_dictionary) { + NOTREACHED(); + continue; + } + + PublisherVoteProperties publisher_vote_properties; + if (!publisher_vote_state.FromDict(batch_votes_dictionary, + &publisher_vote_properties)) { + continue; + } + + publisher_votes_properties.batch_votes.push_back( + publisher_vote_properties); + } + + *properties = publisher_votes_properties; + + return true; +} + +bool PublisherVotesState::ToJson( + JsonWriter* writer, + const PublisherVotesProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kPublisherKey); + writer->String(properties.publisher.c_str()); + + writer->String(kBatchVotesKey); + writer->StartArray(); + const PublisherVoteState publisher_vote_state; + for (const auto& batch_vote : properties.batch_votes) { + publisher_vote_state.ToJson(writer, batch_vote); + } + writer->EndArray(); + + writer->EndObject(); + + return true; +} + +std::string PublisherVotesState::ToJson( + const PublisherVotesProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.h new file mode 100644 index 000000000000..9a7750a47e14 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_PUBLISHER_VOTES_STATE_H_ +#define BRAVELEDGER_STATE_PUBLISHER_VOTES_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/publisher_votes_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class PublisherVotesState + : public state::Reader, + public state::Writer { + public: + PublisherVotesState(); + ~PublisherVotesState(); + + bool FromJson( + const std::string& json, + PublisherVotesProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + PublisherVotesProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const PublisherVotesProperties& properties) const override; + + std::string ToJson( + const PublisherVotesProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_PUBLISHER_VOTES_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc new file mode 100644 index 000000000000..ae4eb51968ba --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/publisher_votes_state_unittest.cc @@ -0,0 +1,56 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/publisher_votes_state.h" +#include "bat/ledger/internal/properties/transaction_ballot_properties.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PublisherVotesStateTest.* + +namespace ledger { + +TEST(PublisherVotesStateTest, ToJsonSerialization) { + // Arrange + PublisherVotesProperties publisher_votes_properties; + publisher_votes_properties.publisher = "Publisher"; + + PublisherVoteProperties publisher_vote_properties; + publisher_vote_properties.surveyor_id = "SurveyorId"; + publisher_vote_properties.proof = "Proof"; + publisher_votes_properties.batch_votes.push_back(publisher_vote_properties); + + // Act + const PublisherVotesState publisher_votes_state; + const std::string json = + publisher_votes_state.ToJson(publisher_votes_properties); + + // Assert + PublisherVotesProperties expected_publisher_votes_properties; + publisher_votes_state.FromJson(json, &expected_publisher_votes_properties); + EXPECT_EQ(expected_publisher_votes_properties, publisher_votes_properties); +} + +TEST(PublisherVotesStateTest, FromJsonDeserialization) { + // Arrange + PublisherVotesProperties publisher_votes_properties; + publisher_votes_properties.publisher = "Publisher"; + + PublisherVoteProperties publisher_vote_properties; + publisher_vote_properties.surveyor_id = "SurveyorId"; + publisher_vote_properties.proof = "Proof"; + publisher_votes_properties.batch_votes.push_back(publisher_vote_properties); + + const std::string json = "{\"publisher\":\"Publisher\",\"batchVotesInfo\":[{\"surveyorId\":\"SurveyorId\",\"proof\":\"Proof\"}]}"; // NOLINT + + // Act + PublisherVotesProperties expected_publisher_votes_properties; + const PublisherVotesState publisher_votes_state; + publisher_votes_state.FromJson(json, &expected_publisher_votes_properties); + + // Assert + EXPECT_EQ(expected_publisher_votes_properties, publisher_votes_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.cc new file mode 100644 index 000000000000..ae2d5f348eb2 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.cc @@ -0,0 +1,127 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/reconcile_direction_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAmountKey[] = "amount"; +const char kAmountPercentKey[] = "amount_percent"; +const char kPublisherKeyKey[] = "publisher_key"; + +} // namespace + +ReconcileDirectionState::ReconcileDirectionState() = default; + +ReconcileDirectionState::~ReconcileDirectionState() = default; + +bool ReconcileDirectionState::FromJson( + const std::string& json, + ReconcileDirectionProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool ReconcileDirectionState::FromDict( + const base::DictionaryValue* dictionary, + ReconcileDirectionProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + ReconcileDirectionProperties reconcile_direction_properties; + + // Publisher Key + const auto* publisher_key = dictionary->FindStringKey(kPublisherKeyKey); + if (!publisher_key) { + NOTREACHED(); + return false; + } + reconcile_direction_properties.publisher_key = *publisher_key; + + // Amount Percent + const auto amount_percent = dictionary->FindDoubleKey(kAmountPercentKey); + if (amount_percent) { + reconcile_direction_properties.amount_percent = *amount_percent; + } else { + const auto amount_percent = dictionary->FindDoubleKey(kAmountKey); + if (!amount_percent) { + NOTREACHED(); + return false; + } + } + + *properties = reconcile_direction_properties; + + return true; +} + +bool ReconcileDirectionState::ToJson( + JsonWriter* writer, + const ReconcileDirectionProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kAmountPercentKey); + writer->Double(properties.amount_percent); + + writer->String(kPublisherKeyKey); + writer->String(properties.publisher_key.c_str()); + + writer->EndObject(); + + return true; +} + +std::string ReconcileDirectionState::ToJson( + const ReconcileDirectionProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.h new file mode 100644 index 000000000000..54ee4ed5e3bc --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_RECONCILE_DIRECTION_STATE_H_ +#define BRAVELEDGER_STATE_RECONCILE_DIRECTION_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/reconcile_direction_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class ReconcileDirectionState + : public state::Reader, + public state::Writer { + public: + ReconcileDirectionState(); + ~ReconcileDirectionState(); + + bool FromJson( + const std::string& json, + ReconcileDirectionProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + ReconcileDirectionProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const ReconcileDirectionProperties& properties) const override; + + std::string ToJson( + const ReconcileDirectionProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_RECONCILE_DIRECTION_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc new file mode 100644 index 000000000000..0f24f67fb123 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_direction_state_unittest.cc @@ -0,0 +1,55 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/reconcile_direction_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=ReconcileDirectionStateTest.* + +namespace ledger { + +TEST(ReconcileDirectionStateTest, ToJsonSerialization) { + // Arrange + ReconcileDirectionProperties reconcile_direction_properties; + reconcile_direction_properties.publisher_key = "ViewingId"; + reconcile_direction_properties.amount_percent = + std::numeric_limits::max(); + + // Act + const ReconcileDirectionState reconcile_direction_state; + const std::string json = + reconcile_direction_state.ToJson(reconcile_direction_properties); + + // Assert + ReconcileDirectionProperties expected_reconcile_direction_properties; + reconcile_direction_state.FromJson(json, + &expected_reconcile_direction_properties); + EXPECT_EQ(expected_reconcile_direction_properties, + reconcile_direction_properties); +} + +TEST(ReconcileDirectionStateTest, FromJsonDeserialization) { + // Arrange + ReconcileDirectionProperties reconcile_direction_properties; + reconcile_direction_properties.publisher_key = "ViewingId"; + reconcile_direction_properties.amount_percent = + std::numeric_limits::max(); + + const std::string json = "{\"amount_percent\":1.7976931348623157e308,\"publisher_key\":\"ViewingId\"}"; // NOLINT + + // Act + ReconcileDirectionProperties expected_reconcile_direction_properties; + const ReconcileDirectionState reconcile_direction_state; + reconcile_direction_state.FromJson(json, + &expected_reconcile_direction_properties); + + // Assert + EXPECT_EQ(expected_reconcile_direction_properties, + reconcile_direction_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.cc new file mode 100644 index 000000000000..7fd220940546 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.cc @@ -0,0 +1,116 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/reconcile_request_state.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAmountKey[] = "amount"; +const char kBodyKey[] = "body"; +const char kCurrencyKey[] = "currency"; +const char kDenominationKey[] = "denomination"; +const char kDestinationKey[] = "destination"; +const char kDigestKey[] = "digest"; +const char kHeadersKey[] = "headers"; +const char kOctetsKey[] = "octets"; +const char kRequestTypeKey[] = "requestType"; +const char kSignatureKey[] = "signature"; +const char kSignedTxKey[] = "signedTx"; +const char kSurveyorIdKey[] = "surveyorId"; +const char kViewingIdKey[] = "viewingId"; + +} // namespace + +ReconcileRequestState::ReconcileRequestState() = default; + +ReconcileRequestState::~ReconcileRequestState() = default; + +bool ReconcileRequestState::ToJson( + JsonWriter* writer, + const ReconcileRequestProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + if (!properties.type.empty()) { + writer->String(kRequestTypeKey); + writer->String(properties.type.c_str()); + } + + writer->String(kSignedTxKey); + writer->StartObject(); + + writer->String(kHeadersKey); + writer->StartObject(); + + writer->String(kDigestKey); + writer->String(properties.signed_tx_headers_digest.c_str()); + + writer->String(kSignatureKey); + writer->String(properties.signed_tx_headers_signature.c_str()); + + writer->EndObject(); + + writer->String(kBodyKey); + writer->StartObject(); + + writer->String(kDenominationKey); + writer->StartObject(); + + writer->String(kAmountKey); + writer->String(properties.signed_tx_body.amount.c_str()); + + writer->String(kCurrencyKey); + writer->String(properties.signed_tx_body.currency.c_str()); + + writer->EndObject(); + + writer->String(kDestinationKey); + writer->String(properties.signed_tx_body.destination.c_str()); + + writer->EndObject(); + + writer->String(kOctetsKey); + writer->String(properties.signed_tx_octets.c_str()); + + writer->EndObject(); + + if (!properties.surveyor_id.empty()) { + writer->String(kSurveyorIdKey); + writer->String(properties.surveyor_id.c_str()); + } + + if (!properties.viewing_id.empty()) { + writer->String(kViewingIdKey); + writer->String(properties.viewing_id.c_str()); + } + + writer->EndObject(); + + return true; +} + +std::string ReconcileRequestState::ToJson( + const ReconcileRequestProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.h new file mode 100644 index 000000000000..8f8067baad12 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state.h @@ -0,0 +1,35 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_RECONCILE_REQUEST_STATE_H_ +#define BRAVELEDGER_STATE_RECONCILE_REQUEST_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/reconcile_request_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class ReconcileRequestState + : public state::Writer { + public: + ReconcileRequestState(); + ~ReconcileRequestState(); + + bool ToJson( + JsonWriter* writer, + const ReconcileRequestProperties& properties) const override; + + std::string ToJson( + const ReconcileRequestProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_RECONCILE_REQUEST_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc new file mode 100644 index 000000000000..f66bebabd27d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/reconcile_request_state_unittest.cc @@ -0,0 +1,43 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/reconcile_request_state.h" +#include "bat/ledger/internal/properties/unsigned_tx_properties.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=ReconcileRequestStateTest.* + +namespace ledger { + +TEST(ReconcileRequestStateTest, ToJsonSerialization) { + // Arrange + ReconcileRequestProperties reconcile_request_properties; + reconcile_request_properties.type = "RequestType"; + reconcile_request_properties.signed_tx_headers_digest = + "RequestSignedTxHeadersDigest"; + reconcile_request_properties.signed_tx_headers_signature = + "RequestSignedTxHeadersSignature"; + + UnsignedTxProperties unsigned_tx_properties; + unsigned_tx_properties.amount = "Amount"; + unsigned_tx_properties.currency = "Currency"; + unsigned_tx_properties.destination = "Destination"; + reconcile_request_properties.signed_tx_body = unsigned_tx_properties; + + reconcile_request_properties.signed_tx_octets = "RequestSignedTxOctets"; + reconcile_request_properties.viewing_id = "RequestViewingId"; + reconcile_request_properties.surveyor_id = "RequestSurveyorId"; + + // Act + const ReconcileRequestState reconcile_request_state; + const std::string json = + reconcile_request_state.ToJson(reconcile_request_properties); + + // Assert + const std::string expected_json = "{\"requestType\":\"RequestType\",\"signedTx\":{\"headers\":{\"digest\":\"RequestSignedTxHeadersDigest\",\"signature\":\"RequestSignedTxHeadersSignature\"},\"body\":{\"denomination\":{\"amount\":\"Amount\",\"currency\":\"Currency\"},\"destination\":\"Destination\"},\"octets\":\"RequestSignedTxOctets\"},\"surveyorId\":\"RequestSurveyorId\",\"viewingId\":\"RequestViewingId\"}"; // NOLINT + EXPECT_EQ(expected_json, json); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state.cc new file mode 100644 index 000000000000..c3c2952ad57d --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state.cc @@ -0,0 +1,209 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/report_balance_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAutoContributionsKey[] = "auto_contribute"; +const char kClosingBalanceKey[] = "closing_balance"; +const char kDepositsKey[] = "deposits"; +const char kAdEarningsKey[] = "earning_from_ads"; +const char kGrantsKey[] = "grants"; +const char kOneTimeDonationsKey[] = "one_time_donation"; +const char kOpeningBalanceKey[] = "opening_balance"; +const char kRecurringDonationsKey[] = "recurring_donation"; +const char kTotalKey[] = "total"; + +} // namespace + +ReportBalanceState::ReportBalanceState() = default; + +ReportBalanceState::~ReportBalanceState() = default; + +bool ReportBalanceState::FromJson( + const std::string& json, + ReportBalanceProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool ReportBalanceState::FromDict( + const base::DictionaryValue* dictionary, + ReportBalanceProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + ReportBalanceProperties report_balance_properties; + + // Opening Balance + const auto* opening_balance = dictionary->FindStringKey(kOpeningBalanceKey); + if (!opening_balance) { + NOTREACHED(); + return false; + } + report_balance_properties.opening_balance = *opening_balance; + + // Closing Balance + const auto* closing_balance = dictionary->FindStringKey(kClosingBalanceKey); + if (!closing_balance) { + NOTREACHED(); + return false; + } + report_balance_properties.closing_balance = *closing_balance; + + // Deposits + const auto* deposits = dictionary->FindStringKey(kDepositsKey); + if (!deposits) { + NOTREACHED(); + return false; + } + report_balance_properties.deposits = *deposits; + + // Grants + const auto* grants = dictionary->FindStringKey(kGrantsKey); + if (!grants) { + NOTREACHED(); + return false; + } + report_balance_properties.grants = *grants; + + // Earnings From Ads + const auto* ad_earnings = dictionary->FindStringKey(kAdEarningsKey); + if (!ad_earnings) { + NOTREACHED(); + return false; + } + report_balance_properties.ad_earnings = *ad_earnings; + + // Auto Contribute + const auto* auto_contributions = + dictionary->FindStringKey(kAutoContributionsKey); + if (!auto_contributions) { + NOTREACHED(); + return false; + } + report_balance_properties.auto_contributions = *auto_contributions; + + // Recurring Donation + const auto* recurring_donations = + dictionary->FindStringKey(kRecurringDonationsKey); + if (!recurring_donations) { + NOTREACHED(); + return false; + } + report_balance_properties.recurring_donations = *recurring_donations; + + // One Time Donation + const auto* one_time_donations = + dictionary->FindStringKey(kOneTimeDonationsKey); + if (!one_time_donations) { + NOTREACHED(); + return false; + } + report_balance_properties.one_time_donations = *one_time_donations; + + // Total + const auto* total = dictionary->FindStringKey(kTotalKey); + if (!total) { + NOTREACHED(); + return false; + } + report_balance_properties.total = *total; + + *properties = report_balance_properties; + + return true; +} + +bool ReportBalanceState::ToJson( + JsonWriter* writer, + const ReportBalanceProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kOpeningBalanceKey); + writer->String(properties.opening_balance.c_str()); + + writer->String(kClosingBalanceKey); + writer->String(properties.closing_balance.c_str()); + + writer->String(kDepositsKey); + writer->String(properties.deposits.c_str()); + + writer->String(kGrantsKey); + writer->String(properties.grants.c_str()); + + writer->String(kAdEarningsKey); + writer->String(properties.ad_earnings.c_str()); + + writer->String(kAutoContributionsKey); + writer->String(properties.auto_contributions.c_str()); + + writer->String(kRecurringDonationsKey); + writer->String(properties.recurring_donations.c_str()); + + writer->String(kOneTimeDonationsKey); + writer->String(properties.one_time_donations.c_str()); + + writer->String(kTotalKey); + writer->String(properties.total.c_str()); + + writer->EndObject(); + + return true; +} + +std::string ReportBalanceState::ToJson( + const ReportBalanceProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state.h new file mode 100644 index 000000000000..ecdf2aa0e6cb --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_REPORT_BALANCE_STATE_H_ +#define BRAVELEDGER_STATE_REPORT_BALANCE_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/report_balance_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class ReportBalanceState + : public state::Reader, + public state::Writer { + public: + ReportBalanceState(); + ~ReportBalanceState(); + + bool FromJson( + const std::string& json, + ReportBalanceProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + ReportBalanceProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const ReportBalanceProperties& state) const override; + + std::string ToJson( + const ReportBalanceProperties& state) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_REPORT_BALANCE_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state_unittest.cc new file mode 100644 index 000000000000..6a76a3ce01a5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/report_balance_state_unittest.cc @@ -0,0 +1,61 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/report_balance_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=ReportBalanceStateTest.* + +namespace ledger { + +TEST(ReportBalanceStateTest, ToJsonSerialization) { + // Arrange + ReportBalanceProperties report_balance_properties; + report_balance_properties.opening_balance = "OpeningBalance"; + report_balance_properties.closing_balance = "ClosingBalance"; + report_balance_properties.deposits = "Deposits"; + report_balance_properties.grants = "Grants"; + report_balance_properties.ad_earnings = "AdEarnings"; + report_balance_properties.auto_contributions = "AutoContributions"; + report_balance_properties.recurring_donations = "RecurringDonations"; + report_balance_properties.one_time_donations = "OneTimeDonations"; + report_balance_properties.total = "Total"; + + // Act + const ReportBalanceState report_balance_state; + const std::string json = + report_balance_state.ToJson(report_balance_properties); + + // Assert + ReportBalanceProperties expected_report_balance_properties; + report_balance_state.FromJson(json, &expected_report_balance_properties); + EXPECT_EQ(expected_report_balance_properties, report_balance_properties); +} + +TEST(ReportBalanceStateTest, FromJsonDeserialization) { + // Arrange + ReportBalanceProperties report_balance; + report_balance.opening_balance = "OpeningBalance"; + report_balance.closing_balance = "ClosingBalance"; + report_balance.deposits = "Deposits"; + report_balance.grants = "Grants"; + report_balance.ad_earnings = "AdEarnings"; + report_balance.auto_contributions = "AutoContributions"; + report_balance.recurring_donations = "RecurringDonations"; + report_balance.one_time_donations = "OneTimeDonations"; + report_balance.total = "Total"; + + const std::string json = "{\"opening_balance\":\"OpeningBalance\",\"closing_balance\":\"ClosingBalance\",\"deposits\":\"Deposits\",\"grants\":\"Grants\",\"earning_from_ads\":\"AdEarnings\",\"auto_contribute\":\"AutoContributions\",\"recurring_donation\":\"RecurringDonations\",\"one_time_donation\":\"OneTimeDonations\",\"total\":\"Total\"}"; // NOLINT + + // Act + ReportBalanceProperties expected_report_balance; + const ReportBalanceState report_balance_state; + report_balance_state.FromJson(json, &expected_report_balance); + + // Assert + EXPECT_EQ(expected_report_balance, report_balance); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_reader.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_reader.h new file mode 100644 index 000000000000..3f42d8cd826b --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_reader.h @@ -0,0 +1,31 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_READER_H_ +#define BRAVELEDGER_STATE_READER_H_ + +#include + +#include "base/values.h" + +namespace ledger { +namespace state { + +template +class Reader { + public: + virtual bool FromJson( + const std::string& json, + T*) const = 0; + + virtual bool FromDict( + const base::DictionaryValue* dictionary, + T*) const = 0; +}; + +} // namespace state +} // namespace ledger + +#endif // BRAVELEDGER_STATE_READER_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_writer.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_writer.h new file mode 100644 index 000000000000..4b0a64a249b7 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/state_writer.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_WRITER_H_ +#define BRAVELEDGER_STATE_WRITER_H_ + +#include + +namespace ledger { +namespace state { + +template +class Writer { + public: + virtual bool ToJson( + T writer, + const U&) const = 0; + + virtual std::string ToJson( + const U&) const = 0; +}; + +} // namespace state +} // namespace ledger + +#endif // BRAVELEDGER_STATE_WRITER_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.cc new file mode 100644 index 000000000000..e02eb96469a5 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.cc @@ -0,0 +1,156 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/surveyor_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kRegistrarVkKey[] = "registrarVK"; +const char kSignatureKey[] = "signature"; +const char kSurveyorIdKey[] = "surveyorId"; +const char kSurveySkKey[] = "surveySK"; +const char kSurveyVkKey[] = "surveyVK"; + +} // namespace + +SurveyorState::SurveyorState() = default; + +SurveyorState::~SurveyorState() = default; + +bool SurveyorState::FromJson( + const std::string& json, + SurveyorProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool SurveyorState::FromDict( + const base::DictionaryValue* dictionary, + SurveyorProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + SurveyorProperties surveyor_properties; + + // Signature + const auto* signature = dictionary->FindStringKey(kSignatureKey); + if (!signature) { + NOTREACHED(); + return false; + } + surveyor_properties.signature = *signature; + + // Surveyor Id + const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); + if (!surveyor_id) { + NOTREACHED(); + return false; + } + surveyor_properties.surveyor_id = *surveyor_id; + + // Survey VK + const auto* survey_vk = dictionary->FindStringKey(kSurveyVkKey); + if (!survey_vk) { + NOTREACHED(); + return false; + } + surveyor_properties.survey_vk = *survey_vk; + + // Registrar VK + const auto* registrar_vk = dictionary->FindStringKey(kRegistrarVkKey); + if (!registrar_vk) { + NOTREACHED(); + return false; + } + surveyor_properties.registrar_vk = *registrar_vk; + + // Survey SK + const auto* survey_sk = dictionary->FindStringKey(kSurveySkKey); + if (survey_sk) { + surveyor_properties.survey_sk = *survey_sk; + } + + *properties = surveyor_properties; + + return true; +} + +bool SurveyorState::ToJson( + JsonWriter* writer, + const SurveyorProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kRegistrarVkKey); + writer->String(properties.registrar_vk.c_str()); + + writer->String(kSignatureKey); + writer->String(properties.signature.c_str()); + + writer->String(kSurveyorIdKey); + writer->String(properties.surveyor_id.c_str()); + + writer->String(kSurveySkKey); + writer->String(properties.survey_sk.c_str()); + + writer->String(kSurveyVkKey); + writer->String(properties.survey_vk.c_str()); + + writer->EndObject(); + + return true; +} + +std::string SurveyorState::ToJson( + const SurveyorProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.h new file mode 100644 index 000000000000..63e84692669b --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_SURVEYOR_STATE_H_ +#define BRAVELEDGER_STATE_SURVEYOR_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/surveyor_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class SurveyorState + : public state::Reader, + public state::Writer { + public: + SurveyorState(); + ~SurveyorState(); + + bool FromJson( + const std::string& json, + SurveyorProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + SurveyorProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const SurveyorProperties& properties) const override; + + std::string ToJson( + const SurveyorProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_SURVEYOR_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc new file mode 100644 index 000000000000..3b2e97315f1f --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/surveyor_state_unittest.cc @@ -0,0 +1,52 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/surveyor_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=SurveyorStateTest.* + +namespace ledger { + +TEST(SurveyorStateTest, ToJsonSerialization) { + // Arrange + SurveyorProperties surveyor_properties; + surveyor_properties.signature = "Signature"; + surveyor_properties.surveyor_id = "SurveyorId"; + surveyor_properties.survey_vk = "SurveyVk"; + surveyor_properties.registrar_vk = "RegistrarVk"; + surveyor_properties.survey_sk = "SurveySk"; + + // Act + const SurveyorState surveyor_state; + const std::string json = surveyor_state.ToJson(surveyor_properties); + + // Assert + SurveyorProperties expected_surveyor_properties; + surveyor_state.FromJson(json, &expected_surveyor_properties); + EXPECT_EQ(expected_surveyor_properties, surveyor_properties); +} + +TEST(SurveyorStateTest, FromJsonDeserialization) { + // Arrange + SurveyorProperties surveyor_properties; + surveyor_properties.signature = "Signature"; + surveyor_properties.surveyor_id = "SurveyorId"; + surveyor_properties.survey_vk = "SurveyVk"; + surveyor_properties.registrar_vk = "RegistrarVk"; + surveyor_properties.survey_sk = "SurveySk"; + + const std::string json = "{\"registrarVK\":\"RegistrarVk\",\"signature\":\"Signature\",\"surveyorId\":\"SurveyorId\",\"surveySK\":\"SurveySk\",\"surveyVK\":\"SurveyVk\"}"; // NOLINT + + // Act + SurveyorProperties expected_surveyor_properties; + const SurveyorState surveyor_state; + surveyor_state.FromJson(json, &expected_surveyor_properties); + + // Assert + EXPECT_EQ(expected_surveyor_properties, surveyor_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.cc new file mode 100644 index 000000000000..35d7536cd645 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.cc @@ -0,0 +1,124 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/transaction_ballot_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kOffsetKey[] = "offset"; +const char kPublisherKey[] = "publisher"; + +} // namespace + +TransactionBallotState::TransactionBallotState() = default; + +TransactionBallotState::~TransactionBallotState() = default; + +bool TransactionBallotState::FromJson( + const std::string& json, + TransactionBallotProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool TransactionBallotState::FromDict( + const base::DictionaryValue* dictionary, + TransactionBallotProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + TransactionBallotProperties transaction_ballot_properties; + + // Publisher + const auto* publisher = dictionary->FindStringKey(kPublisherKey); + if (!publisher) { + NOTREACHED(); + return false; + } + transaction_ballot_properties.publisher = *publisher; + + // Offset (There is no support for unsigned int. Writing JSON with such types + // violates the spec. As we need an unsigned int, we need to a double and cast + // to an unsigned int) + const auto count = dictionary->FindDoubleKey(kOffsetKey); + if (!count) { + NOTREACHED(); + return false; + } + transaction_ballot_properties.count = static_cast(*count); + + *properties = transaction_ballot_properties; + + return true; +} + +bool TransactionBallotState::ToJson( + JsonWriter* writer, + const TransactionBallotProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kPublisherKey); + writer->String(properties.publisher.c_str()); + + writer->String(kOffsetKey); + writer->Uint(properties.count); + + writer->EndObject(); + + return true; +} + +std::string TransactionBallotState::ToJson( + const TransactionBallotProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.h new file mode 100644 index 000000000000..7ee76de03df1 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_TRANSACTION_BALLOT_STATE_H_ +#define BRAVELEDGER_STATE_TRANSACTION_BALLOT_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/transaction_ballot_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class TransactionBallotState + : public state::Reader, + public state::Writer { + public: + TransactionBallotState(); + ~TransactionBallotState(); + + bool FromJson( + const std::string& json, + TransactionBallotProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + TransactionBallotProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const TransactionBallotProperties& properties) const override; + + std::string ToJson( + const TransactionBallotProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_TRANSACTION_BALLOT_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc new file mode 100644 index 000000000000..25a77d938113 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_ballot_state_unittest.cc @@ -0,0 +1,55 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/transaction_ballot_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=TransactionBallotStateTest.* + +namespace ledger { + +TEST(TransactionBallotStateTest, ToJsonSerialization) { + // Arrange + TransactionBallotProperties transaction_ballot_properties; + transaction_ballot_properties.publisher = "Publisher"; + transaction_ballot_properties.count = + std::numeric_limits::max(); + + // Act + const TransactionBallotState transaction_ballot_state; + const std::string json = + transaction_ballot_state.ToJson(transaction_ballot_properties); + + // Assert + TransactionBallotProperties expected_transaction_ballot_properties; + transaction_ballot_state.FromJson(json, + &expected_transaction_ballot_properties); + EXPECT_EQ(expected_transaction_ballot_properties, + transaction_ballot_properties); +} + +TEST(TransactionBallotStateTest, FromJsonDeserialization) { + // Arrange + TransactionBallotProperties transaction_ballot_properties; + transaction_ballot_properties.publisher = "Publisher"; + transaction_ballot_properties.count = + std::numeric_limits::max(); + + const std::string json = "{\"publisher\":\"Publisher\",\"offset\":4294967295}"; // NOLINT + + // Act + TransactionBallotProperties expected_transaction_ballot_properties; + const TransactionBallotState transaction_ballot_state; + transaction_ballot_state.FromJson(json, + &expected_transaction_ballot_properties); + + // Assert + EXPECT_EQ(expected_transaction_ballot_properties, + transaction_ballot_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.cc new file mode 100644 index 000000000000..20115ad6d37c --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.cc @@ -0,0 +1,338 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/transaction_ballot_state.h" +#include "bat/ledger/internal/state/transaction_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAnonizeViewingIdKey[] = "anonizeViewingId"; +const char kBallotsKey[] = "ballots"; +const char kContributionProbiKey[] = "contribution_probi"; +const char kContributionRatesKey[] = "rates"; +const char kMasterUserTokenKey[] = "masterUserToken"; +const char kRegistrarVkKey[] = "registrarVK"; +const char kSubmissionTimestampKey[] = "submissionStamp"; +const char kSurveyorIdKey[] = "surveyorId"; +const char kSurveyorIdsKey[] = "surveyorIds"; +const char kViewingIdKey[] = "viewingId"; +const char kVoteCountKey[] = "votes"; + +} // namespace + +TransactionState::TransactionState() = default; + +TransactionState::~TransactionState() = default; + +bool TransactionState::FromJson( + const std::string& json, + TransactionProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool TransactionState::FromJsonResponse( + const std::string& json, + TransactionProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + TransactionProperties transaction_properties; + + // Contribution Probi + const auto* contribution_probi = + dictionary->FindStringKey(kContributionProbiKey); + if (!contribution_probi) { + NOTREACHED(); + return false; + } + transaction_properties.contribution_probi = *contribution_probi; + + // Submission Timestamp + const auto* submission_timestamp = + dictionary->FindStringKey(kSubmissionTimestampKey); + if (!submission_timestamp) { + NOTREACHED(); + return false; + } + transaction_properties.submission_timestamp = *submission_timestamp; + + *properties = transaction_properties; + + return true; +} + +bool TransactionState::FromDict( + const base::DictionaryValue* dictionary, + TransactionProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + TransactionProperties transaction; + + // Viewing Id + const auto* viewing_id = dictionary->FindStringKey(kViewingIdKey); + if (!viewing_id) { + NOTREACHED(); + return false; + } + transaction.viewing_id = *viewing_id; + + // Surveyor Id + const auto* surveyor_id = dictionary->FindStringKey(kSurveyorIdKey); + if (!surveyor_id) { + NOTREACHED(); + return false; + } + transaction.surveyor_id = *surveyor_id; + + // Contribution Rates + const auto* contributions_rates = + dictionary->FindDictKey(kContributionRatesKey); + if (!contributions_rates) { + NOTREACHED(); + return false; + } + + for (const auto& contribution_rate : contributions_rates->DictItems()) { + const std::string currency_code = contribution_rate.first; + + const auto& exchange_rate_value = contribution_rate.second; + const double exchange_rate = exchange_rate_value.GetDouble(); + + transaction.contribution_rates.insert( + {currency_code, exchange_rate}); + } + + // Contribution Probi + const auto* contribution_probi = + dictionary->FindStringKey(kContributionProbiKey); + if (!contribution_probi) { + NOTREACHED(); + return false; + } + transaction.contribution_probi = *contribution_probi; + + // Submission Timestamp + const auto* submission_timestamp = + dictionary->FindStringKey(kSubmissionTimestampKey); + if (!submission_timestamp) { + NOTREACHED(); + return false; + } + transaction.submission_timestamp = *submission_timestamp; + + // Anonize Viewing Id + const auto* anonize_viewing_id = + dictionary->FindStringKey(kAnonizeViewingIdKey); + if (!anonize_viewing_id) { + NOTREACHED(); + return false; + } + transaction.anonize_viewing_id = *anonize_viewing_id; + + // Registrar VK + const auto* registrar_vk = dictionary->FindStringKey(kRegistrarVkKey); + if (!registrar_vk) { + NOTREACHED(); + return false; + } + transaction.registrar_vk = *registrar_vk; + + // Master user token + const auto* master_user_token = + dictionary->FindStringKey(kMasterUserTokenKey); + if (!master_user_token) { + NOTREACHED(); + return false; + } + transaction.master_user_token = *master_user_token; + + // Surveyor Ids + const auto* surveyor_ids_list = dictionary->FindListKey(kSurveyorIdsKey); + if (!surveyor_ids_list) { + NOTREACHED(); + return false; + } + + for (const auto& surveyor_id_value : surveyor_ids_list->GetList()) { + if (!surveyor_id_value.is_string()) { + NOTREACHED(); + continue; + } + + const std::string surveyor_id = surveyor_id_value.GetString(); + + transaction.surveyor_ids.push_back(surveyor_id); + } + + // Votes (There is no support for unsigned int. Writing JSON with such types + // violates the spec. As we need an unsigned int, we need to a double and cast + // to an unsigned int) + const auto vote_count = dictionary->FindDoubleKey(kVoteCountKey); + if (!vote_count) { + NOTREACHED(); + return false; + } + transaction.vote_count = static_cast(*vote_count); + + // Ballots + const auto* ballots_list = dictionary->FindListKey(kBallotsKey); + if (!ballots_list) { + NOTREACHED(); + return false; + } + + const TransactionBallotState transaction_ballance_state; + for (const auto& ballot_value : ballots_list->GetList()) { + if (!ballot_value.is_dict()) { + NOTREACHED(); + continue; + } + + const base::DictionaryValue* ballot_dictionary = nullptr; + ballot_value.GetAsDictionary(&ballot_dictionary); + if (!ballot_dictionary) { + NOTREACHED(); + continue; + } + + TransactionBallotProperties transaction_ballot; + if (!transaction_ballance_state.FromDict(ballot_dictionary, + &transaction_ballot)) { + continue; + } + + transaction.transaction_ballots.push_back(transaction_ballot); + } + + *properties = transaction; + + return true; +} + +bool TransactionState::ToJson( + JsonWriter* writer, + const TransactionProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kViewingIdKey); + writer->String(properties.viewing_id.c_str()); + + writer->String(kSurveyorIdKey); + writer->String(properties.surveyor_id.c_str()); + + writer->String(kContributionRatesKey); + writer->StartObject(); + for (const auto& contribution_rate : properties.contribution_rates) { + writer->String(contribution_rate.first.c_str()); + writer->Double(contribution_rate.second); + } + writer->EndObject(); + + writer->String(kContributionProbiKey); + writer->String(properties.contribution_probi.c_str()); + + writer->String(kSubmissionTimestampKey); + writer->String(properties.submission_timestamp.c_str()); + + writer->String(kAnonizeViewingIdKey); + writer->String(properties.anonize_viewing_id.c_str()); + + writer->String(kRegistrarVkKey); + writer->String(properties.registrar_vk.c_str()); + + writer->String(kMasterUserTokenKey); + writer->String(properties.master_user_token.c_str()); + + writer->String(kSurveyorIdsKey); + writer->StartArray(); + for (const auto& surveyor_id : properties.surveyor_ids) { + writer->String(surveyor_id.c_str()); + } + writer->EndArray(); + + writer->String(kVoteCountKey); + writer->Uint(properties.vote_count); + + writer->String(kBallotsKey); + writer->StartArray(); + const TransactionBallotState transaction_ballot_state; + for (const auto& ballot : properties.transaction_ballots) { + transaction_ballot_state.ToJson(writer, ballot); + } + writer->EndArray(); + + writer->EndObject(); + + return true; +} + +std::string TransactionState::ToJson( + const TransactionProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.h new file mode 100644 index 000000000000..1e150e0358c2 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state.h @@ -0,0 +1,49 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_TRANSACTION_STATE_H_ +#define BRAVELEDGER_STATE_TRANSACTION_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/transaction_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class TransactionState + : public state::Reader, + public state::Writer { + public: + TransactionState(); + ~TransactionState(); + + bool FromJson( + const std::string& json, + TransactionProperties* properties) const override; + + bool FromJsonResponse( + const std::string& json, + TransactionProperties* properties) const; + + bool FromDict( + const base::DictionaryValue* dictionary, + TransactionProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const TransactionProperties& properties) const override; + + std::string ToJson( + const TransactionProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_TRANSACTION_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc new file mode 100644 index 000000000000..efbc065ffa68 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/transaction_state_unittest.cc @@ -0,0 +1,149 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/transaction_state.h" +#include "bat/ledger/internal/properties/transaction_ballot_properties.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=TransactionPropertiesTest.* + +namespace ledger { + +TEST(TransactionStateTest, ToJsonSerialization) { + // Arrange + TransactionProperties transaction_properties; + transaction_properties.viewing_id = "ViewingId"; + transaction_properties.surveyor_id = "SurveyorId"; + transaction_properties.contribution_probi = "ContributionProbi"; + transaction_properties.submission_timestamp = "SubmissionTimestamp"; + transaction_properties.anonize_viewing_id = "AnonizeViewingId"; + transaction_properties.registrar_vk = "RegistrarVk"; + transaction_properties.master_user_token = "MasterUserToken"; + transaction_properties.surveyor_ids = { "SurveyorId" }; + transaction_properties.vote_count = std::numeric_limits::max(); + transaction_properties.contribution_rates = { + { "BAT", 1.0 }, + { "ETH", 2.0 }, + { "LTC", 3.0 }, + { "BTC", 4.0 }, + { "USD", 5.0 }, + { "EUR", 6.0 } + }; + + TransactionBallotProperties transaction_ballot_properties; + transaction_ballot_properties.publisher = "Publisher"; + transaction_ballot_properties.count = + std::numeric_limits::max(); + transaction_properties.transaction_ballots.push_back( + transaction_ballot_properties); + + // Act + const TransactionState transaction_state; + const std::string json = transaction_state.ToJson(transaction_properties); + + // Assert + TransactionProperties expected_transaction_properties; + transaction_state.FromJson(json, &expected_transaction_properties); + EXPECT_EQ(expected_transaction_properties, transaction_properties); +} + +TEST(TransactionStateTest, FromJsonDeserialization) { + // Arrange + TransactionProperties transaction_properties; + transaction_properties.viewing_id = "ViewingId"; + transaction_properties.surveyor_id = "SurveyorId"; + transaction_properties.contribution_probi = "ContributionProbi"; + transaction_properties.submission_timestamp = "SubmissionTimestamp"; + transaction_properties.anonize_viewing_id = "AnonizeViewingId"; + transaction_properties.registrar_vk = "RegistrarVk"; + transaction_properties.master_user_token = "MasterUserToken"; + transaction_properties.surveyor_ids = { "SurveyorId" }; + transaction_properties.vote_count = std::numeric_limits::max(); + transaction_properties.contribution_rates = { + { "BAT", 1.0 }, + { "ETH", 2.0 }, + { "LTC", 3.0 }, + { "BTC", 4.0 }, + { "USD", 5.0 }, + { "EUR", 6.0 } + }; + + TransactionBallotProperties transaction_ballot_properties; + transaction_ballot_properties.publisher = "Publisher"; + transaction_ballot_properties.count = + std::numeric_limits::max(); + transaction_properties.transaction_ballots.push_back( + transaction_ballot_properties); + + const std::string json = "{\"viewingId\":\"ViewingId\",\"surveyorId\":\"SurveyorId\",\"rates\":{\"BAT\":1.0,\"BTC\":4.0,\"ETH\":2.0,\"EUR\":6.0,\"LTC\":3.0,\"USD\":5.0},\"contribution_probi\":\"ContributionProbi\",\"submissionStamp\":\"SubmissionTimestamp\",\"anonizeViewingId\":\"AnonizeViewingId\",\"registrarVK\":\"RegistrarVk\",\"masterUserToken\":\"MasterUserToken\",\"surveyorIds\":[\"SurveyorId\"],\"votes\":4294967295,\"ballots\":[{\"publisher\":\"Publisher\",\"offset\":4294967295}]}"; // NOLINT + + // Act + TransactionProperties expected_transaction_properties; + const TransactionState transaction_state; + transaction_state.FromJson(json, &expected_transaction_properties); + + // Assert + EXPECT_EQ(expected_transaction_properties, transaction_properties); +} + +TEST(TransactionStateTest, FromJsonResponseDeserialization) { + // Arrange + TransactionProperties transaction_properties; + transaction_properties.contribution_probi = "ContributionProbi"; + transaction_properties.submission_timestamp = "SubmissionTimestamp"; + + const std::string json = "{\"contribution_probi\":\"ContributionProbi\",\"submissionStamp\":\"SubmissionTimestamp\"}"; // NOLINT + + // Act + TransactionProperties expected_transaction_properties; + const TransactionState transaction_state; + transaction_state.FromJsonResponse(json, &expected_transaction_properties); + + // Assert + EXPECT_EQ(expected_transaction_properties, transaction_properties); +} + +TEST(TransactionStateTest, FromInvalidJsonResponseDeserialization) { + // Arrange + TransactionProperties transaction_properties; + transaction_properties.viewing_id = "ViewingId"; + transaction_properties.surveyor_id = "SurveyorId"; + transaction_properties.contribution_probi = "ContributionProbi"; + transaction_properties.submission_timestamp = "SubmissionTimestamp"; + transaction_properties.anonize_viewing_id = "AnonizeViewingId"; + transaction_properties.registrar_vk = "RegistrarVk"; + transaction_properties.master_user_token = "MasterUserToken"; + transaction_properties.surveyor_ids = { "SurveyorId" }; + transaction_properties.vote_count = std::numeric_limits::max(); + transaction_properties.contribution_rates = { + { "BAT", 1.0 }, + { "ETH", 2.0 }, + { "LTC", 3.0 }, + { "BTC", 4.0 }, + { "USD", 5.0 }, + { "EUR", 6.0 } + }; + + TransactionBallotProperties transaction_ballot_properties; + transaction_ballot_properties.publisher = "Publisher"; + transaction_ballot_properties.count = + std::numeric_limits::max(); + transaction_properties.transaction_ballots.push_back( + transaction_ballot_properties); + + const std::string json = "FOOBAR"; + + // Act + TransactionProperties expected_transaction_properties; + const TransactionState transaction_state; + transaction_state.FromJsonResponse(json, &expected_transaction_properties); + + // Assert + EXPECT_NE(expected_transaction_properties, transaction_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state.cc new file mode 100644 index 000000000000..7d72e2bea2d0 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state.cc @@ -0,0 +1,178 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/unsigned_tx_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kAmountKey[] = "amount"; +const char kCurrencyKey[] = "currency"; +const char kDenominationKey[] = "denomination"; +const char kDestinationKey[] = "destination"; +const char kUnsignedTxKey[] = "unsignedTx"; +const char kAmountPath[] = "denomination.amount"; +const char kCurrencyPath[] = "denomination.currency"; +const char kDestinationPath[] = "destination"; + +} // namespace + +UnsignedTxState::UnsignedTxState() = default; + +UnsignedTxState::~UnsignedTxState() = default; + +bool UnsignedTxState::FromJson( + const std::string& json, + UnsignedTxProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool UnsignedTxState::FromJsonResponse( + const std::string& json, + UnsignedTxProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + // Unsigned Tx + const auto* unsigned_tx_value = dictionary->FindKey(kUnsignedTxKey); + if (!unsigned_tx_value || !unsigned_tx_value->is_dict()) { + NOTREACHED(); + return false; + } + + const base::DictionaryValue* unsigned_tx_dictionary = nullptr; + unsigned_tx_value->GetAsDictionary(&unsigned_tx_dictionary); + if (!unsigned_tx_dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(unsigned_tx_dictionary, properties); +} + +bool UnsignedTxState::FromDict( + const base::DictionaryValue* dictionary, + UnsignedTxProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + UnsignedTxProperties unsigned_tx_properties; + + // Amount + const auto* amount = dictionary->FindStringPath(kAmountPath); + if (!amount) { + return false; + } + unsigned_tx_properties.amount = *amount; + + // Currency + const auto* currency = dictionary->FindStringPath(kCurrencyPath); + if (!currency) { + return false; + } + unsigned_tx_properties.currency = *currency; + + // Destination + const auto* destination = dictionary->FindStringPath(kDestinationPath); + if (!destination) { + return false; + } + unsigned_tx_properties.destination = *destination; + + *properties = unsigned_tx_properties; + + return true; +} + +bool UnsignedTxState::ToJson( + JsonWriter* writer, + const UnsignedTxProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kDenominationKey); + writer->StartObject(); + + writer->String(kAmountKey); + writer->String(properties.amount.c_str()); + + writer->String(kCurrencyKey); + writer->String(properties.currency.c_str()); + writer->EndObject(); + + writer->String(kDestinationKey); + writer->String(properties.destination.c_str()); + + writer->EndObject(); + + return true; +} + +std::string UnsignedTxState::ToJson( + const UnsignedTxProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state.h new file mode 100644 index 000000000000..e1f89d6edb33 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state.h @@ -0,0 +1,49 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_UNSIGNED_TX_STATE_H_ +#define BRAVELEDGER_STATE_UNSIGNED_TX_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/unsigned_tx_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class UnsignedTxState + : public state::Reader, + public state::Writer { + public: + UnsignedTxState(); + ~UnsignedTxState(); + + bool FromJson( + const std::string& json, + UnsignedTxProperties* properties) const override; + + bool FromJsonResponse( + const std::string& json, + UnsignedTxProperties* properties) const; + + bool FromDict( + const base::DictionaryValue* dictionary, + UnsignedTxProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const UnsignedTxProperties& properties) const override; + + std::string ToJson( + const UnsignedTxProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_UNSIGNED_TX_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state_unittest.cc new file mode 100644 index 000000000000..07583bdca351 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/unsigned_tx_state_unittest.cc @@ -0,0 +1,84 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/unsigned_tx_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=UnsignedTxStateTest.* + +namespace ledger { + +TEST(UnsignedTxStateTest, ToJsonSerialization) { + // Arrange + UnsignedTxProperties unsigned_tx_properties; + unsigned_tx_properties.amount = "Amount"; + unsigned_tx_properties.currency = "Currency"; + unsigned_tx_properties.destination = "Destination"; + + // Act + const UnsignedTxState unsigned_tx_state; + const std::string json = unsigned_tx_state.ToJson(unsigned_tx_properties); + + // Assert + UnsignedTxProperties expected_unsigned_tx_properties; + unsigned_tx_state.FromJson(json, &expected_unsigned_tx_properties); + EXPECT_EQ(expected_unsigned_tx_properties, unsigned_tx_properties); +} + +TEST(UnsignedTxStateTest, FromJsonDeserialization) { + // Arrange + UnsignedTxProperties unsigned_tx_properties; + unsigned_tx_properties.amount = "Amount"; + unsigned_tx_properties.currency = "Currency"; + unsigned_tx_properties.destination = "Destination"; + + const std::string json = "{\"denomination\":{\"amount\":\"Amount\",\"currency\":\"Currency\"},\"destination\":\"Destination\"}"; // NOLINT + + // Act + UnsignedTxProperties expected_unsigned_tx_properties; + const UnsignedTxState unsigned_tx_state; + unsigned_tx_state.FromJson(json, &expected_unsigned_tx_properties); + + // Assert + EXPECT_EQ(expected_unsigned_tx_properties, unsigned_tx_properties); +} + +TEST(UnsignedTxStateTest, FromJsonResponseDeserialization) { + // Arrange + UnsignedTxProperties unsigned_tx_properties; + unsigned_tx_properties.amount = "Amount"; + unsigned_tx_properties.currency = "Currency"; + unsigned_tx_properties.destination = "Destination"; + + const std::string json = "{\"unsignedTx\":{\"denomination\":{\"amount\":\"Amount\",\"currency\":\"Currency\"},\"destination\":\"Destination\"}}"; // NOLINT + + // Act + UnsignedTxProperties expected_unsigned_tx_properties; + const UnsignedTxState unsigned_tx_state; + unsigned_tx_state.FromJsonResponse(json, &expected_unsigned_tx_properties); + + // Assert + EXPECT_EQ(expected_unsigned_tx_properties, unsigned_tx_properties); +} + +TEST(UnsignedTxStateTest, FromInvalidJsonResponseDeserialization) { + // Arrange + UnsignedTxProperties unsigned_tx_properties; + unsigned_tx_properties.amount = "Amount"; + unsigned_tx_properties.currency = "Currency"; + unsigned_tx_properties.destination = "Destination"; + + const std::string json = "FOOBAR"; + + // Act + UnsignedTxProperties expected_unsigned_tx_properties; + const UnsignedTxState unsigned_tx_state; + unsigned_tx_state.FromJsonResponse(json, &expected_unsigned_tx_properties); + + // Assert + EXPECT_NE(expected_unsigned_tx_properties, unsigned_tx_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state.cc new file mode 100644 index 000000000000..f28e2e8efdd9 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state.cc @@ -0,0 +1,148 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/wallet_info_state.h" +#include "base/json/json_reader.h" +#include "base/base64.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kPaymentIdKey[] = "paymentId"; +const char kAddressCardIdKey[] = "addressCARD_ID"; +const char kKeyInfoSeedKey[] = "keyInfoSeed"; + +} // namespace + +WalletInfoState::WalletInfoState() = default; + +WalletInfoState::~WalletInfoState() = default; + +bool WalletInfoState::FromJson( + const std::string& json, + WalletInfoProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool WalletInfoState::FromDict( + const base::DictionaryValue* dictionary, + WalletInfoProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + WalletInfoProperties wallet_info_properties; + + // Payment Id + const auto* payment_id = dictionary->FindStringKey(kPaymentIdKey); + if (!payment_id) { + NOTREACHED(); + return false; + } + wallet_info_properties.payment_id = *payment_id; + + // Address Card Id + const auto* address_card_id = dictionary->FindStringKey(kAddressCardIdKey); + if (!address_card_id) { + NOTREACHED(); + return false; + } + wallet_info_properties.address_card_id = *address_card_id; + + // Key Info Seed (Base64) + const auto* base64_key_info_seed = dictionary->FindStringKey(kKeyInfoSeedKey); + if (!base64_key_info_seed) { + NOTREACHED(); + return false; + } + + std::string key_info_seed; + if (!base::Base64Decode(*base64_key_info_seed, &key_info_seed)) { + NOTREACHED(); + return false; + } + wallet_info_properties.key_info_seed.assign(key_info_seed.begin(), + key_info_seed.end()); + + *properties = wallet_info_properties; + + return true; +} + +bool WalletInfoState::ToJson( + JsonWriter* writer, + const WalletInfoProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kPaymentIdKey); + writer->String(properties.payment_id.c_str()); + + writer->String(kAddressCardIdKey); + writer->String(properties.address_card_id.c_str()); + + writer->String(kKeyInfoSeedKey); + if (!properties.key_info_seed.empty()) { + const std::string base64_encoded_key_info_seed = + base::Base64Encode(properties.key_info_seed); + writer->String(base64_encoded_key_info_seed.c_str()); + } else { + writer->String(""); + } + + writer->EndObject(); + + return true; +} + +std::string WalletInfoState::ToJson( + const WalletInfoProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state.h new file mode 100644 index 000000000000..34da36b6b975 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_WALLET_INFO_STATE_H_ +#define BRAVELEDGER_STATE_WALLET_INFO_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class WalletInfoState + : public state::Reader, + public state::Writer { + public: + WalletInfoState(); + ~WalletInfoState(); + + bool FromJson( + const std::string& json, + WalletInfoProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + WalletInfoProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const WalletInfoProperties& properties) const override; + + std::string ToJson( + const WalletInfoProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_WALLET_INFO_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state_unittest.cc new file mode 100644 index 000000000000..0822b617ae4a --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_info_state_unittest.cc @@ -0,0 +1,61 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/wallet_info_state.h" +#include "base/base64.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=WalletInfoStateTest.* + +namespace ledger { + +TEST(WalletInfoStateTest, ToJsonSerialization) { + // Arrange + WalletInfoProperties wallet_info_properties; + wallet_info_properties.payment_id = "PaymentId"; + wallet_info_properties.address_card_id = "AddressCardId"; + + std::string key_info_seed; + std::string base64_key_info_seed = + "/kBv0C7wS4EBY3EIa780pYLrhryP3IWCfElIehufOFw="; + ASSERT_TRUE(base::Base64Decode(base64_key_info_seed, &key_info_seed)); + wallet_info_properties.key_info_seed.assign(key_info_seed.begin(), + key_info_seed.end()); + + // Act + const WalletInfoState wallet_info_state; + const std::string json = wallet_info_state.ToJson(wallet_info_properties); + + // Assert + WalletInfoProperties expected_wallet_info_properties; + wallet_info_state.FromJson(json, &expected_wallet_info_properties); + EXPECT_EQ(expected_wallet_info_properties, wallet_info_properties); +} + +TEST(WalletInfoStateTest, FromJsonDeserialization) { + // Arrange + WalletInfoProperties wallet_info_properties; + wallet_info_properties.payment_id = "PaymentId"; + wallet_info_properties.address_card_id = "AddressCardId"; + + std::string key_info_seed; + std::string base64_key_info_seed = + "/kBv0C7wS4EBY3EIa780pYLrhryP3IWCfElIehufOFw="; + ASSERT_TRUE(base::Base64Decode(base64_key_info_seed, &key_info_seed)); + wallet_info_properties.key_info_seed.assign(key_info_seed.begin(), + key_info_seed.end()); + + const std::string json = "{\"paymentId\":\"PaymentId\",\"addressCARD_ID\":\"AddressCardId\",\"keyInfoSeed\":\"/kBv0C7wS4EBY3EIa780pYLrhryP3IWCfElIehufOFw=\"}"; // NOLINT + + // Act + WalletInfoProperties expected_wallet_info_properties; + const WalletInfoState wallet_info_state; + wallet_info_state.FromJson(json, &expected_wallet_info_properties); + + // Assert + EXPECT_EQ(expected_wallet_info_properties, wallet_info_properties); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.cc new file mode 100644 index 000000000000..c8132919918b --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.cc @@ -0,0 +1,153 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "bat/ledger/internal/state/wallet_state.h" +#include "base/json/json_reader.h" +#include "base/logging.h" + +namespace ledger { + +namespace { + +// Do not change these values as they are required to transition legacy state +const char kFeeAmountKey[] = "fee_amount"; +const char kParametersKey[] = "parameters"; +const char kAdFreeKey[] = "adFree"; +const char kFeeKey[] = "fee"; +const char kBatKey[] = "BAT"; +const char kChoicesKey[] = "choices"; +const char kChoicesBatPath[] = "parameters.adFree.choices.BAT"; +const char kFeeBatPath[] = "parameters.adFree.fee.BAT"; + +} // namespace + +WalletState::WalletState() = default; + +WalletState::~WalletState() = default; + +bool WalletState::FromJson( + const std::string& json, + WalletProperties* properties) const { + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + auto json_value = base::JSONReader::Read(json); + if (!json_value) { + NOTREACHED(); + return false; + } + + base::DictionaryValue* dictionary = nullptr; + json_value->GetAsDictionary(&dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + return FromDict(dictionary, properties); +} + +bool WalletState::FromDict( + const base::DictionaryValue* dictionary, + WalletProperties* properties) const { + DCHECK(dictionary); + if (!dictionary) { + NOTREACHED(); + return false; + } + + DCHECK(properties); + if (!properties) { + NOTREACHED(); + return false; + } + + WalletProperties wallet_properties; + + // Fee Amount + const auto fee_amount = dictionary->FindDoublePath(kFeeBatPath); + if (!fee_amount) { + NOTREACHED(); + return false; + } + wallet_properties.fee_amount = *fee_amount; + + // Choices BAT + const auto* choices_bat_list = dictionary->FindListPath(kChoicesBatPath); + if (!choices_bat_list) { + NOTREACHED(); + return false; + } + + for (const auto&choices_bat_value : choices_bat_list->GetList()) { + const double bat = choices_bat_value.GetDouble(); + wallet_properties.parameters_choices.push_back(bat); + } + + *properties = wallet_properties; + + return true; +} + +bool WalletState::ToJson( + JsonWriter* writer, + const WalletProperties& properties) const { + DCHECK(writer); + if (!writer) { + NOTREACHED(); + return false; + } + + writer->StartObject(); + + writer->String(kFeeAmountKey); + writer->Double(properties.fee_amount); + + writer->String(kParametersKey); + writer->StartObject(); + writer->String(kAdFreeKey); + writer->StartObject(); + + writer->String(kFeeKey); + writer->StartObject(); + writer->String(kBatKey); + writer->Double(properties.fee_amount); + writer->EndObject(); + + writer->String(kChoicesKey); + writer->StartObject(); + writer->String(kBatKey); + + writer->StartArray(); + for (const auto& parameters_choice : properties.parameters_choices) { + writer->Double(parameters_choice); + } + writer->EndArray(); + writer->EndObject(); + + writer->EndObject(); + writer->EndObject(); + writer->EndObject(); + + return true; +} + +std::string WalletState::ToJson( + const WalletProperties& properties) const { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + + if (!ToJson(&writer, properties)) { + NOTREACHED(); + return ""; + } + + return buffer.GetString(); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.h b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.h new file mode 100644 index 000000000000..3940186cb300 --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVELEDGER_STATE_WALLET_STATE_H_ +#define BRAVELEDGER_STATE_WALLET_STATE_H_ + +#include + +#include "bat/ledger/internal/state/state_reader.h" +#include "bat/ledger/internal/state/state_writer.h" +#include "bat/ledger/mojom_structs.h" +#include "rapidjson/writer.h" + +namespace ledger { + +using JsonWriter = rapidjson::Writer; + +class WalletState + : public state::Reader, + public state::Writer { + public: + WalletState(); + ~WalletState(); + + bool FromJson( + const std::string& json, + WalletProperties* properties) const override; + + bool FromDict( + const base::DictionaryValue* dictionary, + WalletProperties* properties) const override; + + bool ToJson( + JsonWriter* writer, + const WalletProperties& properties) const override; + + std::string ToJson( + const WalletProperties& properties) const override; +}; + +} // namespace ledger + +#endif // BRAVELEDGER_STATE_WALLET_STATE_H_ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state_unittest.cc new file mode 100644 index 000000000000..3481c90cf7ad --- /dev/null +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/state/wallet_state_unittest.cc @@ -0,0 +1,64 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "bat/ledger/internal/state/wallet_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=WalletStateTest.* + +namespace ledger { + +TEST(WalletStateTest, ToJsonSerialization) { + // Arrange + WalletProperties wallet_properties; + wallet_properties.fee_amount = std::numeric_limits::max(); + wallet_properties.parameters_choices = { + 5.0, + 10.0, + 15.0, + 20.0, + 25.0, + 50.0, + 100.0 + }; + + // Act + const WalletState wallet_state; + std::string json = wallet_state.ToJson(wallet_properties); + + // Assert + WalletProperties expected_wallet_properties; + wallet_state.FromJson(json, &expected_wallet_properties); + EXPECT_TRUE(expected_wallet_properties.Equals(wallet_properties)); +} + +TEST(WalletStateTest, FromJsonDeserialization) { + // Arrange + WalletProperties wallet_properties; + wallet_properties.fee_amount = std::numeric_limits::max(); + wallet_properties.parameters_choices = { + 5.0, + 10.0, + 15.0, + 20.0, + 25.0, + 50.0, + 100.0 + }; + + const std::string json = "{\"fee_amount\":1.7976931348623157e308,\"parameters\":{\"adFree\":{\"fee\":{\"BAT\":1.7976931348623157e308},\"choices\":{\"BAT\":[5.0,10.0,15.0,20.0,25.0,50.0,100.0]}}}}"; // NOLINT + + // Act + WalletProperties expected_wallet_properties; + const WalletState wallet_state; + wallet_state.FromJson(json, &expected_wallet_properties); + + // Assert + EXPECT_TRUE(expected_wallet_properties.Equals(wallet_properties)); +} + +} // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h b/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h index c5c81f65df84..1b7f20697661 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/static_values.h @@ -131,7 +131,7 @@ static const uint8_t g_hkdfSalt[] = { static const double _d = 1.0 / (30.0 * 1000.0); -static const uint64_t _default_min_publisher_duration = 8; // In seconds +static const uint64_t _default_min_page_time_before_logging_a_visit = 8; static const uint64_t _milliseconds_day = 24 * 60 * 60 * 1000; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/uphold/uphold.cc index 32655f28ce27..5dda8cedfa20 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 @@ -97,9 +97,9 @@ void Uphold::ContributionCompleted( ledger_->ReconcileComplete( result, - reconcile.fee_, + reconcile.fee, viewing_id, - reconcile.type_); + reconcile.type); } void Uphold::FetchBalance( diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc index 5aeec871b02e..0f352880204b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/balance.cc @@ -12,11 +12,10 @@ #include "base/json/json_reader.h" #include "bat/ledger/global_constants.h" -#include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" #include "bat/ledger/internal/uphold/uphold.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" #include "bat/ledger/internal/request/request_util.h" +#include "bat/ledger/internal/static_values.h" #include "net/http/http_status_code.h" using std::placeholders::_1; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc index 693f6f1f9d3d..ddb29584a0a4 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.cc @@ -10,7 +10,7 @@ #include "base/json/json_writer.h" #include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/internal/request/request_util.h" #include "net/http/http_status_code.h" @@ -198,10 +198,10 @@ void Create::RequestCredentialsCallback( return; } - braveledger_bat_helper::WALLET_INFO_ST wallet_info; + ledger::WalletInfoProperties wallet_info; std::vector key_info_seed = braveledger_bat_helper::generateSeed(); - wallet_info.keyInfoSeed_ = key_info_seed; + wallet_info.key_info_seed = key_info_seed; ledger_->SetWalletInfo(wallet_info); std::vector secretKey = braveledger_bat_helper::getHKDF(key_info_seed); @@ -294,7 +294,7 @@ void Create::RegisterPersonaCallback( return; } - braveledger_bat_helper::WALLET_INFO_ST wallet_info = ledger_->GetWalletInfo(); + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); unsigned int days; double fee_amount = .0; std::string currency; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.h index 3c0f80a756bc..9d890562a5f3 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/create.h @@ -14,7 +14,6 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" namespace bat_ledger { class LedgerImpl; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc index 5864d5647a17..4a1d895290ec 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.cc @@ -8,7 +8,7 @@ #include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/internal/request/request_util.h" #include "net/http/http_status_code.h" @@ -164,9 +164,8 @@ void Recover::RecoverWalletCallback( return; } - braveledger_bat_helper::WALLET_INFO_ST wallet_info = ledger_->GetWalletInfo(); - braveledger_bat_helper::WALLET_PROPERTIES_ST properties = - ledger_->GetWalletProperties(); + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); + ledger::WalletProperties properties = ledger_->GetWalletProperties(); unsigned int days; double fee_amount = .0; double balance = .0; @@ -187,8 +186,8 @@ void Recover::RecoverWalletCallback( ledger_->SetDays(days); ledger_->SetWalletProperties(&properties); - wallet_info.paymentId_ = recoveryId; - wallet_info.keyInfoSeed_ = new_seed; + wallet_info.payment_id = recoveryId; + wallet_info.key_info_seed = new_seed; ledger_->SetWalletInfo(wallet_info); callback(ledger::Result::LEDGER_OK, balance); } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.h index 97bd8e47523d..db5c28992ede 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/recover.h @@ -14,7 +14,6 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" namespace bat_ledger { class LedgerImpl; 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 62d6ba34b0df..cef3200c00a8 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 @@ -12,8 +12,11 @@ #include "bat/ledger/global_constants.h" #include "bat/ledger/internal/bat_helper.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" +#include "bat/ledger/internal/properties/unsigned_tx_properties.h" +#include "bat/ledger/internal/properties/wallet_info_properties.h" #include "bat/ledger/internal/state_keys.h" +#include "bat/ledger/internal/state/wallet_state.h" +#include "bat/ledger/internal/state/unsigned_tx_state.h" #include "bat/ledger/internal/request/request_util.h" #include "bat/ledger/internal/wallet/balance.h" #include "bat/ledger/internal/wallet/create.h" @@ -67,7 +70,7 @@ void Wallet::GetWalletProperties( std::string passphrase = GetWalletPassphrase(); if (payment_id.empty() || passphrase.empty()) { - braveledger_bat_helper::WALLET_PROPERTIES_ST properties; + ledger::WalletProperties properties; callback(ledger::Result::CORRUPTED_WALLET, WalletPropertiesToWalletInfo(properties)); return; @@ -95,9 +98,9 @@ void Wallet::GetWalletProperties( } ledger::WalletPropertiesPtr Wallet::WalletPropertiesToWalletInfo( - const braveledger_bat_helper::WALLET_PROPERTIES_ST& properties) { + const ledger::WalletProperties& properties) { ledger::WalletPropertiesPtr wallet = ledger::WalletProperties::New(); - wallet->parameters_choices = properties.parameters_choices_; + wallet->parameters_choices = properties.parameters_choices; wallet->fee_amount = ledger_->GetContributionAmount(); return wallet; } @@ -107,7 +110,7 @@ void Wallet::WalletPropertiesCallback( const std::string& response, const std::map& headers, ledger::OnWalletPropertiesCallback callback) { - braveledger_bat_helper::WALLET_PROPERTIES_ST properties; + ledger::WalletProperties properties; ledger_->LogResponse(__func__, response_status_code, response, headers); if (response_status_code != net::HTTP_OK) { callback(ledger::Result::LEDGER_ERROR, @@ -117,7 +120,8 @@ void Wallet::WalletPropertiesCallback( ledger::WalletPropertiesPtr wallet; - bool ok = braveledger_bat_helper::loadFromJson(&properties, response); + const ledger::WalletState wallet_state; + bool ok = wallet_state.FromJson(response, &properties); if (!ok) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << @@ -133,16 +137,16 @@ void Wallet::WalletPropertiesCallback( } std::string Wallet::GetWalletPassphrase() const { - braveledger_bat_helper::WALLET_INFO_ST wallet_info = ledger_->GetWalletInfo(); + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); std::string passPhrase; - if (wallet_info.keyInfoSeed_.size() == 0) { + if (wallet_info.key_info_seed.size() == 0) { return passPhrase; } char* words = nullptr; int result = bip39_mnemonic_from_bytes(nullptr, - &wallet_info.keyInfoSeed_.front(), - wallet_info.keyInfoSeed_.size(), + &wallet_info.key_info_seed.front(), + wallet_info.key_info_seed.size(), &words); if (result != 0) { DCHECK(false); @@ -329,14 +333,14 @@ std::string Wallet::GetClaimPayload( const std::string user_funds, const std::string new_address, const std::string anon_address) { - braveledger_bat_helper::WALLET_INFO_ST wallet_info = ledger_->GetWalletInfo(); + ledger::WalletInfoProperties wallet_info = ledger_->GetWalletInfo(); - braveledger_bat_helper::UNSIGNED_TX unsigned_tx; - unsigned_tx.amount_ = user_funds; - unsigned_tx.currency_ = "BAT"; - unsigned_tx.destination_ = new_address; - const std::string octets = - braveledger_bat_helper::stringifyUnsignedTx(unsigned_tx); + ledger::UnsignedTxProperties unsigned_tx; + unsigned_tx.amount = user_funds; + unsigned_tx.currency = "BAT"; + unsigned_tx.destination = new_address; + const ledger::UnsignedTxState unsigned_tx_state; + const std::string octets = unsigned_tx_state.ToJson(unsigned_tx); std::string header_digest = "SHA-256=" + braveledger_bat_helper::getBase64( @@ -348,7 +352,7 @@ std::string Wallet::GetClaimPayload( header_values.push_back(header_digest); std::vector secret_key = braveledger_bat_helper::getHKDF( - wallet_info.keyInfoSeed_); + wallet_info.key_info_seed); std::vector public_key; std::vector new_secret_key; bool success = braveledger_bat_helper::getPublicKeyFromSeed( 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 0a13d4be7788..1717e2ea4dbc 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 @@ -14,7 +14,6 @@ #include #include "bat/ledger/ledger.h" -#include "bat/ledger/internal/bat_helper.h" namespace bat_ledger { class LedgerImpl; @@ -56,7 +55,7 @@ class Wallet { void GetWalletProperties(ledger::OnWalletPropertiesCallback callback); ledger::WalletPropertiesPtr WalletPropertiesToWalletInfo( - const braveledger_bat_helper::WALLET_PROPERTIES_ST& properties); + const ledger::WalletProperties& properties); void FetchBalance(ledger::FetchBalanceCallback callback); diff --git a/vendor/bat-native-ledger/src/bat/ledger/ledger.cc b/vendor/bat-native-ledger/src/bat/ledger/ledger.cc index ab5a2c5e96ee..d3926b9e9fa0 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/ledger.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/ledger.cc @@ -5,11 +5,8 @@ #include "bat/ledger/internal/media/media.h" #include "bat/ledger/internal/ledger_impl.h" -#include "bat/ledger/internal/rapidjson_bat_helper.h" +#include "bat/ledger/internal/static_values.h" #include "bat/ledger/ledger.h" -#include "rapidjson/document.h" -#include "rapidjson/stringbuffer.h" -#include "rapidjson/writer.h" namespace ledger {