Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Fix #1654, Fix #1656, Fix #1861: Add support for claiming virtual grants
Browse files Browse the repository at this point in the history
  • Loading branch information
kylehickinson committed Nov 4, 2019
1 parent ba35ce2 commit f7144ed
Show file tree
Hide file tree
Showing 18 changed files with 301 additions and 83 deletions.
Binary file modified BraveRewards/BraveRewards.framework/BraveRewards
Binary file not shown.
22 changes: 10 additions & 12 deletions BraveRewards/BraveRewards.framework/Headers/BATBraveLedger.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#import "ledger.mojom.objc.h"
#import "BATRewardsNotification.h"
#import "BATBraveLedgerObserver.h"
#import "BATPromotionSolution.h"

@class BATBraveAds;

Expand Down Expand Up @@ -166,23 +167,20 @@ NS_SWIFT_NAME(BraveLedger)
completion:(void (^)(BATResult result))completion;


#pragma mark - Grants
#pragma mark - Promotions

@property (nonatomic, readonly) NSArray<BATGrant *> *pendingGrants;
@property (nonatomic, readonly) NSArray<BATPromotion *> *pendingPromotions;

- (void)fetchAvailableGrantsForLanguage:(NSString *)language
paymentId:(NSString *)paymentId;
@property (nonatomic, readonly) NSArray<BATPromotion *> *finishedPromotions;

- (void)fetchAvailableGrantsForLanguage:(NSString *)language
paymentId:(NSString *)paymentId
completion:(nullable void (^)(NSArray<BATGrant *> *grants))completion;
- (void)fetchPromotions:(nullable void (^)(NSArray<BATPromotion *> *grants))completion;

- (void)grantCaptchaForPromotionId:(NSString *)promoID
promotionType:(NSString *)promotionType
completion:(void (^)(NSString *image, NSString *hint))completion;
- (void)claimPromotion:(NSString *)deviceCheckPublicKey
completion:(void (^)(BATResult result, NSString * _Nonnull json))completion;

- (void)solveGrantCaptchWithPromotionId:(NSString *)promotionId
solution:(NSString *)solution;
- (void)attestPromotion:(NSString *)promotionId
solution:(BATPromotionSolution *)solution
completion:(nullable void (^)(BATResult result, BATPromotion * _Nullable promotion))completion;

#pragma mark - History

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@ NS_SWIFT_NAME(LedgerObserver)

@property (nonatomic, copy, nullable) void (^publisherListUpdated)();

///
@property (nonatomic, copy, nullable) void (^finishedPromotionsAdded)(NSArray<BATPromotion *> *promotions);

/// Eligable grants were added to the wallet
@property (nonatomic, copy, nullable) void (^grantsAdded)(NSArray<BATGrant *> *grants);
@property (nonatomic, copy, nullable) void (^promotionsAdded)(NSArray<BATPromotion *> *promotions);

/// A grant was claimed
@property (nonatomic, copy, nullable) void (^grantClaimed)(BATGrant *grant);
@property (nonatomic, copy, nullable) void (^promotionClaimed)(BATPromotion *promotion);

/// A reconcile transaction completed and the user may have an updated balance
/// and likely an updated balance report
Expand Down
23 changes: 23 additions & 0 deletions BraveRewards/BraveRewards.framework/Headers/BATPromotionSolution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

/// The solution to claiming a promotion on iOS. Obtain the `noonce` through
/// `[BATBraveLedger claimPromotion:completion:]` method, and obtain the
/// blob and signature from the users keychain
NS_SWIFT_NAME(PromotionSolution)
@interface BATPromotionSolution : NSObject

@property (nonatomic, copy) NSString *noonce;
@property (nonatomic, copy) NSString *blob;
@property (nonatomic, copy) NSString *signature;

- (NSString *)JSONPayload;

@end

NS_ASSUME_NONNULL_END
1 change: 1 addition & 0 deletions BraveRewards/BraveRewards.framework/Headers/BraveRewards.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ FOUNDATION_EXPORT const unsigned char BraveRewardsVersionString[];
#import <BraveRewards/Records.h>
#import <BraveRewards/ledger.mojom.objc.h>
#import <BraveRewards/BATRewardsNotification.h>
#import <BraveRewards/BATPromotionSolution.h>
84 changes: 71 additions & 13 deletions BraveRewards/BraveRewards.framework/Headers/ledger.mojom.objc.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,10 @@ typedef NS_ENUM(NSInteger, BATResult) {
BATResultRegistrationVerificationFailed = 10,
BATResultBadRegistrationResponse = 11,
BATResultWalletCreated = 12,
BATResultGrantNotFound = 13,
BATResultAcTableEmpty = 14,
BATResultNotEnoughFunds = 15,
BATResultTipError = 16,
BATResultCorruptedWallet = 17,
BATResultGrantAlreadyClaimed = 18,
BATResultContributionAmountTooLow = 19,
BATResultVerifiedPublisher = 20,
BATResultPendingPublisherRemoved = 21,
Expand Down Expand Up @@ -141,8 +139,39 @@ typedef NS_ENUM(NSInteger, BATEnvironment) {
} NS_SWIFT_NAME(Environment);


typedef NS_ENUM(NSInteger, BATPromotionType) {
BATPromotionTypeUgp = 0,
BATPromotionTypeAds = 1,
} NS_SWIFT_NAME(PromotionType);

@class BATContributionInfo, BATPublisherInfo, BATPublisherBanner, BATPendingContribution, BATPendingContributionInfo, BATVisitData, BATGrant, BATWalletProperties, BATBalance, BATAutoContributeProps, BATMediaEventInfo, BATExternalWallet, BATBalanceReportInfo, BATActivityInfoFilterOrderPair, BATActivityInfoFilter, BATReconcileInfo, BATRewardsInternalsInfo, BATServerPublisherInfo, BATTransferFee, BATContributionQueue, BATContributionQueuePublisher;

typedef NS_ENUM(NSInteger, BATPromotionStatus) {
BATPromotionStatusActive = 0,
BATPromotionStatusAttested = 1,
BATPromotionStatusClaimed = 2,
BATPromotionStatusSignedTokens = 3,
BATPromotionStatusFinished = 4,
BATPromotionStatusOver = 5,
} NS_SWIFT_NAME(PromotionStatus);


typedef NS_ENUM(NSInteger, BATPlatform) {
BATPlatformDesktop = 0,
BATPlatformAndroid = 1,
BATPlatformIos = 2,
} NS_SWIFT_NAME(Platform);


typedef NS_ENUM(NSInteger, BATOperatingSystem) {
BATOperatingSystemWindows = 0,
BATOperatingSystemMacos = 1,
BATOperatingSystemLinux = 2,
BATOperatingSystemUndefined = 3,
} NS_SWIFT_NAME(OperatingSystem);



@class BATContributionInfo, BATPublisherInfo, BATPublisherBanner, BATPendingContribution, BATPendingContributionInfo, BATVisitData, BATWalletProperties, BATBalance, BATAutoContributeProps, BATMediaEventInfo, BATExternalWallet, BATBalanceReportInfo, BATActivityInfoFilterOrderPair, BATActivityInfoFilter, BATReconcileInfo, BATRewardsInternalsInfo, BATServerPublisherInfo, BATTransferFee, BATContributionQueue, BATContributionQueuePublisher, BATPromotion, BATPromotionCreds, BATUnblindedToken, BATClientInfo;

NS_ASSUME_NONNULL_BEGIN

Expand Down Expand Up @@ -222,20 +251,10 @@ NS_SWIFT_NAME(VisitData)
@property (nonatomic, copy) NSString * faviconUrl;
@end

NS_SWIFT_NAME(Grant)
@interface BATGrant : NSObject <NSCopying>
@property (nonatomic, copy) NSString * altcurrency;
@property (nonatomic, copy) NSString * probi;
@property (nonatomic, copy) NSString * promotionId;
@property (nonatomic) uint64_t expiryTime;
@property (nonatomic, copy) NSString * type;
@end

NS_SWIFT_NAME(WalletProperties)
@interface BATWalletProperties : NSObject <NSCopying>
@property (nonatomic) double feeAmount;
@property (nonatomic, copy) NSArray<NSNumber *> * parametersChoices;
@property (nonatomic, copy) NSArray<BATGrant *> * grants;
@end

NS_SWIFT_NAME(Balance)
Expand Down Expand Up @@ -358,4 +377,43 @@ NS_SWIFT_NAME(ContributionQueuePublisher)
@property (nonatomic) double amountPercent;
@end

NS_SWIFT_NAME(Promotion)
@interface BATPromotion : NSObject <NSCopying>
@property (nonatomic, copy) NSString * id;
@property (nonatomic) uint32_t version;
@property (nonatomic) BATPromotionType type;
@property (nonatomic, copy) NSString * publicKeys;
@property (nonatomic) uint32_t suggestions;
@property (nonatomic) double approximateValue;
@property (nonatomic) bool claimed;
@property (nonatomic) BATPromotionStatus status;
@property (nonatomic) uint64_t expiresAt;
@property (nonatomic, copy, nullable) BATPromotionCreds * credentials;
@end

NS_SWIFT_NAME(PromotionCreds)
@interface BATPromotionCreds : NSObject <NSCopying>
@property (nonatomic, copy) NSString * tokens;
@property (nonatomic, copy) NSString * blindedCreds;
@property (nonatomic, copy) NSString * signedCreds;
@property (nonatomic, copy) NSString * publicKey;
@property (nonatomic, copy) NSString * batchProof;
@property (nonatomic, copy) NSString * claimId;
@end

NS_SWIFT_NAME(UnblindedToken)
@interface BATUnblindedToken : NSObject <NSCopying>
@property (nonatomic) uint64_t id;
@property (nonatomic, copy) NSString * tokenValue;
@property (nonatomic, copy) NSString * publicKey;
@property (nonatomic) double value;
@property (nonatomic, copy) NSString * promotionId;
@end

NS_SWIFT_NAME(ClientInfo)
@interface BATClientInfo : NSObject <NSCopying>
@property (nonatomic) BATPlatform platform;
@property (nonatomic) BATOperatingSystem os;
@end

NS_ASSUME_NONNULL_END
Binary file modified BraveRewards/BraveRewards.framework/Info.plist
Binary file not shown.
Binary file modified BraveRewards/BraveRewards.framework/Model.momd/Model.mom
Binary file not shown.
Binary file modified BraveRewards/BraveRewards.framework/Model.momd/VersionInfo.plist
Binary file not shown.
89 changes: 89 additions & 0 deletions BraveRewardsUI/Extensions/BraveLedgerExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

import Foundation
import BraveRewards
import Shared

private let log = Logger.rewardsLogger

extension BraveLedger {

Expand Down Expand Up @@ -125,6 +128,92 @@ extension BraveLedger {
}
return id
}

public func setupDeviceCheckEnrollment(_ client: DeviceCheckClient, completion: @escaping () -> Void) {
// Enroll in DeviceCheck
client.generateToken { [weak self] (token, error) in
guard let self = self else { return }
if let error = error {
log.error("Failed to generate DeviceCheck token: \(error)")
completion()
return
}
let paymentId = self.paymentId ?? ""
client.generateEnrollment(paymentId: paymentId, token: token) { registration, error in
if let error = error {
log.error("Failed to enroll in DeviceCheck: \(error)")
completion()
return
}
guard let registration = registration else { return }
client.registerDevice(enrollment: registration) { error in
if let error = error {
log.error("Failed to register device with mobile attestation server: \(error)")
completion()
return
}
}
}
}
}

public func claimPromotion(_ promotion: Promotion, completion: @escaping (_ success: Bool) -> Void) {
guard let paymentId = self.paymentId else { return }
let deviceCheck = DeviceCheckClient(environment: BraveLedger.environment)
let group = DispatchGroup()
if !DeviceCheckClient.isDeviceEnrolled() {
group.enter()
setupDeviceCheckEnrollment(deviceCheck) {
if !DeviceCheckClient.isDeviceEnrolled() {
DispatchQueue.main.async {
completion(false)
}
return
}
group.leave()
}
}
group.notify(queue: .main) {
deviceCheck.generateAttestation(paymentId: paymentId) { (attestation, error) in
guard let attestation = attestation else {
completion(false)
return
}
self.claimPromotion(attestation.publicKeyHash) { result, noonce in
if result != .ledgerOk {
completion(false)
return
}

deviceCheck.generateAttestationVerification(nonce: noonce) { verification, error in
guard let verification = verification else {
completion(false)
return
}

let solution = PromotionSolution()
solution.noonce = noonce
solution.signature = verification.signature
do {
solution.blob = try verification.attestationBlob.bsonData().base64EncodedString()
} catch {
log.error("Couldn't serialize attestation blob. The attest promotion will fail")
}

self.attestPromotion(promotion.id, solution: solution) { result, promotion in
if result == .ledgerOk {
self.fetchPromotions { _ in
completion(true)
}
} else {
completion(false)
}
}
}
}
}
}
}
}

extension PublisherInfo {
Expand Down
23 changes: 10 additions & 13 deletions BraveRewardsUI/Grants/GrantsListViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,16 @@ class GrantsListViewController: UIViewController {
super.viewDidLoad()

title = Strings.Grants

if let grants = ledger.walletInfo?.grants, !grants.isEmpty {
grants.forEach {
if let value = BATValue(probi: $0.probi) {
let isAd = $0.type == "ads"
grantsView.stackView.addArrangedSubview(
GrantsItemView(
amount: value.displayString,
expirationDate: isAd ? nil : Date(timeIntervalSince1970: TimeInterval($0.expiryTime))
)
)
}
}

ledger.finishedPromotions.forEach {
let value = BATValue($0.approximateValue)
let isAd = $0.type == .ads
grantsView.stackView.addArrangedSubview(
GrantsItemView(
amount: value.displayString,
expirationDate: isAd ? nil : Date(timeIntervalSince1970: TimeInterval($0.expiresAt))
)
)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions BraveRewardsUI/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ A UI framework for consuming Brave Rewards. The core logic around BraveRewards r
The latest BraveRewards.framework was built on:

```
brave-browser/373314e05e8e0abe41c21d5aee6314371e4154ad
brave-core/6544304acdc2641b4e9d6aa02cf711194a64876e
brave-browser/5d5f18be463abaf9b5f23d5b7ec14be51f7fd412
brave-core/c201526020483db2cb7125d2e412481ca11979f9
```
Loading

0 comments on commit f7144ed

Please sign in to comment.