Merge pull request #144 from James-Sangalli/handleImport

Handle import
pull/152/head
James Sangalli 7 years ago committed by GitHub
commit 300f89f912
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      Trust.xcworkspace/xcshareddata/xcschemes/AlphaWallet - Europe.xcscheme
  2. 4
      Trust.xcworkspace/xcshareddata/xcschemes/AlphaWallet.xcscheme
  3. 4
      Trust.xcworkspace/xcshareddata/xcschemes/AlphaWalletTests.xcscheme
  4. 4
      Trust.xcworkspace/xcshareddata/xcschemes/AlphaWalletUITests.xcscheme
  5. 4
      Trust/Localization/en.lproj/Localizable.strings
  6. 64
      Trust/Market/Coordinators/UniversalLinkCoordinator.swift
  7. 162
      Trust/Market/UniversalLinkHandler.swift
  8. 2
      Trust/Settings/Types/Constants.swift
  9. 2
      Trust/Tokens/Coordinators/TokensCoordinator.swift
  10. 16
      Trust/Transactions/Coordinators/TicketsCoordinator.swift
  11. 29
      TrustTests/Market/UniversalLinkHandlerTests.swift

@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>
@ -49,7 +49,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>

@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>
@ -49,7 +49,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>

@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>
@ -190,7 +190,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>

@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>
@ -49,7 +49,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2912CCF41F6A830700C6CBE3"
BuildableName = "AlphaWallet.app"
BuildableName = "AlphaWallet"
BlueprintName = "AlphaWallet"
ReferencedContainer = "container:Trust.xcodeproj">
</BuildableReference>

@ -248,8 +248,8 @@
"a.welcome.onboarding.createwallet.button.title" = "GET STARTED";
"a.settings.advanced.label.title" = "Advanced";
"a.marketplace.tabbar.item.title" = "Marketplace";
"a.claim.ticket.success.title" = "Your ticket has been imported and should be available shortly";
"a.claim.ticket.failed.title" = "Your ticket was not imported";
"a.claim.ticket.success.title" = "Your ticket has been imported and will be available shortly";
"a.claim.ticket.failed.title" = "Invalid ticket link";
"a.claim.ticket.inProgress.title" = "Importing ticket...";
"a.claim.ticket.done.button.title" = "Done";
"a.claim.ticket.import.button.title" = "Import";

@ -21,9 +21,8 @@ class UniversalLinkCoordinator: Coordinator {
guard matchedPrefix else {
return false
}
let keystore = try! EtherKeystore()
let signedOrder = UniversalLinkHandler().parseURL(url: (url?.description)!)
let signedOrder = UniversalLinkHandler().parseUniversalLink(url: (url?.absoluteString)!)
let signature = signedOrder.signature.substring(from: 2)
// form the json string out of the order for the paymaster server
@ -35,20 +34,21 @@ class UniversalLinkCoordinator: Coordinator {
indicesStringEncoded += String(indices[i]) + ","
}
//cut off last comma
indicesStringEncoded = indicesStringEncoded.substring(from: indicesStringEncoded.count - 1)
indicesStringEncoded = indicesStringEncoded.substring(to: indicesStringEncoded.count - 1)
let address = (keystore.recentlyUsedWallet?.address.eip55String)!
let parameters: Parameters = [
"address": keystore.recentlyUsedWallet?.address.description,
"address": address,
"indices": indicesStringEncoded,
"v": signature.substring(from: 128),
"r": "0x" + signature.substring(with: Range(uncheckedBounds: (0, 64))),
"s": "0x" + signature.substring(with: Range(uncheckedBounds: (64, 128)))
]
let query = UniversalLinkHandler.paymentServer
let query = UniversalLinkHandler.paymentServer
//TODO check if URL is valid or not. Price?
let validURL = true
if validURL {
//TODO check if URL is valid or not by validating signature, low priority
//TODO localize
if signature.count > 128 {
if let viewController = delegate?.viewControllerForPresenting(in: self) {
UIAlertController.alert(title: nil, message: "Import Link?", alertButtonTitles: [R.string.localizable.aClaimTicketImportButtonTitle(), R.string.localizable.cancel()], alertButtonStyles: [.default, .cancel], viewController: viewController) {
if $0 == 0 {
@ -79,29 +79,35 @@ class UniversalLinkCoordinator: Coordinator {
}
}
Alamofire.request(
query,
method: .post,
parameters: parameters
).responseJSON {
result in
// TODO handle http response
print(result)
//TODO handle successful or not. Pass an error (message?) to the view model if we have one
let successful = true
if let vc = self.statusViewController, var viewModel = vc.viewModel {
if successful {
viewModel.state = .succeeded
vc.configure(viewModel: viewModel)
} else {
viewModel.state = .failed
vc.configure(viewModel: viewModel)
}
}
}
}
Alamofire.request(
query,
method: .post,
parameters: parameters
).responseJSON {
result in
var successful = true
//401 code will be given if signature is invalid on the server
if let response = result.response, (response.statusCode == 401 || response.statusCode > 299) {
successful = false
}
if let vc = self.statusViewController {
// TODO handle http response
print(result)
if let vc = self.statusViewController, var viewModel = vc.viewModel {
if successful {
viewModel.state = .succeeded
vc.configure(viewModel: viewModel)
} else {
viewModel.state = .failed
vc.configure(viewModel: viewModel)
}
}
}
}
}
}
extension UniversalLinkCoordinator: StatusViewControllerDelegate {
func didPressDone(in viewController: StatusViewController) {
viewController.dismiss(animated: true)

@ -27,24 +27,24 @@ https://app.awallet.io/AA9CQFq1tAAAe+6CvdnoZrK9EUeApH8iYcaE4wECAwQFBgcICS+YK4TGN
import Foundation
import BigInt
public class UniversalLinkHandler {
public let urlPrefix = "https://app.awallet.io/"
public static let paymentServer = "http://stormbird.duckdns.org:8080/api/claimToken"
public static let paymentServer = "https://feemaster.eastasia.cloudapp.azure.com:8080/api/claimToken" //"http://stormbird.duckdns.org:8080/api/claimToken"
func createUniversalLink(signedOrder: SignedOrder) -> String
{
let message = MarketQueueHandler.bytesToHexa(signedOrder.message)
let signature = signedOrder.signature.substring(from: 2)
//message is with 32 bytes each of price and expiry and is shortened for link
func createUniversalLink(signedOrder: SignedOrder) -> String {
let message = formatMessageForLink(signedOrder: signedOrder)
let signature = signedOrder.signature
let link = (message + signature).hexa2Bytes
let binaryData = Data(bytes: link)
let base64String = binaryData.base64EncodedString()
return urlPrefix + base64String
}
func parseURL(url: String) -> SignedOrder {
//TODO add exception handling
//link has shortened price and expiry and must be expanded
func parseUniversalLink(url: String) -> SignedOrder {
let linkInfo = url.substring(from: urlPrefix.count)
let linkBytes = Data(base64Encoded: linkInfo)?.array
let price = getPriceFromLinkBytes(linkBytes: linkBytes!)
@ -52,19 +52,87 @@ public class UniversalLinkHandler {
let contractAddress = getContractAddressFromLinkBytes(linkBytes: linkBytes!)
let ticketIndices = getTicketIndicesFromLinkBytes(linkBytes: linkBytes!)
let (v, r, s) = getVRSFromLinkBytes(linkBytes: linkBytes!)
let message = getMessageFromLinkBytes(linkBytes: linkBytes!)
let order = Order(
price: price,
indices: ticketIndices,
expiry: expiry,
contractAddress: contractAddress,
start: BigUInt("0")!,
count: ticketIndices.count
price: price,
indices: ticketIndices,
expiry: expiry,
contractAddress: contractAddress,
start: BigUInt("0")!,
count: ticketIndices.count
)
let message = getMessageFromOrder(order: order)
return SignedOrder(order: order, message: message, signature: "0x" + r + s + v)
}
//we used a special encoding so that one 16 bit number could represent either one ticket or two
//this is for the purpose of keeping universal links as short as possible
func decodeTicketIndices(indices: [UInt16]) -> [UInt8] {
var indicesBytes = [UInt8]()
for i in 0...indices.count - 1 {
let index = indices[i]
if(index < 128) {
let byte = UInt8(index)
indicesBytes.append(byte)
} else {
//Top 7 bits
let firstByteHigh = UInt8(128 + (index >> 8))
//bottom 8 bits
let secondByteLow = UInt8(index & 255)
indicesBytes.append(firstByteHigh)
indicesBytes.append(secondByteLow)
}
}
return indicesBytes
}
//shortens price and expiry
func formatMessageForLink(signedOrder: SignedOrder) -> String {
let message = signedOrder.message
let indices = decodeTicketIndices(indices: signedOrder.order.indices)
var messageWithSzabo = [UInt8]()
let price = Array(message[0...31])
let expiry = Array(message[32...63])
let priceHex = MarketQueueHandler.bytesToHexa(price)
let expiryHex = MarketQueueHandler.bytesToHexa(expiry)
//removes leading zeros
let priceInt = BigUInt(priceHex, radix: 16)!
let expiryInt = BigUInt(expiryHex, radix: 16)!
//change from wei to szabo
let priceSzabo = priceInt / 1000000000000
var priceBytes = formatTo4Bytes(priceSzabo.serialize().bytes)
var expiryBytes = formatTo4Bytes(expiryInt.serialize().bytes)
for i in 0...3 {
messageWithSzabo.append(priceBytes[i])
}
for i in 0...3 {
messageWithSzabo.append(expiryBytes[i])
}
for i in 64...83 {
messageWithSzabo.append(message[i])
}
for i in 0...indices.count - 1 {
messageWithSzabo.append(indices[i])
}
return MarketQueueHandler.bytesToHexa(messageWithSzabo)
}
func formatTo4Bytes(_ array: [UInt8]) -> [UInt8] {
var formattedArray = [UInt8]()
if array.count == 4 {
return array
} else if array.isEmpty {
for _ in 0...3 {
formattedArray.append(0)
}
return formattedArray
} else {
let missingDigits = 4 - array.count
for _ in 0...missingDigits - 1 {
formattedArray.append(0)
}
return formattedArray
}
}
func getPriceFromLinkBytes(linkBytes: [UInt8]) -> BigUInt {
var priceBytes = [UInt8]()
@ -72,8 +140,9 @@ public class UniversalLinkHandler {
//price in szabo
priceBytes.append(linkBytes[i])
}
return (BigUInt(MarketQueueHandler.bytesToHexa(priceBytes),
radix: 16)!.multiplied(by: BigUInt("1000000000000")!))
let priceHex = MarketQueueHandler.bytesToHexa(priceBytes)
let price = BigUInt(priceHex, radix: 16)!
return price * 1000000000000
}
func getExpiryFromLinkBytes(linkBytes: [UInt8]) -> BigUInt {
@ -113,25 +182,23 @@ public class UniversalLinkHandler {
else {
ticketIndices.append(UInt16(byte))
}
break;
break
case 2:
currentIndex += UInt16(byte)
ticketIndices.append(currentIndex)
state = 1
break;
break
default:
break
}
}
return ticketIndices
}
func getVRSFromLinkBytes(linkBytes: [UInt8]) -> (String, String, String) {
var signatureStart = linkBytes.count - 65
var rBytes = [UInt8]()
for i in signatureStart...signatureStart + 31
{
for i in signatureStart...signatureStart + 31 {
rBytes.append(linkBytes[i])
}
let r = MarketQueueHandler.bytesToHexa(rBytes)
@ -140,20 +207,49 @@ public class UniversalLinkHandler {
for i in signatureStart...signatureStart + 31 {
sBytes.append(linkBytes[i])
}
let s = MarketQueueHandler.bytesToHexa(sBytes)
let v = String(format:"%2X", linkBytes[linkBytes.count - 1]).trimmed
return (v, r, s)
}
func getMessageFromLinkBytes(linkBytes: [UInt8]) -> [UInt8] {
let messageLength = linkBytes.count - 65
//price and expiry need to be 32 bytes each
func getMessageFromOrder(order: Order) -> [UInt8] {
var message = [UInt8]()
for i in 0...messageLength - 1 {
message.append(linkBytes[i])
//encode price and expiry first
let priceBytes = padTo32(order.price.serialize().array)
for i in 0...31 {
message.append(priceBytes[i])
}
let expiryBytes = padTo32(order.expiry.serialize().array)
for i in 0...31 {
message.append(expiryBytes[i])
}
let contractBytes = order.contractAddress.hexa2Bytes
for i in 0...19 {
message.append(contractBytes[i])
}
let indices = OrderHandler.uInt16ArrayToUInt8(arrayOfUInt16: order.indices)
for i in 0...indices.count - 1 {
message.append(indices[i])
}
return message
}
func padTo32(_ buffer: [UInt8]) -> [UInt8] {
var padded = [UInt8]()
if buffer.isEmpty {
for _ in 0...31 {
padded.append(0)
}
} else {
for _ in 0...31 - buffer.count - 1 {
padded.append(0)
}
for i in 0...buffer.count - 1 {
padded.append(buffer[i])
}
}
return padded
}
}
}

@ -21,7 +21,7 @@ public struct Constants {
public static let dappsBrowserURL = "https://dapps.trustwalletapp.com"
//FIFA hardcoded FIFA token address. Look for "//FIFA" for relevant changes
public static let fifaContractAddress = "0xa3347C8ED134444C25169872c90a6360D42b3691"
public static let fifaContractAddress = "0xb9F20F7C6F5Ed408DeDaB79B093b42Fb83E77f8E"
}
public struct UnitConfiguration {

@ -73,7 +73,7 @@ class TokensCoordinator: Coordinator {
// which contains a ticket priced 0. TODO: The case when ticket price > 0
// is not dealt yet.
@objc func useUniversalLink(url: String) {
let signedOrder = UniversalLinkHandler().parseURL(url: url)
let signedOrder = UniversalLinkHandler().parseUniversalLink(url: url)
//TODO get info around name, symbol etc
let tokenObject = TokenObject(
contract: signedOrder.order.contractAddress,

@ -10,6 +10,7 @@ import UIKit
import Result
import TrustKeystore
import MessageUI
import BigInt
protocol TicketsCoordinatorDelegate: class {
func didPressTransfer(for type: PaymentFlow,
@ -180,8 +181,19 @@ class TicketsCoordinator: NSObject, Coordinator {
}
private func generateTransferLink(ticketHolder: TicketHolder, paymentFlow: PaymentFlow) -> String {
//TODO replace with transfer link generated from ticketHolder and paymentFlow
return "https://app.alphawallet.io/something"
let order = Order(
price: BigUInt("0")!,
indices: ticketHolder.ticketIndices,
expiry: BigUInt("0")!,
contractAddress: Constants.fifaContractAddress,
start: BigUInt("0")!,
count: ticketHolder.ticketIndices.count
)
let orders = [order]
let address = keystore.recentlyUsedWallet?.address
let account = try! EtherKeystore().getAccount(for: address!)
let signedOrders = try! OrderHandler().signOrders(orders: orders, account: account!)
return UniversalLinkHandler().createUniversalLink(signedOrder: signedOrders[0])
}
private func transferViaWalletAddressTextEntry(ticketHolder: TicketHolder, paymentFlow: PaymentFlow) {

@ -5,16 +5,37 @@
import Foundation
@testable import Trust
import XCTest
import BigInt
import TrustKeystore
class UniversalLinkHandlerTests: XCTestCase {
func testUniversalLinkParser() {
let testUrl = "https://app.awallet.io/AAGGoFq8Ule8mhAmpLxvC6i75IbR0J2lcys55AECAwQFBgcICYvWi5I+Tl5m9XumBD5jLIm6i39kD7F40UW4BaJDEVOWLTYz3kek7wjT7Bn+2w0NCiyx7zWuvseTA8qfoIqCIxob"
let signedOrder = UniversalLinkHandler().parseURL(url: testUrl)
let testUrl = "https://app.awallet.io/AAAAAAAAAACjNHyO0TRETCUWmHLJCmNg1Cs2kQFxEtQiQ269SZP2r2Y6CETiCqCE3HGQa63LYjsaCOccJi0mj9bpsmnZCwFkjVcNaaJ6Ed8lVU83UiGILQZ4CcFhHA=="
let signedOrder = UniversalLinkHandler().parseUniversalLink(url: testUrl)
XCTAssertGreaterThanOrEqual(signedOrder.signature.count, 130)
let url = UniversalLinkHandler().createUniversalLink(signedOrder: signedOrder)
print(url)
XCTAssertEqual(testUrl, url)
}
func testCreateUniversalLink() {
var indices = [UInt16]()
indices.append(1)
let testOrder1 = Order(price: BigUInt("0")!,
indices: indices,
expiry: BigUInt("0")!,
contractAddress: Constants.fifaContractAddress,
start: BigUInt("91239231313")!,
count: 3
)
var testOrders = [Order]()
testOrders.append(testOrder1)
//let account = try! EtherKeystore().getAccount(for: Address(string: "0x007bEe82BDd9e866b2bd114780a47f2261C684E3")!)
//let signedOrder = try! OrderHandler().signOrders(orders: testOrders, account: account!)
//let url = UniversalLinkHandler().createUniversalLink(signedOrder: signedOrder[0])
//print(url)
}
}
}

Loading…
Cancel
Save