Skip to content

Commit

Permalink
feat: user proflie from sdk fix
Browse files Browse the repository at this point in the history
  • Loading branch information
MdTeach committed Jul 17, 2023
1 parent 7aee818 commit 69d47a1
Show file tree
Hide file tree
Showing 11 changed files with 221 additions and 107 deletions.
9 changes: 7 additions & 2 deletions Sources/Chat/Send.swift
Original file line number Diff line number Diff line change
Expand Up @@ -234,14 +234,19 @@ extension PushChat {
let anotherUser = try await PushUser.get(
account: sendOptions.receiverAddress, env: sendOptions.env)

var shouldEncrypt = true

// else create the user frist and send unencrypted intent message
if anotherUser == nil {
if anotherUser == nil || anotherUser?.publicKey == nil {
let _ = try await PushUser.createUserEmpty(
userAddress: sendOptions.receiverAddress, env: sendOptions.env)

shouldEncrypt = false
}

let publicKeys = shouldEncrypt ? try await getP2PChatPublicKeys(sendOptions) : []
let sendMessagePayload = try await getSendMessagePayload(
sendOptions, publicKeys: [], shouldEncrypt: false)
sendOptions, publicKeys: publicKeys, shouldEncrypt: shouldEncrypt)

return try await sendIntentService(payload: sendMessagePayload, env: sendOptions.env)
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Endpoints/PushEndpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ extension PushEndpoint {
)
}

static func createUser(env: ENV) -> Self {
static func createUser(env: ENV, version: String = "v2") -> Self {
PushEndpoint(
env: env,
path: "users",
queryItems: [],
apiVersion: "v2"
apiVersion: version
)
}

Expand Down
72 changes: 20 additions & 52 deletions Sources/Helpers/Crypto/Pgp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,6 @@ func bytesToHex(bytes: [UInt8]) -> String {
return bytes.map { String(format: "%02hhx", $0) }.joined()
}

func recoverAddressFromSignature(signature: String, signedData: String) throws -> String {
// TODO: Implement
return ""
}

func verifyProfileSignature(verificationProof: String, signedData: String, wallet: String) throws
-> Bool
{
let length = verificationProof.split(separator: ":").count
let signature = verificationProof.split(separator: ":")[length - 1]
let _ = try recoverAddressFromSignature(
signature: String(signature), signedData: signedData)
// TODO: return recoveredAddress.lowercased() == wallet.lowercased();
return true
}

enum PgpError: Error {
case INVALID_PUBLIC_KEY
case INVALID_PRIVATE_KEY
Expand All @@ -38,10 +22,20 @@ enum PgpError: Error {

public struct EncryptedPrivateKeyV2: Encodable {
var ciphertext: String
var salt: String?
var salt: String
var nonce: String
var version: ENCRYPTION_TYPE?
var preKey: String?
var version: ENCRYPTION_TYPE
var preKey: String

public func getJSONString() throws -> String {
return try getJsonStringFromKV([
("ciphertext", self.ciphertext),
("salt", self.salt),
("nonce", self.nonce),
("version", self.version.stringValue),
("preKey", self.preKey),
])
}
}

func useEmptyPassPhrase(key: Key?) -> String? {
Expand All @@ -59,18 +53,16 @@ public struct Pgp {
}

public func preparePGPPublicKey(signer: Push.Signer) async throws -> String {
let publicKey = self.getPublicKey().trimmingCharacters(in: .newlines)

let createProfileMessage =
"Create Push Profile \n" + generateSHA256Hash(msg: self.getPublicKey())
"Create Push Profile \n" + generateSHA256Hash(msg: publicKey)
let verificationProof = try await signer.getEip191Signature(message: createProfileMessage)

let chatPublicKey = [
"key": self.getPublicKey(),
"signature": verificationProof,
]

let chatPKJsonData = try JSONSerialization.data(withJSONObject: chatPublicKey, options: [])
let chatPKeyJsonString = String(data: chatPKJsonData, encoding: .utf8)!

let chatPKeyJsonString = try getJsonStringFromKV([
("key", publicKey),
("signature", "eip191" + ":" + verificationProof),
])
return chatPKeyJsonString

}
Expand Down Expand Up @@ -151,30 +143,6 @@ public struct Pgp {
return try Pgp(publicKey: pk, secretKey: sk)
}

public static func verifyPGPPublicKey(encryptionType: String, publicKey: String, did: String)
throws -> String
{
guard
let parsedPublicKey = try? JSONSerialization.jsonObject(with: publicKey.data(using: .utf8)!)
as? [String: String],
let key = parsedPublicKey["key"],
let verificationProof = parsedPublicKey["signature"]
else {
throw PgpError.INVALID_PUBLIC_KEY
}

let pCAIP10Wallet = pCAIP10ToWallet(address: did)
let signedData = "Create Push Profile \n" + generateSHA256Hash(msg: key)

if try verifyProfileSignature(
verificationProof: verificationProof, signedData: signedData, wallet: pCAIP10Wallet)
{
return key
} else {
throw PgpError.INVALID_SIGNATURE
}
}

public func encryptPGPKey(wallet: Push.Wallet) async throws -> EncryptedPrivateKeyV2 {
var array = [UInt8](repeating: 0, count: 32)
getRandomValues(array: &array)
Expand Down
22 changes: 22 additions & 0 deletions Sources/Helpers/JsonUtils.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import Foundation

func getJsonStringFromKV(_ tuples: [(String, String)]) throws -> String {
func removeOccurrences(substring: String, text: String, with: String) -> String {
return text.replacingOccurrences(of: substring, with: with)
}

var jsonArray: [[String: String]] = []
for tuple in tuples {
let jsonDict: [String: String] = [
tuple.0: tuple.1
]
jsonArray.append(jsonDict)
}

let jsonData = try JSONSerialization.data(withJSONObject: jsonArray)
var jsonString = String(data: jsonData, encoding: .utf8)!
jsonString = removeOccurrences(substring: "},{", text: jsonString, with: ",")
jsonString = removeOccurrences(substring: "}]", text: jsonString, with: "}")
jsonString = removeOccurrences(substring: "[{", text: jsonString, with: "{")
return jsonString
}
31 changes: 15 additions & 16 deletions Sources/User/CreateUser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,23 @@ extension PushUser {
var did: String
var publicKey: String
var encryptedPrivateKey: String

public func getJSONString() throws -> String {
return try getJsonStringFromKV([
("caip10", self.caip10),
("did", self.did),
("publicKey", self.publicKey),
("encryptedPrivateKey", self.encryptedPrivateKey),
])
}
}

private struct CreateUserAPIOptions: Encodable {
var caip10: String
var did: String
var publicKey: String
var encryptedPrivateKey: String
var encryptionType: String
var encryptionType: String?
var name: String?
var encryptedPassword: String?
var verificationProof: String?
Expand Down Expand Up @@ -98,11 +107,7 @@ extension PushUser {
let encryptedPrivateKey: EncryptedPrivateKeyV2 = try await keyPairs.encryptPGPKey(
wallet: wallet)

guard let encryptedPrivateKeyData = try? JSONEncoder().encode(encryptedPrivateKey),
let encryptedPrivateKeyString = String(data: encryptedPrivateKeyData, encoding: .utf8)
else {
throw UtilsError.ERROR_CONVERTING_ENCRYPTED_PRIVATEkEY_TO_DATA
}
let encryptedPrivateKeyString = try encryptedPrivateKey.getJSONString()

options.progressHook?(
ProgressHookType(
Expand All @@ -112,23 +117,19 @@ extension PushUser {
level: ProgressLevel.INFO
))

let apiData = CreateUserHashData(
let apiDataString = try CreateUserHashData(
caip10: walletToPCAIP10(account: caip10),
did: walletToPCAIP10(account: caip10),
publicKey: publicKey,
encryptedPrivateKey: encryptedPrivateKeyString
)
).getJSONString()

guard let apiDataString = String(data: try JSONEncoder().encode(apiData), encoding: .utf8)
else {
throw UtilsError.ERROR_CONVERTING_MSG_HASH_TO_DATA
}
let hash = generateSHA256Hash(
msg:
apiDataString
)

let _ = try await wallet.getEip191Signature(message: hash, version: "v2")
let verificationProof = try await wallet.getEip191Signature(message: hash, version: "v2")

let updatedData = CreateUserAPIOptions(
caip10: walletToPCAIP10(account: caip10),
Expand All @@ -137,9 +138,7 @@ extension PushUser {
encryptedPrivateKey: encryptedPrivateKeyString,
encryptionType: ENCRYPTION_TYPE.PGP_V3.stringValue,
name: "",
// Replace with verification proof
// verificationProof: signatureObject
signature: "xyz",
signature: verificationProof,
sigType: "a"
)

Expand Down
1 change: 1 addition & 0 deletions Tests/Chat/Group/CreateGroupTests.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Foundation
import Push
import XCTest

Expand Down
44 changes: 41 additions & 3 deletions Tests/Chat/P2P/SendTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class SendChatsTests: XCTestCase {
XCTAssertEqual(latestMessage, messageToSen)
}

func testSendIntent() async throws {
func testSendIntentUnEncrypted() async throws {
let recipientAddress = generateRandomEthereumAddress()
let senderAddress = UserAddress
let senderPgpPk = UserPrivateKey
Expand All @@ -62,6 +62,45 @@ class SendChatsTests: XCTestCase {
XCTAssertEqual(latestMessage, messageToSen)
}

func testSendIntentEncrypted() async throws {
let userPk = getRandomAccount()
let signer = try SignerPrivateKey(
privateKey: userPk
)
let recipientAddress = try await signer.getAddress()

let _ = try await PushUser.create(
options: PushUser.CreateUserOptions(
env: ENV.STAGING,
signer: SignerPrivateKey(
privateKey: userPk
),
progressHook: nil
))

let senderAddress = UserAddress
let senderPgpPk = UserPrivateKey

let messageToSen = "Hello user \(recipientAddress)"

let _ = try await Push.PushChat.sendIntent(
PushChat.SendOptions(
messageContent: messageToSen,
messageType: "Text",
receiverAddress: recipientAddress,
account: senderAddress,
pgpPrivateKey: senderPgpPk
))

let threadHash = try await PushChat.ConversationHash(
conversationId: recipientAddress, account: senderAddress)!
let latestMessage = try await PushChat.History(
threadHash: threadHash, limit: 1, pgpPrivateKey: senderPgpPk, toDecrypt: true, env: .STAGING
).first!.messageContent

XCTAssertEqual(latestMessage, messageToSen)
}

func testSendMGOnly() async throws {
let recipientAddress = generateRandomEthereumAddress()
let senderAddress = UserAddress
Expand Down Expand Up @@ -166,7 +205,6 @@ class SendChatsTests: XCTestCase {

XCTAssertEqual(res, messageToSen2)
}

}

let UserAddress = "0xD26A7BF7fa0f8F1f3f73B056c9A67565A6aFE63c"
Expand Down Expand Up @@ -261,5 +299,5 @@ let UserPublicKey = """
8+HQfOVr7NE7e20Vtat7P51yzZTBCPfOsPdHPRdJeWrIS76DmfKF0ATKOw0PNfWB
EIXKzpU+pdxSjyFbgg9NGOczMtYUTkheIQeBerPjFWsoCEtHMcE=
=5cZE
-----END PGP PUBLIC KEY BLOCK-----"
-----END PGP PUBLIC KEY BLOCK-----
"""
17 changes: 7 additions & 10 deletions Tests/Helper/PgpTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ class PgpTests: XCTestCase {
let pair2 = try Pgp.GenerateNewPgpPair()

let originalMessage = "This is a good place to find a city"
let message = originalMessage.data(using: .utf8)!

let encMsg = try pair1.encryptWithPGPKey(
message: message, anotherUserPublicKey: pair2.publicKey)
let encMsg = try Pgp.pgpEncryptV2(
message: originalMessage, pgpPublicKeys: [pair1.getPublicKey(), pair2.getPublicKey()])

XCTAssertTrue(
encMsg.hasPrefix("-----BEGIN PGP MESSAGE-----"),
Expand All @@ -27,11 +26,11 @@ class PgpTests: XCTestCase {
encMsg.hasSuffix("-----END PGP MESSAGE-----\n"),
"encryptedSecret should end with appropriate suffix")

let decMsg1 = try pair1.decryptWithPGPKey(message: encMsg)
// let decMsg2 = try pair2.decryptWithPGPKey(message: encMsg)
let decMsg1 = try Pgp.pgpDecrypt(cipherText: encMsg, toPrivateKeyArmored: pair1.getSecretKey())
let decMsg2 = try Pgp.pgpDecrypt(cipherText: encMsg, toPrivateKeyArmored: pair2.getSecretKey())

// XCTAssertEqual(originalMessage, decMsg1)
// XCTAssertEqual(originalMessage, decMsg2)
XCTAssertEqual(originalMessage, decMsg1)
XCTAssertEqual(originalMessage, decMsg2)
}

func testPgpSignatureVerification() async throws {
Expand Down Expand Up @@ -80,12 +79,10 @@ class PgpTests: XCTestCase {
String(data: try JSONEncoder().encode(apiData), encoding: .utf8)!
)

let signature = try Pgp.sign(message: hash, privateKey: secKey)
let _ = try Pgp.sign(message: hash, privateKey: secKey)

XCTAssertEqual(message, hash)

print(signature)

}
}

Expand Down
4 changes: 1 addition & 3 deletions Tests/User/CreateUserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ class CreateUserTests: XCTestCase {
let user = try await PushUser.create(
options: PushUser.CreateUserOptions(
env: ENV.STAGING,
signer: SignerPrivateKey(
privateKey: userPk
),
signer: signer,
progressHook: nil
))

Expand Down
Loading

0 comments on commit 69d47a1

Please sign in to comment.