From 58f43107abdb68a15af59bd364ac261fd2ed27f7 Mon Sep 17 00:00:00 2001 From: moiseev-signal <122060238+moiseev-signal@users.noreply.github.com> Date: Fri, 23 Feb 2024 09:56:38 -0800 Subject: [PATCH] Enforce Swift code formatting --- .editorconfig | 3 + .github/workflows/build_and_test.yml | 4 + .swiftformat | 25 + swift/Package.swift | 6 +- swift/Sources/LibSignalClient/Address.swift | 16 +- swift/Sources/LibSignalClient/Aes256Ctr.swift | 24 +- swift/Sources/LibSignalClient/Aes256Gcm.swift | 110 +- .../LibSignalClient/Aes256GcmSiv.swift | 56 +- .../Sources/LibSignalClient/AsyncUtils.swift | 4 +- swift/Sources/LibSignalClient/Cds2.swift | 20 +- .../LibSignalClient/DataStoreInMemory.swift | 30 +- .../LibSignalClient/DataStoreProtocols.swift | 2 +- .../LibSignalClient/DataStoreUtils.swift | 154 ++- .../LibSignalClient/DeviceTransfer.swift | 14 +- swift/Sources/LibSignalClient/Error.swift | 2 +- .../Sources/LibSignalClient/Fingerprint.swift | 31 +- .../Sources/LibSignalClient/HsmEnclave.swift | 19 +- swift/Sources/LibSignalClient/Ias.swift | 1 - .../Sources/LibSignalClient/IdentityKey.swift | 19 +- .../LibSignalClient/IncrementalMac.swift | 18 +- .../Sources/LibSignalClient/IoProtocols.swift | 10 +- swift/Sources/LibSignalClient/IoUtils.swift | 13 +- swift/Sources/LibSignalClient/Kdf.swift | 46 +- swift/Sources/LibSignalClient/Kem.swift | 15 +- swift/Sources/LibSignalClient/Media.swift | 4 +- .../LibSignalClient/MessageBackup.swift | 101 +- .../LibSignalClient/NativeHandleOwner.swift | 12 +- swift/Sources/LibSignalClient/Net.swift | 31 +- swift/Sources/LibSignalClient/Pin.swift | 4 +- .../Sources/LibSignalClient/PrivateKey.swift | 7 +- swift/Sources/LibSignalClient/Protocol.swift | 100 +- swift/Sources/LibSignalClient/PublicKey.swift | 11 +- .../LibSignalClient/SealedSender.swift | 164 ++- .../SealedSenderCertificates.swift | 28 +- swift/Sources/LibSignalClient/ServiceId.swift | 6 +- swift/Sources/LibSignalClient/Sgx.swift | 5 +- swift/Sources/LibSignalClient/Svr2.swift | 17 +- swift/Sources/LibSignalClient/Username.swift | 10 +- swift/Sources/LibSignalClient/Utils.swift | 6 +- .../messages/CiphertextMessage.swift | 5 +- .../messages/PlaintextContent.swift | 6 +- .../messages/PreKeySignalMessage.swift | 6 +- .../SenderKeyDistributionMessage.swift | 24 +- .../messages/SenderKeyMessage.swift | 6 +- .../messages/SignalMessage.swift | 24 +- .../state/KyberPreKeyRecord.swift | 6 +- .../LibSignalClient/state/PreKeyBundle.swift | 144 ++- .../LibSignalClient/state/PreKeyRecord.swift | 14 +- .../state/SenderKeyRecord.swift | 6 +- .../LibSignalClient/state/SessionRecord.swift | 8 +- .../state/SignedPreKeyRecord.swift | 27 +- .../zkgroup/AuthCredential.swift | 6 +- .../zkgroup/AuthCredentialPresentation.swift | 46 +- .../zkgroup/AuthCredentialResponse.swift | 6 +- .../zkgroup/AuthCredentialWithPni.swift | 6 +- .../AuthCredentialWithPniResponse.swift | 6 +- .../zkgroup/BackupAuthCredential.swift | 3 +- .../BackupAuthCredentialPresentation.swift | 1 - .../zkgroup/BackupAuthCredentialRequest.swift | 2 +- .../BackupAuthCredentialRequestContext.swift | 2 - .../LibSignalClient/zkgroup/ByteArray.swift | 12 +- .../zkgroup/CallLinkAuthCredential.swift | 46 +- .../CallLinkAuthCredentialPresentation.swift | 39 +- .../CallLinkAuthCredentialResponse.swift | 54 +- .../zkgroup/CallLinkPublicParams.swift | 6 +- .../zkgroup/CallLinkSecretParams.swift | 50 +- .../zkgroup/ClientZkAuthOperations.swift | 142 +-- .../zkgroup/ClientZkGroupCipher.swift | 116 +- .../zkgroup/ClientZkProfileOperations.swift | 94 +- .../zkgroup/ClientZkReceiptOperations.swift | 84 +- .../zkgroup/CreateCallLinkCredential.swift | 50 +- ...CreateCallLinkCredentialPresentation.swift | 28 +- .../CreateCallLinkCredentialRequest.swift | 42 +- ...eateCallLinkCredentialRequestContext.swift | 74 +- .../CreateCallLinkCredentialResponse.swift | 6 +- .../ExpiringProfileKeyCredential.swift | 26 +- ...ExpiringProfileKeyCredentialResponse.swift | 6 +- .../zkgroup/GenericServerPublicParams.swift | 6 +- .../zkgroup/GenericServerSecretParams.swift | 48 +- .../zkgroup/GroupIdentifier.swift | 10 +- .../zkgroup/GroupMasterKey.swift | 10 +- .../zkgroup/GroupPublicParams.swift | 20 +- .../zkgroup/GroupSecretParams.swift | 64 +- .../zkgroup/GroupSendCredential.swift | 59 +- .../GroupSendCredentialPresentation.swift | 35 +- .../zkgroup/GroupSendCredentialResponse.swift | 207 +-- .../zkgroup/NotarySignature.swift | 10 +- .../LibSignalClient/zkgroup/ProfileKey.swift | 54 +- .../zkgroup/ProfileKeyCiphertext.swift | 6 +- .../zkgroup/ProfileKeyCommitment.swift | 6 +- .../ProfileKeyCredentialPresentation.swift | 32 +- .../zkgroup/ProfileKeyCredentialRequest.swift | 6 +- .../ProfileKeyCredentialRequestContext.swift | 20 +- .../zkgroup/ProfileKeyVersion.swift | 10 +- .../zkgroup/ReceiptCredential.swift | 32 +- .../ReceiptCredentialPresentation.swift | 44 +- .../zkgroup/ReceiptCredentialRequest.swift | 6 +- .../ReceiptCredentialRequestContext.swift | 20 +- .../zkgroup/ReceiptCredentialResponse.swift | 6 +- .../zkgroup/ReceiptSerial.swift | 10 +- .../zkgroup/ServerPublicParams.swift | 24 +- .../zkgroup/ServerSecretParams.swift | 70 +- .../zkgroup/ServerZkAuthOperations.swift | 104 +- .../zkgroup/ServerZkProfileOperations.swift | 62 +- .../zkgroup/ServerZkReceiptOperations.swift | 48 +- .../zkgroup/UuidCiphertext.swift | 6 +- .../LibSignalClientTests/AsyncTests.swift | 8 +- .../LibSignalClientTests/BridgingTests.swift | 2 +- .../ClonableHandleOwnerTests.swift | 2 +- .../LibSignalClientTests/CryptoTests.swift | 66 +- .../HsmEnclaveTests.swift | 3 +- .../Tests/LibSignalClientTests/IasTests.swift | 35 +- .../IncrementalMacTests.swift | 20 +- .../Tests/LibSignalClientTests/IoUtils.swift | 16 +- .../MediaSanitizerTests.swift | 4 +- .../MessageBackupTests.swift | 92 +- .../Tests/LibSignalClientTests/NetTests.swift | 9 +- .../Tests/LibSignalClientTests/PinTests.swift | 1 - .../LibSignalClientTests/PublicAPITests.swift | 327 +++-- .../LibSignalClientTests/ServiceIdTests.swift | 12 +- .../LibSignalClientTests/SessionTests.swift | 673 ++++++---- .../Tests/LibSignalClientTests/SgxTests.swift | 25 +- .../LibSignalClientTests/TestCaseBase.swift | 4 +- .../LibSignalClientTests/TestUtils.swift | 1 + .../LibSignalClientTests/UsernameTests.swift | 24 +- .../LibSignalClientTests/ZKGroupTests.swift | 1123 +++++++++-------- 126 files changed, 3121 insertions(+), 2738 deletions(-) create mode 100644 .swiftformat diff --git a/.editorconfig b/.editorconfig index 5ee0feec..6a21d12c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -34,3 +34,6 @@ max_line_length = 80 [*.sh] indent_size = 4 + +[*.swift] +indent_size = 4 diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 812cb7d4..5d0e284a 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -353,6 +353,10 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Check formatting + run: swiftformat --swiftversion 5 --reporter github-actions-log --lint . + working-directory: swift + - name: Run lint run: swiftlint lint --strict --reporter github-actions-logging working-directory: swift diff --git a/.swiftformat b/.swiftformat new file mode 100644 index 00000000..20f4ce2c --- /dev/null +++ b/.swiftformat @@ -0,0 +1,25 @@ +#--header "\nCopyright {created.year} Signal Messenger, LLC.\nSPDX-License-Identifier: AGPL-3.0-only\n" +--disable hoistPatternLet +# Explicit self is better than implicit self. +--self insert +# Some arguments that it considers unused are used in doc comments, and replacing them with '_' is an error. +--stripunusedargs unnamed-only +--wraparguments before-first +--wrapcollections before-first +# Libsignal is a collection of many languages, remembering specific of each one is hard. Make it explicit. +--disable redundantinternal +# Ranges look better without spaces +--ranges no-space +# Pragmas should start at the begining of line. +--ifdef outdent +--indent 4 +# Patters are not redundant, they show the shape of thing, they show the shape of things. +--disable redundantPattern +# Leave try in the innermost position. +--disable hoistTry +# Explicit ACL even in extensions. +--extensionacl "on-declarations" +# Explicit is better than implicit. +--disable redundantNilInit +# Indentation for multi-line string literals. +--indentstrings true diff --git a/swift/Package.swift b/swift/Package.swift index 8e218ce0..278a04c8 100644 --- a/swift/Package.swift +++ b/swift/Package.swift @@ -12,13 +12,13 @@ let rustBuildDir = "../target/debug/" let package = Package( name: "LibSignalClient", platforms: [ - .macOS(.v10_15), .iOS(.v13) + .macOS(.v10_15), .iOS(.v13), ], products: [ .library( name: "LibSignalClient", targets: ["LibSignalClient"] - ) + ), ], dependencies: [ .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.3.0"), @@ -34,6 +34,6 @@ let package = Package( name: "LibSignalClientTests", dependencies: ["LibSignalClient"], linkerSettings: [.unsafeFlags(["-L\(rustBuildDir)"])] - ) + ), ] ) diff --git a/swift/Sources/LibSignalClient/Address.swift b/swift/Sources/LibSignalClient/Address.swift index 74405535..472f424d 100644 --- a/swift/Sources/LibSignalClient/Address.swift +++ b/swift/Sources/LibSignalClient/Address.swift @@ -8,9 +8,11 @@ import SignalFfi public class ProtocolAddress: ClonableHandleOwner { public convenience init(name: String, deviceId: UInt32) throws { var handle: OpaquePointer? - try checkError(signal_address_new(&handle, - name, - deviceId)) + try checkError(signal_address_new( + &handle, + name, + deviceId + )) self.init(owned: handle!) } @@ -25,11 +27,11 @@ public class ProtocolAddress: ClonableHandleOwner { } } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_address_clone(&newHandle, currentHandle) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_address_destroy(handle) } @@ -47,7 +49,7 @@ public class ProtocolAddress: ClonableHandleOwner { /// /// In a future release ProtocolAddresses will *only* support ServiceIds. public var serviceId: ServiceId! { - return try? ServiceId.parseFrom(serviceIdString: name) + return try? ServiceId.parseFrom(serviceIdString: self.name) } public var deviceId: UInt32 { @@ -63,7 +65,7 @@ public class ProtocolAddress: ClonableHandleOwner { extension ProtocolAddress: CustomDebugStringConvertible { public var debugDescription: String { - return "\(name).\(deviceId)" + return "\(self.name).\(self.deviceId)" } } diff --git a/swift/Sources/LibSignalClient/Aes256Ctr.swift b/swift/Sources/LibSignalClient/Aes256Ctr.swift index aaf7e0e8..a45c9f32 100644 --- a/swift/Sources/LibSignalClient/Aes256Ctr.swift +++ b/swift/Sources/LibSignalClient/Aes256Ctr.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class Aes256Ctr32: NativeHandleOwner { public static let keyLength: Int = 32 @@ -27,27 +27,31 @@ public class Aes256Ctr32: NativeHandleOwner { var nonceBufferWithoutCounter = SignalBorrowedBuffer(nonceBytes) nonceBufferWithoutCounter.length -= 4 var result: OpaquePointer? - try checkError(signal_aes256_ctr32_new(&result, - keyBuffer, - nonceBufferWithoutCounter, - initialCounter)) + try checkError(signal_aes256_ctr32_new( + &result, + keyBuffer, + nonceBufferWithoutCounter, + initialCounter + )) return result } } self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_aes256_ctr32_destroy(handle) } public func process(_ message: inout Data) throws { try withNativeHandle { nativeHandle in try message.withUnsafeMutableBytes { messageBytes in - try checkError(signal_aes256_ctr32_process(nativeHandle, - SignalBorrowedMutableBuffer(messageBytes), - 0, - UInt32(messageBytes.count))) + try checkError(signal_aes256_ctr32_process( + nativeHandle, + SignalBorrowedMutableBuffer(messageBytes), + 0, + UInt32(messageBytes.count) + )) } } } diff --git a/swift/Sources/LibSignalClient/Aes256Gcm.swift b/swift/Sources/LibSignalClient/Aes256Gcm.swift index 2eb18533..9cc3bfa4 100644 --- a/swift/Sources/LibSignalClient/Aes256Gcm.swift +++ b/swift/Sources/LibSignalClient/Aes256Gcm.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public struct Aes256GcmEncryptedData { public static let keyLength: Int = 32 @@ -33,19 +33,18 @@ public struct Aes256GcmEncryptedData { } public func concatenate() -> Data { - var result = Data(capacity: nonce.count + ciphertext.count + authenticationTag.count) - result += nonce - result += ciphertext - result += authenticationTag + var result = Data(capacity: nonce.count + self.ciphertext.count + self.authenticationTag.count) + result += self.nonce + result += self.ciphertext + result += self.authenticationTag return result } - public static func encrypt( + public static func encrypt( _ message: Data, - key: KeyBytes, - associatedData: AssociatedDataBytes - ) throws -> Self - where KeyBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes { + key: some ContiguousBytes, + associatedData: some ContiguousBytes + ) throws -> Self { var nonce = Data(count: Self.nonceLength) try nonce.withUnsafeMutableBytes { try fillRandom($0) } @@ -57,17 +56,16 @@ public struct Aes256GcmEncryptedData { return Self(nonce: nonce, ciphertext: ciphertext, authenticationTag: tag) } - public static func encrypt(_ message: Data, key: KeyBytes) throws -> Self { - return try encrypt(message, key: key, associatedData: []) + public static func encrypt(_ message: Data, key: some ContiguousBytes) throws -> Self { + return try self.encrypt(message, key: key, associatedData: []) } // Inlinable here specifically to avoid copying the ciphertext again if the struct is no longer used. @inlinable - public func decrypt( - key: KeyBytes, - associatedData: AssociatedDataBytes - ) throws -> Data - where KeyBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes { + public func decrypt( + key: some ContiguousBytes, + associatedData: some ContiguousBytes + ) throws -> Data { let cipher = try Aes256GcmDecryption(key: key, nonce: self.nonce, associatedData: associatedData) var plaintext = self.ciphertext try cipher.decrypt(&plaintext) @@ -78,26 +76,28 @@ public struct Aes256GcmEncryptedData { } @inlinable - public func decrypt(key: KeyBytes) throws -> Data { - return try decrypt(key: key, associatedData: []) + public func decrypt(key: some ContiguousBytes) throws -> Data { + return try self.decrypt(key: key, associatedData: []) } } /// Supports streamed encryption and custom nonces. Use Aes256GcmEncryptedData if you don't need either. public class Aes256GcmEncryption: NativeHandleOwner { - public convenience init( - key: KeyBytes, - nonce: NonceBytes, - associatedData: AssociatedDataBytes - ) throws where KeyBytes: ContiguousBytes, NonceBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes { + public convenience init( + key: some ContiguousBytes, + nonce: some ContiguousBytes, + associatedData: some ContiguousBytes + ) throws { let handle: OpaquePointer? = try key.withUnsafeBorrowedBuffer { keyBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in var result: OpaquePointer? - try checkError(signal_aes256_gcm_encryption_new(&result, - keyBuffer, - nonceBuffer, - adBuffer)) + try checkError(signal_aes256_gcm_encryption_new( + &result, + keyBuffer, + nonceBuffer, + adBuffer + )) return result } } @@ -105,17 +105,19 @@ public class Aes256GcmEncryption: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_aes256_gcm_encryption_destroy(handle) } public func encrypt(_ message: inout Data) throws { try withNativeHandle { nativeHandle in try message.withUnsafeMutableBytes { messageBytes in - try checkError(signal_aes256_gcm_encryption_update(nativeHandle, - SignalBorrowedMutableBuffer(messageBytes), - 0, - UInt32(messageBytes.count))) + try checkError(signal_aes256_gcm_encryption_update( + nativeHandle, + SignalBorrowedMutableBuffer(messageBytes), + 0, + UInt32(messageBytes.count) + )) } } } @@ -131,19 +133,21 @@ public class Aes256GcmEncryption: NativeHandleOwner { /// Supports streamed decryption. Use Aes256GcmEncryptedData if you don't need streamed decryption. public class Aes256GcmDecryption: NativeHandleOwner { - public convenience init( - key: KeyBytes, - nonce: NonceBytes, - associatedData: AssociatedDataBytes - ) throws where KeyBytes: ContiguousBytes, NonceBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes { + public convenience init( + key: some ContiguousBytes, + nonce: some ContiguousBytes, + associatedData: some ContiguousBytes + ) throws { let handle: OpaquePointer? = try key.withUnsafeBorrowedBuffer { keyBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in var result: OpaquePointer? - try checkError(signal_aes256_gcm_decryption_new(&result, - keyBuffer, - nonceBuffer, - adBuffer)) + try checkError(signal_aes256_gcm_decryption_new( + &result, + keyBuffer, + nonceBuffer, + adBuffer + )) return result } } @@ -151,28 +155,32 @@ public class Aes256GcmDecryption: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_aes256_gcm_decryption_destroy(handle) } public func decrypt(_ message: inout Data) throws { try withNativeHandle { nativeHandle in try message.withUnsafeMutableBytes { messageBytes in - try checkError(signal_aes256_gcm_decryption_update(nativeHandle, - SignalBorrowedMutableBuffer(messageBytes), - 0, - UInt32(messageBytes.count))) + try checkError(signal_aes256_gcm_decryption_update( + nativeHandle, + SignalBorrowedMutableBuffer(messageBytes), + 0, + UInt32(messageBytes.count) + )) } } } - public func verifyTag(_ tag: Bytes) throws -> Bool { + public func verifyTag(_ tag: some ContiguousBytes) throws -> Bool { return try withNativeHandle { nativeHandle in try tag.withUnsafeBorrowedBuffer { tagBuffer in var result = false - try checkError(signal_aes256_gcm_decryption_verify_tag(&result, - nativeHandle, - tagBuffer)) + try checkError(signal_aes256_gcm_decryption_verify_tag( + &result, + nativeHandle, + tagBuffer + )) return result } } diff --git a/swift/Sources/LibSignalClient/Aes256GcmSiv.swift b/swift/Sources/LibSignalClient/Aes256GcmSiv.swift index e981c08e..d987b5c9 100644 --- a/swift/Sources/LibSignalClient/Aes256GcmSiv.swift +++ b/swift/Sources/LibSignalClient/Aes256GcmSiv.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class Aes256GcmSiv: NativeHandleOwner { public convenience init(key bytes: Bytes) throws { @@ -16,29 +16,27 @@ public class Aes256GcmSiv: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_aes256_gcm_siv_destroy(handle) } - public func encrypt( - _ message: MessageBytes, - nonce: NonceBytes, - associatedData: AssociatedDataBytes - ) throws -> [UInt8] - where MessageBytes: ContiguousBytes, - NonceBytes: ContiguousBytes, - AssociatedDataBytes: ContiguousBytes { - + public func encrypt( + _ message: some ContiguousBytes, + nonce: some ContiguousBytes, + associatedData: some ContiguousBytes + ) throws -> [UInt8] { try withNativeHandle { nativeHandle in try message.withUnsafeBorrowedBuffer { messageBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in try invokeFnReturningArray { - signal_aes256_gcm_siv_encrypt($0, - nativeHandle, - messageBuffer, - nonceBuffer, - adBuffer) + signal_aes256_gcm_siv_encrypt( + $0, + nativeHandle, + messageBuffer, + nonceBuffer, + adBuffer + ) } } } @@ -46,29 +44,27 @@ public class Aes256GcmSiv: NativeHandleOwner { } } - public func decrypt ( - _ message: MessageBytes, - nonce: NonceBytes, - associatedData: AssociatedDataBytes) throws -> [UInt8] - where MessageBytes: ContiguousBytes, - NonceBytes: ContiguousBytes, - AssociatedDataBytes: ContiguousBytes { - + public func decrypt( + _ message: some ContiguousBytes, + nonce: some ContiguousBytes, + associatedData: some ContiguousBytes + ) throws -> [UInt8] { try withNativeHandle { nativeHandle in try message.withUnsafeBorrowedBuffer { messageBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in try invokeFnReturningArray { - signal_aes256_gcm_siv_decrypt($0, - nativeHandle, - messageBuffer, - nonceBuffer, - adBuffer) + signal_aes256_gcm_siv_decrypt( + $0, + nativeHandle, + messageBuffer, + nonceBuffer, + adBuffer + ) } } } } } } - } diff --git a/swift/Sources/LibSignalClient/AsyncUtils.swift b/swift/Sources/LibSignalClient/AsyncUtils.swift index 0cc745a7..a4c55502 100644 --- a/swift/Sources/LibSignalClient/AsyncUtils.swift +++ b/swift/Sources/LibSignalClient/AsyncUtils.swift @@ -28,12 +28,14 @@ extension Int32: Completable { extension UnsafeRawPointer: Completable { typealias PromiseCallback = SignalCPromiseRawPointer } + extension OpaquePointer: Completable { // C function pointer that takes two output arguments and one input argument. typealias PromiseCallback = (@convention(c) ( _ error: SignalFfiErrorRef?, _ value: UnsafePointer?, - _ context: UnsafeRawPointer?) -> Void)? + _ context: UnsafeRawPointer? + ) -> Void)? } extension SignalFfiCdsiLookupResponse: Completable { diff --git a/swift/Sources/LibSignalClient/Cds2.swift b/swift/Sources/LibSignalClient/Cds2.swift index 9fdeecea..e9a2e79c 100644 --- a/swift/Sources/LibSignalClient/Cds2.swift +++ b/swift/Sources/LibSignalClient/Cds2.swift @@ -3,24 +3,28 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi /// /// Cds2Client provides bindings to interact with Signal's v2 Contact Discovery Service. /// /// See ``SgxClient`` public class Cds2Client: SgxClient { - - public convenience init(mrenclave: MrenclaveBytes, attestationMessage: AttestationBytes, currentDate: Date) throws - where MrenclaveBytes: ContiguousBytes, AttestationBytes: ContiguousBytes { + public convenience init( + mrenclave: some ContiguousBytes, + attestationMessage: some ContiguousBytes, + currentDate: Date + ) throws { let handle: OpaquePointer? = try attestationMessage.withUnsafeBorrowedBuffer { attestationMessageBuffer in try mrenclave.withUnsafeBorrowedBuffer { mrenclaveBuffer in var result: OpaquePointer? - try checkError(signal_cds2_client_state_new(&result, - mrenclaveBuffer, - attestationMessageBuffer, - UInt64(currentDate.timeIntervalSince1970 * 1000))) + try checkError(signal_cds2_client_state_new( + &result, + mrenclaveBuffer, + attestationMessageBuffer, + UInt64(currentDate.timeIntervalSince1970 * 1000) + )) return result } } diff --git a/swift/Sources/LibSignalClient/DataStoreInMemory.swift b/swift/Sources/LibSignalClient/DataStoreInMemory.swift index 56aa6bcd..0ed924c1 100644 --- a/swift/Sources/LibSignalClient/DataStoreInMemory.swift +++ b/swift/Sources/LibSignalClient/DataStoreInMemory.swift @@ -27,8 +27,8 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre private var senderKeyMap: [SenderKeyName: SenderKeyRecord] = [:] public init() { - privateKey = IdentityKeyPair.generate() - registrationId = UInt32.random(in: 0...0x3FFF) + self.privateKey = IdentityKeyPair.generate() + self.registrationId = UInt32.random(in: 0...0x3FFF) } public init(identity: IdentityKeyPair, registrationId: UInt32) { @@ -37,15 +37,15 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre } open func identityKeyPair(context: StoreContext) throws -> IdentityKeyPair { - return privateKey + return self.privateKey } open func localRegistrationId(context: StoreContext) throws -> UInt32 { - return registrationId + return self.registrationId } open func saveIdentity(_ identity: IdentityKey, for address: ProtocolAddress, context: StoreContext) throws -> Bool { - if publicKeys.updateValue(identity, forKey: address) == nil { + if self.publicKeys.updateValue(identity, forKey: address) == nil { return false // newly created } else { return true @@ -61,7 +61,7 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre } open func identity(for address: ProtocolAddress, context: StoreContext) throws -> IdentityKey? { - return publicKeys[address] + return self.publicKeys[address] } open func loadPreKey(id: UInt32, context: StoreContext) throws -> PreKeyRecord { @@ -73,11 +73,11 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre } open func storePreKey(_ record: PreKeyRecord, id: UInt32, context: StoreContext) throws { - prekeyMap[id] = record + self.prekeyMap[id] = record } open func removePreKey(id: UInt32, context: StoreContext) throws { - prekeyMap.removeValue(forKey: id) + self.prekeyMap.removeValue(forKey: id) } open func loadSignedPreKey(id: UInt32, context: StoreContext) throws -> SignedPreKeyRecord { @@ -89,7 +89,7 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre } open func storeSignedPreKey(_ record: SignedPreKeyRecord, id: UInt32, context: StoreContext) throws { - signedPrekeyMap[id] = record + self.signedPrekeyMap[id] = record } open func loadKyberPreKey(id: UInt32, context: StoreContext) throws -> KyberPreKeyRecord { @@ -101,15 +101,15 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre } open func storeKyberPreKey(_ record: KyberPreKeyRecord, id: UInt32, context: StoreContext) throws { - kyberPrekeyMap[id] = record + self.kyberPrekeyMap[id] = record } open func markKyberPreKeyUsed(id: UInt32, context: StoreContext) throws { - kyberPrekeysUsed.insert(id) + self.kyberPrekeysUsed.insert(id) } open func loadSession(for address: ProtocolAddress, context: StoreContext) throws -> SessionRecord? { - return sessionMap[address] + return self.sessionMap[address] } open func loadExistingSessions(for addresses: [ProtocolAddress], context: StoreContext) throws -> [SessionRecord] { @@ -122,14 +122,14 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre } open func storeSession(_ record: SessionRecord, for address: ProtocolAddress, context: StoreContext) throws { - sessionMap[address] = record + self.sessionMap[address] = record } open func storeSenderKey(from sender: ProtocolAddress, distributionId: UUID, record: SenderKeyRecord, context: StoreContext) throws { - senderKeyMap[SenderKeyName(sender: sender, distributionId: distributionId)] = record + self.senderKeyMap[SenderKeyName(sender: sender, distributionId: distributionId)] = record } open func loadSenderKey(from sender: ProtocolAddress, distributionId: UUID, context: StoreContext) throws -> SenderKeyRecord? { - return senderKeyMap[SenderKeyName(sender: sender, distributionId: distributionId)] + return self.senderKeyMap[SenderKeyName(sender: sender, distributionId: distributionId)] } } diff --git a/swift/Sources/LibSignalClient/DataStoreProtocols.swift b/swift/Sources/LibSignalClient/DataStoreProtocols.swift index 5d05bd06..efcc5945 100644 --- a/swift/Sources/LibSignalClient/DataStoreProtocols.swift +++ b/swift/Sources/LibSignalClient/DataStoreProtocols.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public enum Direction { case sending diff --git a/swift/Sources/LibSignalClient/DataStoreUtils.swift b/swift/Sources/LibSignalClient/DataStoreUtils.swift index ab4d3a76..bbfd9ec0 100644 --- a/swift/Sources/LibSignalClient/DataStoreUtils.swift +++ b/swift/Sources/LibSignalClient/DataStoreUtils.swift @@ -3,12 +3,14 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi internal func withIdentityKeyStore(_ store: IdentityKeyStore, _ context: StoreContext, _ body: (UnsafePointer) throws -> Result) throws -> Result { - func ffiShimGetIdentityKeyPair(storeCtx: UnsafeMutableRawPointer?, - keyp: UnsafeMutablePointer?) -> Int32 { + func ffiShimGetIdentityKeyPair( + storeCtx: UnsafeMutableRawPointer?, + keyp: UnsafeMutablePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var privateKey = try store.identityKeyPair(context: context).privateKey @@ -17,8 +19,10 @@ internal func withIdentityKeyStore(_ store: IdentityKeyStore, _ context: } } - func ffiShimGetLocalRegistrationId(storeCtx: UnsafeMutableRawPointer?, - idp: UnsafeMutablePointer?) -> Int32 { + func ffiShimGetLocalRegistrationId( + storeCtx: UnsafeMutableRawPointer?, + idp: UnsafeMutablePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in let id = try store.localRegistrationId(context: context) @@ -27,9 +31,11 @@ internal func withIdentityKeyStore(_ store: IdentityKeyStore, _ context: } } - func ffiShimSaveIdentity(storeCtx: UnsafeMutableRawPointer?, - address: OpaquePointer?, - public_key: OpaquePointer?) -> Int32 { + func ffiShimSaveIdentity( + storeCtx: UnsafeMutableRawPointer?, + address: OpaquePointer?, + public_key: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var address = ProtocolAddress(borrowing: address) @@ -46,9 +52,11 @@ internal func withIdentityKeyStore(_ store: IdentityKeyStore, _ context: } } - func ffiShimGetIdentity(storeCtx: UnsafeMutableRawPointer?, - public_key: UnsafeMutablePointer?, - address: OpaquePointer?) -> Int32 { + func ffiShimGetIdentity( + storeCtx: UnsafeMutableRawPointer?, + public_key: UnsafeMutablePointer?, + address: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var address = ProtocolAddress(borrowing: address) @@ -63,10 +71,12 @@ internal func withIdentityKeyStore(_ store: IdentityKeyStore, _ context: } } - func ffiShimIsTrustedIdentity(storeCtx: UnsafeMutableRawPointer?, - address: OpaquePointer?, - public_key: OpaquePointer?, - raw_direction: UInt32) -> Int32 { + func ffiShimIsTrustedIdentity( + storeCtx: UnsafeMutableRawPointer?, + address: OpaquePointer?, + public_key: OpaquePointer?, + raw_direction: UInt32 + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var address = ProtocolAddress(borrowing: address) @@ -96,15 +106,18 @@ internal func withIdentityKeyStore(_ store: IdentityKeyStore, _ context: get_local_registration_id: ffiShimGetLocalRegistrationId, save_identity: ffiShimSaveIdentity, get_identity: ffiShimGetIdentity, - is_trusted_identity: ffiShimIsTrustedIdentity) + is_trusted_identity: ffiShimIsTrustedIdentity + ) return try body(&ffiStore) } } internal func withPreKeyStore(_ store: PreKeyStore, _ context: StoreContext, _ body: (UnsafePointer) throws -> Result) throws -> Result { - func ffiShimStorePreKey(storeCtx: UnsafeMutableRawPointer?, - id: UInt32, - record: OpaquePointer?) -> Int32 { + func ffiShimStorePreKey( + storeCtx: UnsafeMutableRawPointer?, + id: UInt32, + record: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var record = PreKeyRecord(borrowing: record) @@ -114,9 +127,11 @@ internal func withPreKeyStore(_ store: PreKeyStore, _ context: StoreCont } } - func ffiShimLoadPreKey(storeCtx: UnsafeMutableRawPointer?, - recordp: UnsafeMutablePointer?, - id: UInt32) -> Int32 { + func ffiShimLoadPreKey( + storeCtx: UnsafeMutableRawPointer?, + recordp: UnsafeMutablePointer?, + id: UInt32 + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var record = try store.loadPreKey(id: id, context: context) @@ -125,8 +140,10 @@ internal func withPreKeyStore(_ store: PreKeyStore, _ context: StoreCont } } - func ffiShimRemovePreKey(storeCtx: UnsafeMutableRawPointer?, - id: UInt32) -> Int32 { + func ffiShimRemovePreKey( + storeCtx: UnsafeMutableRawPointer?, + id: UInt32 + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in try store.removePreKey(id: id, context: context) @@ -139,15 +156,18 @@ internal func withPreKeyStore(_ store: PreKeyStore, _ context: StoreCont ctx: $0, load_pre_key: ffiShimLoadPreKey, store_pre_key: ffiShimStorePreKey, - remove_pre_key: ffiShimRemovePreKey) + remove_pre_key: ffiShimRemovePreKey + ) return try body(&ffiStore) } } internal func withSignedPreKeyStore(_ store: SignedPreKeyStore, _ context: StoreContext, _ body: (UnsafePointer) throws -> Result) throws -> Result { - func ffiShimStoreSignedPreKey(storeCtx: UnsafeMutableRawPointer?, - id: UInt32, - record: OpaquePointer?) -> Int32 { + func ffiShimStoreSignedPreKey( + storeCtx: UnsafeMutableRawPointer?, + id: UInt32, + record: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SignedPreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var record = SignedPreKeyRecord(borrowing: record) @@ -157,9 +177,11 @@ internal func withSignedPreKeyStore(_ store: SignedPreKeyStore, _ contex } } - func ffiShimLoadSignedPreKey(storeCtx: UnsafeMutableRawPointer?, - recordp: UnsafeMutablePointer?, - id: UInt32) -> Int32 { + func ffiShimLoadSignedPreKey( + storeCtx: UnsafeMutableRawPointer?, + recordp: UnsafeMutablePointer?, + id: UInt32 + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SignedPreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var record = try store.loadSignedPreKey(id: id, context: context) @@ -172,15 +194,18 @@ internal func withSignedPreKeyStore(_ store: SignedPreKeyStore, _ contex var ffiStore = SignalSignedPreKeyStore( ctx: $0, load_signed_pre_key: ffiShimLoadSignedPreKey, - store_signed_pre_key: ffiShimStoreSignedPreKey) + store_signed_pre_key: ffiShimStoreSignedPreKey + ) return try body(&ffiStore) } } internal func withKyberPreKeyStore(_ store: KyberPreKeyStore, _ context: StoreContext, _ body: (UnsafePointer) throws -> Result) throws -> Result { - func ffiShimStoreKyberPreKey(storeCtx: UnsafeMutableRawPointer?, - id: UInt32, - record: OpaquePointer?) -> Int32 { + func ffiShimStoreKyberPreKey( + storeCtx: UnsafeMutableRawPointer?, + id: UInt32, + record: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var record = KyberPreKeyRecord(borrowing: record) @@ -190,9 +215,11 @@ internal func withKyberPreKeyStore(_ store: KyberPreKeyStore, _ context: } } - func ffiShimLoadKyberPreKey(storeCtx: UnsafeMutableRawPointer?, - recordp: UnsafeMutablePointer?, - id: UInt32) -> Int32 { + func ffiShimLoadKyberPreKey( + storeCtx: UnsafeMutableRawPointer?, + recordp: UnsafeMutablePointer?, + id: UInt32 + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var record = try store.loadKyberPreKey(id: id, context: context) @@ -201,8 +228,10 @@ internal func withKyberPreKeyStore(_ store: KyberPreKeyStore, _ context: } } - func ffiShimMarkKyberPreKeyUsed(storeCtx: UnsafeMutableRawPointer?, - id: UInt32) -> Int32 { + func ffiShimMarkKyberPreKeyUsed( + storeCtx: UnsafeMutableRawPointer?, + id: UInt32 + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in try store.markKyberPreKeyUsed(id: id, context: context) @@ -215,15 +244,18 @@ internal func withKyberPreKeyStore(_ store: KyberPreKeyStore, _ context: ctx: $0, load_kyber_pre_key: ffiShimLoadKyberPreKey, store_kyber_pre_key: ffiShimStoreKyberPreKey, - mark_kyber_pre_key_used: ffiShimMarkKyberPreKeyUsed) + mark_kyber_pre_key_used: ffiShimMarkKyberPreKeyUsed + ) return try body(&ffiStore) } } internal func withSessionStore(_ store: SessionStore, _ context: StoreContext, _ body: (UnsafePointer) throws -> Result) throws -> Result { - func ffiShimStoreSession(storeCtx: UnsafeMutableRawPointer?, - address: OpaquePointer?, - record: OpaquePointer?) -> Int32 { + func ffiShimStoreSession( + storeCtx: UnsafeMutableRawPointer?, + address: OpaquePointer?, + record: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SessionStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var address = ProtocolAddress(borrowing: address) @@ -235,9 +267,11 @@ internal func withSessionStore(_ store: SessionStore, _ context: StoreCo } } - func ffiShimLoadSession(storeCtx: UnsafeMutableRawPointer?, - recordp: UnsafeMutablePointer?, - address: OpaquePointer?) -> Int32 { + func ffiShimLoadSession( + storeCtx: UnsafeMutableRawPointer?, + recordp: UnsafeMutablePointer?, + address: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SessionStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var address = ProtocolAddress(borrowing: address) @@ -255,16 +289,19 @@ internal func withSessionStore(_ store: SessionStore, _ context: StoreCo var ffiStore = SignalSessionStore( ctx: $0, load_session: ffiShimLoadSession, - store_session: ffiShimStoreSession) + store_session: ffiShimStoreSession + ) return try body(&ffiStore) } } internal func withSenderKeyStore(_ store: SenderKeyStore, _ context: StoreContext, _ body: (UnsafePointer) throws -> Result) rethrows -> Result { - func ffiShimStoreSenderKey(storeCtx: UnsafeMutableRawPointer?, - sender: OpaquePointer?, - distributionId: UnsafePointer?, - record: OpaquePointer?) -> Int32 { + func ffiShimStoreSenderKey( + storeCtx: UnsafeMutableRawPointer?, + sender: OpaquePointer?, + distributionId: UnsafePointer?, + record: OpaquePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SenderKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var sender = ProtocolAddress(borrowing: sender) @@ -277,10 +314,12 @@ internal func withSenderKeyStore(_ store: SenderKeyStore, _ context: Sto } } - func ffiShimLoadSenderKey(storeCtx: UnsafeMutableRawPointer?, - recordp: UnsafeMutablePointer?, - sender: OpaquePointer?, - distributionId: UnsafePointer?) -> Int32 { + func ffiShimLoadSenderKey( + storeCtx: UnsafeMutableRawPointer?, + recordp: UnsafeMutablePointer?, + sender: OpaquePointer?, + distributionId: UnsafePointer? + ) -> Int32 { let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SenderKeyStore, StoreContext)>.self) return storeContext.pointee.catchCallbackErrors { store, context in var sender = ProtocolAddress(borrowing: sender) @@ -299,7 +338,8 @@ internal func withSenderKeyStore(_ store: SenderKeyStore, _ context: Sto var ffiStore = SignalSenderKeyStore( ctx: $0, load_sender_key: ffiShimLoadSenderKey, - store_sender_key: ffiShimStoreSenderKey) + store_sender_key: ffiShimStoreSenderKey + ) return try body(&ffiStore) } } diff --git a/swift/Sources/LibSignalClient/DeviceTransfer.swift b/swift/Sources/LibSignalClient/DeviceTransfer.swift index 69ba71e5..92b96c9d 100644 --- a/swift/Sources/LibSignalClient/DeviceTransfer.swift +++ b/swift/Sources/LibSignalClient/DeviceTransfer.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public enum KeyFormat: UInt8, CaseIterable { // PKCS#8 is the default for backward compatibility @@ -30,13 +30,15 @@ public struct DeviceTransferKey { } public func generateCertificate(_ name: String, _ daysTilExpire: Int) -> [UInt8] { - return privateKey.withUnsafeBorrowedBuffer { privateKeyBuffer in + return self.privateKey.withUnsafeBorrowedBuffer { privateKeyBuffer in failOnError { try invokeFnReturningArray { - signal_device_transfer_generate_certificate($0, - privateKeyBuffer, - name, - UInt32(daysTilExpire)) + signal_device_transfer_generate_certificate( + $0, + privateKeyBuffer, + name, + UInt32(daysTilExpire) + ) } } } diff --git a/swift/Sources/LibSignalClient/Error.swift b/swift/Sources/LibSignalClient/Error.swift index b3d65a85..34cf591b 100644 --- a/swift/Sources/LibSignalClient/Error.swift +++ b/swift/Sources/LibSignalClient/Error.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi #if canImport(SignalCoreKit) import SignalCoreKit diff --git a/swift/Sources/LibSignalClient/Fingerprint.swift b/swift/Sources/LibSignalClient/Fingerprint.swift index bce9abff..5844c093 100644 --- a/swift/Sources/LibSignalClient/Fingerprint.swift +++ b/swift/Sources/LibSignalClient/Fingerprint.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public struct DisplayableFingerprint { public let formatted: String @@ -18,7 +18,7 @@ public struct ScannableFingerprint { /// Throws an error if `other` is not a valid fingerprint encoding, or if it uses an /// incompatible encoding version. public func compare(againstEncoding other: Other) throws -> Bool { - var result: Bool = false + var result = false try encoding.withUnsafeBorrowedBuffer { encodingBuffer in try other.withUnsafeBorrowedBuffer { otherBuffer in try checkError(signal_fingerprint_compare(&result, encodingBuffer, otherBuffer)) @@ -45,21 +45,26 @@ public struct NumericFingerprintGenerator { self.iterations = iterations } - public func create(version: Int, - localIdentifier: LocalBytes, - localKey: PublicKey, - remoteIdentifier: RemoteBytes, - remoteKey: PublicKey) throws -> Fingerprint - where LocalBytes: ContiguousBytes, RemoteBytes: ContiguousBytes { + public func create( + version: Int, + localIdentifier: some ContiguousBytes, + localKey: PublicKey, + remoteIdentifier: some ContiguousBytes, + remoteKey: PublicKey + ) throws -> Fingerprint { var obj: OpaquePointer? try withNativeHandles(localKey, remoteKey) { localKeyHandle, remoteKeyHandle in try localIdentifier.withUnsafeBorrowedBuffer { localBuffer in try remoteIdentifier.withUnsafeBorrowedBuffer { remoteBuffer in - try checkError(signal_fingerprint_new(&obj, UInt32(iterations), UInt32(version), - localBuffer, - localKeyHandle, - remoteBuffer, - remoteKeyHandle)) + try checkError(signal_fingerprint_new( + &obj, + UInt32(self.iterations), + UInt32(version), + localBuffer, + localKeyHandle, + remoteBuffer, + remoteKeyHandle + )) } } } diff --git a/swift/Sources/LibSignalClient/HsmEnclave.swift b/swift/Sources/LibSignalClient/HsmEnclave.swift index bba07886..db218ef7 100644 --- a/swift/Sources/LibSignalClient/HsmEnclave.swift +++ b/swift/Sources/LibSignalClient/HsmEnclave.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi /// The HsmCodeHashList is a wrapper around a flat UInt8 array to make it more /// convenient to send code hashes to initialize the client. @@ -15,7 +15,7 @@ public struct HsmCodeHashList { var codeHashes: [UInt8] public init() { - codeHashes = [] + self.codeHashes = [] } public mutating func append(_ codeHash: [UInt8]) throws { @@ -23,11 +23,11 @@ public struct HsmCodeHashList { fatalError("code hash length must be 32") } - codeHashes.append(contentsOf: codeHash) + self.codeHashes.append(contentsOf: codeHash) } func flatten() -> [UInt8] { - return codeHashes + return self.codeHashes } } @@ -48,16 +48,17 @@ public struct HsmCodeHashList { /// which decrypts and verifies it, passing the plaintext back to the client for processing. /// public class HsmEnclaveClient: NativeHandleOwner { - public convenience init(publicKey: Bytes, codeHashes: HsmCodeHashList) throws { let codeHashBytes = codeHashes.flatten() let handle: OpaquePointer? = try publicKey.withUnsafeBorrowedBuffer { publicKeyBuffer in try codeHashBytes.withUnsafeBorrowedBuffer { codeHashBuffer in var result: OpaquePointer? - try checkError(signal_hsm_enclave_client_new(&result, - publicKeyBuffer, - codeHashBuffer)) + try checkError(signal_hsm_enclave_client_new( + &result, + publicKeyBuffer, + codeHashBuffer + )) return result } } @@ -65,7 +66,7 @@ public class HsmEnclaveClient: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_hsm_enclave_client_destroy(handle) } diff --git a/swift/Sources/LibSignalClient/Ias.swift b/swift/Sources/LibSignalClient/Ias.swift index 61ec5b5c..85c2df97 100644 --- a/swift/Sources/LibSignalClient/Ias.swift +++ b/swift/Sources/LibSignalClient/Ias.swift @@ -7,7 +7,6 @@ import Foundation import SignalFfi public enum Ias { - public static func verify< Signature: ContiguousBytes, Body: ContiguousBytes, diff --git a/swift/Sources/LibSignalClient/IdentityKey.swift b/swift/Sources/LibSignalClient/IdentityKey.swift index 476178d3..9edf22f7 100644 --- a/swift/Sources/LibSignalClient/IdentityKey.swift +++ b/swift/Sources/LibSignalClient/IdentityKey.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public struct IdentityKey: Equatable { public let publicKey: PublicKey @@ -14,22 +14,21 @@ public struct IdentityKey: Equatable { } public init(bytes: Bytes) throws { - publicKey = try PublicKey(bytes) + self.publicKey = try PublicKey(bytes) } public func serialize() -> [UInt8] { - return publicKey.serialize() + return self.publicKey.serialize() } public func verifyAlternateIdentity(_ other: IdentityKey, signature: Bytes) throws -> Bool { - var result: Bool = false + var result = false try withNativeHandles(publicKey, other.publicKey) { selfHandle, otherHandle in try signature.withUnsafeBorrowedBuffer { signatureBuffer in try checkError(signal_identitykey_verify_alternate_identity(&result, selfHandle, otherHandle, signatureBuffer)) } } return result - } } @@ -50,8 +49,8 @@ public struct IdentityKeyPair { try checkError(signal_identitykeypair_deserialize(&privkeyPtr, &pubkeyPtr, $0)) } - publicKey = PublicKey(owned: pubkeyPtr!) - privateKey = PrivateKey(owned: privkeyPtr!) + self.publicKey = PublicKey(owned: pubkeyPtr!) + self.privateKey = PrivateKey(owned: privkeyPtr!) } public init(publicKey: PublicKey, privateKey: PrivateKey) { @@ -60,7 +59,7 @@ public struct IdentityKeyPair { } public func serialize() -> [UInt8] { - return withNativeHandles(publicKey, privateKey) { publicKey, privateKey in + return withNativeHandles(self.publicKey, self.privateKey) { publicKey, privateKey in failOnError { try invokeFnReturningArray { signal_identitykeypair_serialize($0, publicKey, privateKey) @@ -70,11 +69,11 @@ public struct IdentityKeyPair { } public var identityKey: IdentityKey { - return IdentityKey(publicKey: publicKey) + return IdentityKey(publicKey: self.publicKey) } public func signAlternateIdentity(_ other: IdentityKey) -> [UInt8] { - return withNativeHandles(publicKey, privateKey, other.publicKey) { publicKey, privateKey, other in + return withNativeHandles(self.publicKey, self.privateKey, other.publicKey) { publicKey, privateKey, other in failOnError { try invokeFnReturningArray { signal_identitykeypair_sign_alternate_identity($0, publicKey, privateKey, other) diff --git a/swift/Sources/LibSignalClient/IncrementalMac.swift b/swift/Sources/LibSignalClient/IncrementalMac.swift index f986bd07..9d06d3c2 100644 --- a/swift/Sources/LibSignalClient/IncrementalMac.swift +++ b/swift/Sources/LibSignalClient/IncrementalMac.swift @@ -23,7 +23,7 @@ public enum SizeChoice { } public class IncrementalMacContext: NativeHandleOwner { - private var _digest: Data = Data() + private var _digest: Data = .init() public convenience init(key: Key, chunkSize sizeChoice: SizeChoice) throws { let chunkSize = try sizeChoice.sizeInBytes() @@ -35,14 +35,14 @@ public class IncrementalMacContext: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_incremental_mac_destroy(handle) } public func update(_ bytes: Bytes) throws { let digest = try bytes.withUnsafeBorrowedBuffer { bytesPtr in - return try invokeFnReturningArray { - return signal_incremental_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length)) + try invokeFnReturningArray { + signal_incremental_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length)) } } self._digest.append(contentsOf: digest) @@ -50,7 +50,7 @@ public class IncrementalMacContext: NativeHandleOwner { public func finalize() throws -> [UInt8] { let digest = try invokeFnReturningArray { - return signal_incremental_mac_finalize($0, unsafeNativeHandle) + signal_incremental_mac_finalize($0, unsafeNativeHandle) } self._digest.append(contentsOf: digest) return Array(self._digest) @@ -73,14 +73,14 @@ public class ValidatingMacContext: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_validating_mac_destroy(handle) } public func update(_ bytes: Bytes) throws -> UInt32 { let validBytesCount = try bytes.withUnsafeBorrowedBuffer { bytesPtr in - return try invokeFnReturningInteger { - return signal_validating_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length)) + try invokeFnReturningInteger { + signal_validating_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length)) } } if validBytesCount < 0 { @@ -91,7 +91,7 @@ public class ValidatingMacContext: NativeHandleOwner { public func finalize() throws -> UInt32 { let validBytesCount = try invokeFnReturningInteger { - return signal_validating_mac_finalize($0, unsafeNativeHandle) + signal_validating_mac_finalize($0, unsafeNativeHandle) } if validBytesCount < 0 { throw SignalError.verificationFailed("Bad incremental MAC (finalize)") diff --git a/swift/Sources/LibSignalClient/IoProtocols.swift b/swift/Sources/LibSignalClient/IoProtocols.swift index 8c01d316..052f38f4 100644 --- a/swift/Sources/LibSignalClient/IoProtocols.swift +++ b/swift/Sources/LibSignalClient/IoProtocols.swift @@ -56,16 +56,16 @@ public class SignalInputStreamAdapter: SignalInputStream where Inner: Col } public func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int { - let amount = min(buffer.count, inner.count) - buffer.copyBytes(from: inner.prefix(amount)) - inner = inner.dropFirst(amount) + let amount = min(buffer.count, self.inner.count) + buffer.copyBytes(from: self.inner.prefix(amount)) + self.inner = self.inner.dropFirst(amount) return amount } public func skip(by amount: UInt64) throws { - if amount > UInt64(inner.count) { + if amount > UInt64(self.inner.count) { throw SignalInputStreamError.unexpectedEof } - inner = inner.dropFirst(Int(amount)) + self.inner = self.inner.dropFirst(Int(amount)) } } diff --git a/swift/Sources/LibSignalClient/IoUtils.swift b/swift/Sources/LibSignalClient/IoUtils.swift index e2810bc2..f600f2f0 100644 --- a/swift/Sources/LibSignalClient/IoUtils.swift +++ b/swift/Sources/LibSignalClient/IoUtils.swift @@ -7,10 +7,12 @@ import Foundation import SignalFfi internal func withInputStream(_ stream: SignalInputStream, _ body: (UnsafePointer) throws -> Result) throws -> Result { - func ffiShimRead(stream_ctx: UnsafeMutableRawPointer?, - pBuf: UnsafeMutablePointer?, - bufLen: Int, - pAmountRead: UnsafeMutablePointer?) -> Int32 { + func ffiShimRead( + stream_ctx: UnsafeMutableRawPointer?, + pBuf: UnsafeMutablePointer?, + bufLen: Int, + pAmountRead: UnsafeMutablePointer? + ) -> Int32 { let streamContext = stream_ctx!.assumingMemoryBound(to: ErrorHandlingContext.self) return streamContext.pointee.catchCallbackErrors { stream in let buf = UnsafeMutableRawBufferPointer(start: pBuf, count: bufLen) @@ -32,7 +34,8 @@ internal func withInputStream(_ stream: SignalInputStream, _ body: (Unsa var ffiStream = SignalFfi.SignalInputStream( ctx: $0, read: ffiShimRead as SignalRead, - skip: ffiShimSkip as SignalSkip) + skip: ffiShimSkip as SignalSkip + ) return try body(&ffiStream) } } diff --git a/swift/Sources/LibSignalClient/Kdf.swift b/swift/Sources/LibSignalClient/Kdf.swift index cae22b15..1fa983e3 100644 --- a/swift/Sources/LibSignalClient/Kdf.swift +++ b/swift/Sources/LibSignalClient/Kdf.swift @@ -3,24 +3,27 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi -public func hkdf(outputLength: Int, - inputKeyMaterial: InputBytes, - salt: SaltBytes, - info: InfoBytes) throws -> [UInt8] -where InputBytes: ContiguousBytes, SaltBytes: ContiguousBytes, InfoBytes: ContiguousBytes { +public func hkdf( + outputLength: Int, + inputKeyMaterial: some ContiguousBytes, + salt: some ContiguousBytes, + info: some ContiguousBytes +) throws -> [UInt8] { var output = Array(repeating: UInt8(0x00), count: outputLength) try output.withUnsafeMutableBytes { outputBuffer in try inputKeyMaterial.withUnsafeBorrowedBuffer { inputBuffer in try salt.withUnsafeBorrowedBuffer { saltBuffer in try info.withUnsafeBorrowedBuffer { infoBuffer in - try checkError(signal_hkdf_derive(.init(outputBuffer), - inputBuffer, - infoBuffer, - saltBuffer)) + try checkError(signal_hkdf_derive( + .init(outputBuffer), + inputBuffer, + infoBuffer, + saltBuffer + )) } } } @@ -30,15 +33,18 @@ where InputBytes: ContiguousBytes, SaltBytes: ContiguousBytes, InfoBytes: Contig } @available(*, deprecated, message: "Remove the 'version' parameter for standard HKDF behavior") -public func hkdf(outputLength: Int, - version: UInt32, - inputKeyMaterial: InputBytes, - salt: SaltBytes, - info: InfoBytes) throws -> [UInt8] -where InputBytes: ContiguousBytes, SaltBytes: ContiguousBytes, InfoBytes: ContiguousBytes { +public func hkdf( + outputLength: Int, + version: UInt32, + inputKeyMaterial: some ContiguousBytes, + salt: some ContiguousBytes, + info: some ContiguousBytes +) throws -> [UInt8] { precondition(version == 3, "HKDF versions other than 3 are no longer supported") - return try hkdf(outputLength: outputLength, - inputKeyMaterial: inputKeyMaterial, - salt: salt, - info: info) + return try hkdf( + outputLength: outputLength, + inputKeyMaterial: inputKeyMaterial, + salt: salt, + info: info + ) } diff --git a/swift/Sources/LibSignalClient/Kem.swift b/swift/Sources/LibSignalClient/Kem.swift index 4edb31c2..b7626c04 100644 --- a/swift/Sources/LibSignalClient/Kem.swift +++ b/swift/Sources/LibSignalClient/Kem.swift @@ -3,11 +3,10 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class KEMKeyPair: ClonableHandleOwner { - public static func generate() -> KEMKeyPair { return failOnError { try invokeFnReturningNativeHandle { @@ -16,11 +15,11 @@ public class KEMKeyPair: ClonableHandleOwner { } } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_kyber_key_pair_clone(&newHandle, currentHandle) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_kyber_key_pair_destroy(handle) } @@ -55,11 +54,11 @@ public class KEMPublicKey: ClonableHandleOwner { self.init(owned: handle!) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_kyber_public_key_clone(&newHandle, currentHandle) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_kyber_public_key_destroy(handle) } @@ -96,11 +95,11 @@ public class KEMSecretKey: ClonableHandleOwner { self.init(owned: handle!) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_kyber_secret_key_clone(&newHandle, currentHandle) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_kyber_secret_key_destroy(handle) } diff --git a/swift/Sources/LibSignalClient/Media.swift b/swift/Sources/LibSignalClient/Media.swift index e247196c..74802b50 100644 --- a/swift/Sources/LibSignalClient/Media.swift +++ b/swift/Sources/LibSignalClient/Media.swift @@ -74,11 +74,11 @@ public func sanitizeWebp(input: SignalInputStream, length ignored: UInt64) throw } public class SanitizedMetadata: ClonableHandleOwner { - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_sanitized_metadata_clone(&newHandle, currentHandle) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_sanitized_metadata_destroy(handle) } diff --git a/swift/Sources/LibSignalClient/MessageBackup.swift b/swift/Sources/LibSignalClient/MessageBackup.swift index 699e2209..f4d38b77 100644 --- a/swift/Sources/LibSignalClient/MessageBackup.swift +++ b/swift/Sources/LibSignalClient/MessageBackup.swift @@ -7,26 +7,25 @@ import Foundation import SignalFfi public class MessageBackupKey: NativeHandleOwner { - public convenience init(masterKey: [UInt8], aci: Aci) throws { - let masterKey = try ByteArray(newContents: masterKey, expectedLength: 32) - let handle = try masterKey.withUnsafePointerToSerialized { masterKey in - try aci.withPointerToFixedWidthBinary { aci in - var outputHandle: OpaquePointer? - try checkError(signal_message_backup_key_new(&outputHandle, masterKey, aci)) - return outputHandle - } + public convenience init(masterKey: [UInt8], aci: Aci) throws { + let masterKey = try ByteArray(newContents: masterKey, expectedLength: 32) + let handle = try masterKey.withUnsafePointerToSerialized { masterKey in + try aci.withPointerToFixedWidthBinary { aci in + var outputHandle: OpaquePointer? + try checkError(signal_message_backup_key_new(&outputHandle, masterKey, aci)) + return outputHandle + } + } + self.init(owned: handle!) } - self.init(owned: handle!) - } - internal required init(owned handle: OpaquePointer) { - super.init(owned: handle) - } - - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { - signal_message_backup_key_destroy(handle) - } + internal required init(owned handle: OpaquePointer) { + super.init(owned: handle) + } + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + signal_message_backup_key_destroy(handle) + } } /// Validates a message backup file. @@ -42,58 +41,58 @@ public class MessageBackupKey: NativeHandleOwner { /// - `SignalError.ioError`: If an IO error on the input occurs. /// - `MessageBackupValidationError`: If validation fails public func validateMessageBackup( - key: MessageBackupKey, length: UInt64, makeStream: () -> SignalInputStream + key: MessageBackupKey, length: UInt64, makeStream: () -> SignalInputStream ) throws -> MessageBackupUnknownFields { - let outcome: ValidationOutcome = try withInputStream(makeStream()) { firstInput in - try withInputStream(makeStream()) { secondInput in - try key.withNativeHandle { key in - try invokeFnReturningNativeHandle { - signal_message_backup_validator_validate($0, key, firstInput, secondInput, length) + let outcome: ValidationOutcome = try withInputStream(makeStream()) { firstInput in + try withInputStream(makeStream()) { secondInput in + try key.withNativeHandle { key in + try invokeFnReturningNativeHandle { + signal_message_backup_validator_validate($0, key, firstInput, secondInput, length) + } + } } - } } - } - if let errorMessage = outcome.errorMessage { - throw MessageBackupValidationError(errorMessage: errorMessage, unknownFields: outcome.unknownFields) - } - return outcome.unknownFields + if let errorMessage = outcome.errorMessage { + throw MessageBackupValidationError(errorMessage: errorMessage, unknownFields: outcome.unknownFields) + } + return outcome.unknownFields } /// The outcome of a failed validation attempt. public struct MessageBackupValidationError: Error { - /// The human-readable error that caused validation to fail. - public var errorMessage: String - /// Unknown fields encountered while validating. - public var unknownFields: MessageBackupUnknownFields + /// The human-readable error that caused validation to fail. + public var errorMessage: String + /// Unknown fields encountered while validating. + public var unknownFields: MessageBackupUnknownFields } /// Unknown fields encountered while validating. public struct MessageBackupUnknownFields { - public let fields: [String] + public let fields: [String] } private class ValidationOutcome: NativeHandleOwner { - public var unknownFields: MessageBackupUnknownFields { - let fields = failOnError { - try self.withNativeHandle { result in - try invokeFnReturningStringArray { - signal_message_backup_validation_outcome_get_unknown_fields($0, result) + public var unknownFields: MessageBackupUnknownFields { + let fields = failOnError { + try self.withNativeHandle { result in + try invokeFnReturningStringArray { + signal_message_backup_validation_outcome_get_unknown_fields($0, result) + } + } } - } + return MessageBackupUnknownFields(fields: fields) } - return MessageBackupUnknownFields(fields: fields) - } - public var errorMessage: String? { - try! self.withNativeHandle { result in - try invokeFnReturningOptionalString { - signal_message_backup_validation_outcome_get_error_message($0, result) - } + public var errorMessage: String? { + try! self.withNativeHandle { result in + try invokeFnReturningOptionalString { + signal_message_backup_validation_outcome_get_error_message($0, result) + } + } } - } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { - signal_message_backup_validation_outcome_destroy(handle) - } + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + signal_message_backup_validation_outcome_destroy(handle) + } } diff --git a/swift/Sources/LibSignalClient/NativeHandleOwner.swift b/swift/Sources/LibSignalClient/NativeHandleOwner.swift index 257cc0c3..e9fe50a6 100644 --- a/swift/Sources/LibSignalClient/NativeHandleOwner.swift +++ b/swift/Sources/LibSignalClient/NativeHandleOwner.swift @@ -16,7 +16,7 @@ public class NativeHandleOwner { /// You should probably use `withNativeHandle(_:)` /// unless you can't use block scoping to keep the owner (`self`) alive. internal var unsafeNativeHandle: OpaquePointer? { - switch handle { + switch self.handle { case nil: return nil case .borrowed(let handle)?: @@ -26,7 +26,7 @@ public class NativeHandleOwner { } } - required internal init(owned handle: OpaquePointer) { + internal required init(owned handle: OpaquePointer) { self.handle = .owned(handle) } @@ -34,7 +34,7 @@ public class NativeHandleOwner { self.handle = handle.map { .borrowed($0) } } - internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + internal class func destroyNativeHandle(_: OpaquePointer) -> SignalFfiErrorRef? { fatalError("must be implemented by subclasses") } @@ -61,7 +61,7 @@ public class NativeHandleOwner { } @available(*, unavailable, message: "use the method form instead") -internal func withNativeHandle(_ a: NativeHandleOwner, _ callback: (OpaquePointer?) throws -> Result) rethrows -> Result { +internal func withNativeHandle(_: NativeHandleOwner, _: (OpaquePointer?) throws -> Result) rethrows -> Result { fatalError() } @@ -96,11 +96,11 @@ internal func withNativeHandles(_ a: NativeHandleOwner, _ b: NativeHandl } public class ClonableHandleOwner: NativeHandleOwner { - required internal init(owned handle: OpaquePointer) { + internal required init(owned handle: OpaquePointer) { super.init(owned: handle) } - internal override init(borrowing handle: OpaquePointer?) { + override internal init(borrowing handle: OpaquePointer?) { super.init(borrowing: handle) } diff --git a/swift/Sources/LibSignalClient/Net.swift b/swift/Sources/LibSignalClient/Net.swift index bb607a9e..8534da89 100644 --- a/swift/Sources/LibSignalClient/Net.swift +++ b/swift/Sources/LibSignalClient/Net.swift @@ -91,15 +91,15 @@ public class Net { ) async throws -> CdsiLookup { let timeoutMs = durationToMillis(timeout) let handle: OpaquePointer = try await invokeAsyncFunction { promise, context in - asyncContext.withNativeHandle { asyncContext in - connectionManager.withNativeHandle { connectionManager in + self.asyncContext.withNativeHandle { asyncContext in + self.connectionManager.withNativeHandle { connectionManager in request.withNativeHandle { request in signal_cdsi_lookup_new(promise, context, asyncContext, connectionManager, auth.username, auth.password, request, timeoutMs) } } } } - return CdsiLookup(native: handle, asyncContext: asyncContext) + return CdsiLookup(native: handle, asyncContext: self.asyncContext) } private var asyncContext: TokioAsyncContext @@ -150,7 +150,8 @@ public class CdsiLookupRequest: NativeHandleOwner { prevE164s: [String], acisAndAccessKeys: [AciAndAccessKey], token: Data?, - returnAcisWithoutUaks: Bool) throws { + returnAcisWithoutUaks: Bool + ) throws { self.init() try self.withNativeHandle { handle in for e164 in e164s { @@ -182,7 +183,7 @@ public class CdsiLookupRequest: NativeHandleOwner { } } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { signal_lookup_request_destroy(handle) } } @@ -192,7 +193,7 @@ public class CdsiLookupRequest: NativeHandleOwner { /// Returned by ``Net/cdsiLookup(auth:request:timeout:)`` when a request is successfully initiated. public class CdsiLookup { class NativeCdsiLookup: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { signal_cdsi_lookup_destroy(handle) } } @@ -212,10 +213,10 @@ public class CdsiLookup { /// numbers. public var token: Data { failOnError { - try native.withNativeHandle { handle in - try invokeFnReturningData { - signal_cdsi_lookup_token($0, handle) - } + try self.native.withNativeHandle { handle in + try invokeFnReturningData { + signal_cdsi_lookup_token($0, handle) + } } } } @@ -232,8 +233,8 @@ public class CdsiLookup { /// `SignalError.networkProtocolError` for a CDSI or attested connection protocol issue. public func complete() async throws -> CdsiLookupResponse { let response: SignalFfiCdsiLookupResponse = try await invokeAsyncFunction { promise, context in - asyncContext.withNativeHandle { asyncContext in - native.withNativeHandle { handle in + self.asyncContext.withNativeHandle { asyncContext in + self.native.withNativeHandle { handle in signal_cdsi_lookup_complete(promise, context, asyncContext, handle) } } @@ -285,7 +286,7 @@ public class LookupResponseEntryList: Collection { public subscript(bounds: Range) -> SubSequence { self.owned[bounds] } } -let nilUuid = uuid_t(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) +let nilUuid = uuid_t(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) /// Entry contained in a successful CDSI lookup response. /// @@ -336,7 +337,7 @@ internal class TokioAsyncContext: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { signal_tokio_async_context_destroy(handle) } } @@ -348,7 +349,7 @@ internal class ConnectionManager: NativeHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { signal_connection_manager_destroy(handle) } } diff --git a/swift/Sources/LibSignalClient/Pin.swift b/swift/Sources/LibSignalClient/Pin.swift index 72456167..944cb70b 100644 --- a/swift/Sources/LibSignalClient/Pin.swift +++ b/swift/Sources/LibSignalClient/Pin.swift @@ -48,7 +48,7 @@ public func verifyLocalPin(_ pin: Bytes, againstEncodedH /// A hash of the pin that can be used to interact with a Secure Value Recovery service. public class PinHash: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_pin_hash_destroy(handle) } @@ -83,7 +83,6 @@ public class PinHash: NativeHandleOwner { /// - parameter salt: A 32 byte salt /// - returns: A `PinHash` public convenience init(normalizedPin: PinBytes, salt: SaltBytes) throws { - var result: OpaquePointer? try normalizedPin.withUnsafeBorrowedBuffer { pinBytes in try salt.withUnsafeBytes { saltBytes in @@ -114,5 +113,4 @@ public class PinHash: NativeHandleOwner { } self.init(owned: result!) } - } diff --git a/swift/Sources/LibSignalClient/PrivateKey.swift b/swift/Sources/LibSignalClient/PrivateKey.swift index 58b6cd71..0d73e164 100644 --- a/swift/Sources/LibSignalClient/PrivateKey.swift +++ b/swift/Sources/LibSignalClient/PrivateKey.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class PrivateKey: ClonableHandleOwner { public convenience init(_ bytes: Bytes) throws { @@ -24,11 +24,11 @@ public class PrivateKey: ClonableHandleOwner { } } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_privatekey_clone(&newHandle, currentHandle) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_privatekey_destroy(handle) } @@ -73,5 +73,4 @@ public class PrivateKey: ClonableHandleOwner { } } } - } diff --git a/swift/Sources/LibSignalClient/Protocol.swift b/swift/Sources/LibSignalClient/Protocol.swift index fd58b2c9..7035ebae 100644 --- a/swift/Sources/LibSignalClient/Protocol.swift +++ b/swift/Sources/LibSignalClient/Protocol.swift @@ -3,15 +3,17 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi -public func signalEncrypt(message: Bytes, - for address: ProtocolAddress, - sessionStore: SessionStore, - identityStore: IdentityKeyStore, - now: Date = Date(), - context: StoreContext) throws -> CiphertextMessage { +public func signalEncrypt( + message: Bytes, + for address: ProtocolAddress, + sessionStore: SessionStore, + identityStore: IdentityKeyStore, + now: Date = Date(), + context: StoreContext +) throws -> CiphertextMessage { return try address.withNativeHandle { addressHandle in try message.withUnsafeBorrowedBuffer { messageBuffer in try withSessionStore(sessionStore, context) { ffiSessionStore in @@ -25,11 +27,13 @@ public func signalEncrypt(message: Bytes, } } -public func signalDecrypt(message: SignalMessage, - from address: ProtocolAddress, - sessionStore: SessionStore, - identityStore: IdentityKeyStore, - context: StoreContext) throws -> [UInt8] { +public func signalDecrypt( + message: SignalMessage, + from address: ProtocolAddress, + sessionStore: SessionStore, + identityStore: IdentityKeyStore, + context: StoreContext +) throws -> [UInt8] { return try withNativeHandles(message, address) { messageHandle, addressHandle in try withSessionStore(sessionStore, context) { ffiSessionStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in @@ -41,14 +45,16 @@ public func signalDecrypt(message: SignalMessage, } } -public func signalDecryptPreKey(message: PreKeySignalMessage, - from address: ProtocolAddress, - sessionStore: SessionStore, - identityStore: IdentityKeyStore, - preKeyStore: PreKeyStore, - signedPreKeyStore: SignedPreKeyStore, - kyberPreKeyStore: KyberPreKeyStore, - context: StoreContext) throws -> [UInt8] { +public func signalDecryptPreKey( + message: PreKeySignalMessage, + from address: ProtocolAddress, + sessionStore: SessionStore, + identityStore: IdentityKeyStore, + preKeyStore: PreKeyStore, + signedPreKeyStore: SignedPreKeyStore, + kyberPreKeyStore: KyberPreKeyStore, + context: StoreContext +) throws -> [UInt8] { return try withNativeHandles(message, address) { messageHandle, addressHandle in try withSessionStore(sessionStore, context) { ffiSessionStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in @@ -66,12 +72,14 @@ public func signalDecryptPreKey(message: PreKeySignalMessage, } } -public func processPreKeyBundle(_ bundle: PreKeyBundle, - for address: ProtocolAddress, - sessionStore: SessionStore, - identityStore: IdentityKeyStore, - now: Date = Date(), - context: StoreContext) throws { +public func processPreKeyBundle( + _ bundle: PreKeyBundle, + for address: ProtocolAddress, + sessionStore: SessionStore, + identityStore: IdentityKeyStore, + now: Date = Date(), + context: StoreContext +) throws { return try withNativeHandles(bundle, address) { bundleHandle, addressHandle in try withSessionStore(sessionStore, context) { ffiSessionStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in @@ -81,11 +89,13 @@ public func processPreKeyBundle(_ bundle: PreKeyBundle, } } -public func groupEncrypt(_ message: Bytes, - from sender: ProtocolAddress, - distributionId: UUID, - store: SenderKeyStore, - context: StoreContext) throws -> CiphertextMessage { +public func groupEncrypt( + _ message: Bytes, + from sender: ProtocolAddress, + distributionId: UUID, + store: SenderKeyStore, + context: StoreContext +) throws -> CiphertextMessage { return try sender.withNativeHandle { senderHandle in try message.withUnsafeBorrowedBuffer { messageBuffer in try withUnsafePointer(to: distributionId.uuid) { distributionId in @@ -99,10 +109,12 @@ public func groupEncrypt(_ message: Bytes, } } -public func groupDecrypt(_ message: Bytes, - from sender: ProtocolAddress, - store: SenderKeyStore, - context: StoreContext) throws -> [UInt8] { +public func groupDecrypt( + _ message: Bytes, + from sender: ProtocolAddress, + store: SenderKeyStore, + context: StoreContext +) throws -> [UInt8] { return try sender.withNativeHandle { senderHandle in try message.withUnsafeBorrowedBuffer { messageBuffer in try withSenderKeyStore(store, context) { ffiStore in @@ -114,15 +126,19 @@ public func groupDecrypt(_ message: Bytes, } } -public func processSenderKeyDistributionMessage(_ message: SenderKeyDistributionMessage, - from sender: ProtocolAddress, - store: SenderKeyStore, - context: StoreContext) throws { +public func processSenderKeyDistributionMessage( + _ message: SenderKeyDistributionMessage, + from sender: ProtocolAddress, + store: SenderKeyStore, + context: StoreContext +) throws { return try withNativeHandles(sender, message) { senderHandle, messageHandle in try withSenderKeyStore(store, context) { - try checkError(signal_process_sender_key_distribution_message(senderHandle, - messageHandle, - $0)) + try checkError(signal_process_sender_key_distribution_message( + senderHandle, + messageHandle, + $0 + )) } } } diff --git a/swift/Sources/LibSignalClient/PublicKey.swift b/swift/Sources/LibSignalClient/PublicKey.swift index 08c0508f..4b2c9aa0 100644 --- a/swift/Sources/LibSignalClient/PublicKey.swift +++ b/swift/Sources/LibSignalClient/PublicKey.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class PublicKey: ClonableHandleOwner { public convenience init(_ bytes: Bytes) throws { @@ -16,11 +16,11 @@ public class PublicKey: ClonableHandleOwner { self.init(owned: handle!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_publickey_destroy(handle) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_publickey_clone(&newHandle, currentHandle) } @@ -44,9 +44,8 @@ public class PublicKey: ClonableHandleOwner { } } - public func verifySignature(message: MessageBytes, signature: SignatureBytes) throws -> Bool - where MessageBytes: ContiguousBytes, SignatureBytes: ContiguousBytes { - var result: Bool = false + public func verifySignature(message: some ContiguousBytes, signature: some ContiguousBytes) throws -> Bool { + var result = false try withNativeHandle { nativeHandle in try message.withUnsafeBorrowedBuffer { messageBuffer in try signature.withUnsafeBorrowedBuffer { signatureBuffer in diff --git a/swift/Sources/LibSignalClient/SealedSender.swift b/swift/Sources/LibSignalClient/SealedSender.swift index e70a4cba..5f86c590 100644 --- a/swift/Sources/LibSignalClient/SealedSender.swift +++ b/swift/Sources/LibSignalClient/SealedSender.swift @@ -3,26 +3,32 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi @inlinable -public func sealedSenderEncrypt(message: Bytes, - for address: ProtocolAddress, - from senderCert: SenderCertificate, - sessionStore: SessionStore, - identityStore: IdentityKeyStore, - context: StoreContext) throws -> [UInt8] { - let ciphertextMessage = try signalEncrypt(message: message, - for: address, - sessionStore: sessionStore, - identityStore: identityStore, - context: context) +public func sealedSenderEncrypt( + message: Bytes, + for address: ProtocolAddress, + from senderCert: SenderCertificate, + sessionStore: SessionStore, + identityStore: IdentityKeyStore, + context: StoreContext +) throws -> [UInt8] { + let ciphertextMessage = try signalEncrypt( + message: message, + for: address, + sessionStore: sessionStore, + identityStore: identityStore, + context: context + ) - let usmc = try UnidentifiedSenderMessageContent(ciphertextMessage, - from: senderCert, - contentHint: .default, - groupId: []) + let usmc = try UnidentifiedSenderMessageContent( + ciphertextMessage, + from: senderCert, + contentHint: .default, + groupId: [] + ) return try sealedSenderEncrypt(usmc, for: address, identityStore: identityStore, context: context) } @@ -41,17 +47,21 @@ public class UnidentifiedSenderMessageContent: NativeHandleOwner { public static var `default`: Self { return Self(SignalContentHintDefault) } + public static var resendable: Self { return Self(SignalContentHintResendable) } + public static var implicit: Self { return Self(SignalContentHintImplicit) } } - public convenience init(message sealedSenderMessage: Bytes, - identityStore: IdentityKeyStore, - context: StoreContext) throws { + public convenience init( + message sealedSenderMessage: Bytes, + identityStore: IdentityKeyStore, + context: StoreContext + ) throws { var result: OpaquePointer? try sealedSenderMessage.withUnsafeBorrowedBuffer { messageBuffer in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in @@ -59,31 +69,36 @@ public class UnidentifiedSenderMessageContent: NativeHandleOwner { signal_sealed_session_cipher_decrypt_to_usmc( &result, messageBuffer, - ffiIdentityStore)) + ffiIdentityStore + )) } } self.init(owned: result!) } - public convenience init(_ message: CiphertextMessage, - from sender: SenderCertificate, - contentHint: ContentHint, - groupId: GroupIdBytes) throws { + public convenience init( + _ message: CiphertextMessage, + from sender: SenderCertificate, + contentHint: ContentHint, + groupId: GroupIdBytes + ) throws { var result: OpaquePointer? try withNativeHandles(message, sender) { messageHandle, senderHandle in try groupId.withUnsafeBorrowedBuffer { groupIdBuffer in try checkError( - signal_unidentified_sender_message_content_new(&result, - messageHandle, - senderHandle, - contentHint.rawValue, - groupIdBuffer)) + signal_unidentified_sender_message_content_new( + &result, + messageHandle, + senderHandle, + contentHint.rawValue, + groupIdBuffer + )) } } self.init(owned: result!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_unidentified_sender_message_content_destroy(handle) } @@ -144,28 +159,34 @@ public class UnidentifiedSenderMessageContent: NativeHandleOwner { } } -public func sealedSenderEncrypt(_ content: UnidentifiedSenderMessageContent, - for recipient: ProtocolAddress, - identityStore: IdentityKeyStore, - context: StoreContext) throws -> [UInt8] { +public func sealedSenderEncrypt( + _ content: UnidentifiedSenderMessageContent, + for recipient: ProtocolAddress, + identityStore: IdentityKeyStore, + context: StoreContext +) throws -> [UInt8] { return try withNativeHandles(recipient, content) { recipientHandle, contentHandle in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try invokeFnReturningArray { - signal_sealed_session_cipher_encrypt($0, - recipientHandle, - contentHandle, - ffiIdentityStore) + signal_sealed_session_cipher_encrypt( + $0, + recipientHandle, + contentHandle, + ffiIdentityStore + ) } } } } -public func sealedSenderMultiRecipientEncrypt(_ content: UnidentifiedSenderMessageContent, - for recipients: [ProtocolAddress], - excludedRecipients: [ServiceId] = [], - identityStore: IdentityKeyStore, - sessionStore: SessionStore, - context: StoreContext) throws -> [UInt8] { +public func sealedSenderMultiRecipientEncrypt( + _ content: UnidentifiedSenderMessageContent, + for recipients: [ProtocolAddress], + excludedRecipients: [ServiceId] = [], + identityStore: IdentityKeyStore, + sessionStore: SessionStore, + context: StoreContext +) throws -> [UInt8] { let sessions = try sessionStore.loadExistingSessions(for: recipients, context: context) // Use withExtendedLifetime instead of withNativeHandle for the arrays of wrapper objects, // which aren't compatible with withNativeHandle's simple lexical scoping. @@ -173,19 +194,21 @@ public func sealedSenderMultiRecipientEncrypt(_ content: UnidentifiedSenderMessa let recipientHandles = recipients.map { $0.unsafeNativeHandle } let sessionHandles = sessions.map { $0.unsafeNativeHandle } return try content.withNativeHandle { contentHandle in - return try recipientHandles.withUnsafeBufferPointer { recipientHandles in + try recipientHandles.withUnsafeBufferPointer { recipientHandles in let recipientHandlesBuffer = SignalBorrowedSliceOfProtocolAddress(base: recipientHandles.baseAddress, length: recipientHandles.count) return try sessionHandles.withUnsafeBufferPointer { sessionHandles in let sessionHandlesBuffer = SignalBorrowedSliceOfSessionRecord(base: sessionHandles.baseAddress, length: sessionHandles.count) return try ServiceId.concatenatedFixedWidthBinary(excludedRecipients).withUnsafeBorrowedBuffer { excludedRecipientsBuffer in - return try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in + try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try invokeFnReturningArray { - signal_sealed_sender_multi_recipient_encrypt($0, - recipientHandlesBuffer, - sessionHandlesBuffer, - excludedRecipientsBuffer, - contentHandle, - ffiIdentityStore) + signal_sealed_sender_multi_recipient_encrypt( + $0, + recipientHandlesBuffer, + sessionHandlesBuffer, + excludedRecipientsBuffer, + contentHandle, + ffiIdentityStore + ) } } } @@ -225,7 +248,7 @@ public struct SealedSenderAddress: Hashable { /// /// In a future release SealedSenderAddress will *only* support ACIs. public var senderAci: Aci! { - return try? Aci.parseFrom(serviceIdString: uuidString) + return try? Aci.parseFrom(serviceIdString: self.uuidString) } } @@ -234,15 +257,17 @@ public struct SealedSenderResult { public var sender: SealedSenderAddress } -public func sealedSenderDecrypt(message: Bytes, - from localAddress: SealedSenderAddress, - trustRoot: PublicKey, - timestamp: UInt64, - sessionStore: SessionStore, - identityStore: IdentityKeyStore, - preKeyStore: PreKeyStore, - signedPreKeyStore: SignedPreKeyStore, - context: StoreContext) throws -> SealedSenderResult { +public func sealedSenderDecrypt( + message: Bytes, + from localAddress: SealedSenderAddress, + trustRoot: PublicKey, + timestamp: UInt64, + sessionStore: SessionStore, + identityStore: IdentityKeyStore, + preKeyStore: PreKeyStore, + signedPreKeyStore: SignedPreKeyStore, + context: StoreContext +) throws -> SealedSenderResult { var senderE164: UnsafePointer? var senderUUID: UnsafePointer? var senderDeviceId: UInt32 = 0 @@ -268,7 +293,8 @@ public func sealedSenderDecrypt(message: Bytes, ffiSessionStore, ffiIdentityStore, ffiPreKeyStore, - ffiSignedPreKeyStore) + ffiSignedPreKeyStore + ) } } } @@ -282,8 +308,12 @@ public func sealedSenderDecrypt(message: Bytes, signal_free_string(senderUUID) } - return SealedSenderResult(message: plaintext, - sender: try SealedSenderAddress(e164: senderE164.map(String.init(cString:)), - uuidString: String(cString: senderUUID!), - deviceId: senderDeviceId)) + return SealedSenderResult( + message: plaintext, + sender: try SealedSenderAddress( + e164: senderE164.map(String.init(cString:)), + uuidString: String(cString: senderUUID!), + deviceId: senderDeviceId + ) + ) } diff --git a/swift/Sources/LibSignalClient/SealedSenderCertificates.swift b/swift/Sources/LibSignalClient/SealedSenderCertificates.swift index c30191f1..de420121 100644 --- a/swift/Sources/LibSignalClient/SealedSenderCertificates.swift +++ b/swift/Sources/LibSignalClient/SealedSenderCertificates.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class ServerCertificate: NativeHandleOwner { public convenience init(_ bytes: Bytes) throws { @@ -25,7 +25,7 @@ public class ServerCertificate: NativeHandleOwner { self.init(owned: result!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_server_certificate_destroy(handle) } @@ -94,19 +94,21 @@ public class SenderCertificate: NativeHandleOwner { public convenience init(sender: SealedSenderAddress, publicKey: PublicKey, expiration: UInt64, signerCertificate: ServerCertificate, signerKey: PrivateKey) throws { var result: OpaquePointer? try withNativeHandles(publicKey, signerCertificate, signerKey) { publicKeyHandle, signerCertificateHandle, signerKeyHandle in - try checkError(signal_sender_certificate_new(&result, - sender.uuidString, - sender.e164, - sender.deviceId, - publicKeyHandle, - expiration, - signerCertificateHandle, - signerKeyHandle)) + try checkError(signal_sender_certificate_new( + &result, + sender.uuidString, + sender.e164, + sender.deviceId, + publicKeyHandle, + expiration, + signerCertificateHandle, + signerKeyHandle + )) } self.init(owned: result!) } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_sender_certificate_destroy(handle) } @@ -184,7 +186,7 @@ public class SenderCertificate: NativeHandleOwner { /// /// In a future release SenderCertificate will *only* support ACIs. public var senderAci: Aci! { - return try? Aci.parseFrom(serviceIdString: senderUuid) + return try? Aci.parseFrom(serviceIdString: self.senderUuid) } public var senderE164: String? { @@ -214,7 +216,7 @@ public class SenderCertificate: NativeHandleOwner { } public func validate(trustRoot: PublicKey, time: UInt64) throws -> Bool { - var result: Bool = false + var result = false try withNativeHandles(self, trustRoot) { certificateHandle, trustRootHandle in try checkError(signal_sender_certificate_validate(&result, certificateHandle, trustRootHandle, time)) } diff --git a/swift/Sources/LibSignalClient/ServiceId.swift b/swift/Sources/LibSignalClient/ServiceId.swift index e9ab2c45..8d44899a 100644 --- a/swift/Sources/LibSignalClient/ServiceId.swift +++ b/swift/Sources/LibSignalClient/ServiceId.swift @@ -43,7 +43,7 @@ public enum ServiceIdError: Error { } public class ServiceId { - fileprivate var storage: ServiceIdStorage = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + private var storage: ServiceIdStorage = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) fileprivate init(fromFixedWidthBinary storage: ServiceIdStorage) { self.storage = storage @@ -187,7 +187,7 @@ public class Aci: ServiceId { super.init(.aci, uuid) } - internal override init(fromFixedWidthBinary bytes: ServiceIdStorage) { + override internal init(fromFixedWidthBinary bytes: ServiceIdStorage) { super.init(fromFixedWidthBinary: bytes) } } @@ -197,7 +197,7 @@ public class Pni: ServiceId { super.init(.pni, uuid) } - internal override init(fromFixedWidthBinary bytes: ServiceIdStorage) { + override internal init(fromFixedWidthBinary bytes: ServiceIdStorage) { super.init(fromFixedWidthBinary: bytes) } } diff --git a/swift/Sources/LibSignalClient/Sgx.swift b/swift/Sources/LibSignalClient/Sgx.swift index 834875c8..df3c65c6 100644 --- a/swift/Sources/LibSignalClient/Sgx.swift +++ b/swift/Sources/LibSignalClient/Sgx.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi /// /// SgxClient provides bindings to interact with a Signal SGX service @@ -25,8 +25,7 @@ import Foundation /// which decrypts and verifies it, passing the plaintext back to the client for processing. /// public class SgxClient: NativeHandleOwner { - - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_sgx_client_state_destroy(handle) } diff --git a/swift/Sources/LibSignalClient/Svr2.swift b/swift/Sources/LibSignalClient/Svr2.swift index 125af427..10543843 100644 --- a/swift/Sources/LibSignalClient/Svr2.swift +++ b/swift/Sources/LibSignalClient/Svr2.swift @@ -11,15 +11,20 @@ import SignalFfi /// /// See ``SgxClient`` public class Svr2Client: SgxClient { - public convenience init(mrenclave: MrenclaveBytes, attestationMessage: AttestationBytes, currentDate: Date) throws - where MrenclaveBytes: ContiguousBytes, AttestationBytes: ContiguousBytes { + public convenience init( + mrenclave: some ContiguousBytes, + attestationMessage: some ContiguousBytes, + currentDate: Date + ) throws { let handle: OpaquePointer? = try attestationMessage.withUnsafeBorrowedBuffer { attestationMessageBuffer in try mrenclave.withUnsafeBorrowedBuffer { mrenclaveBuffer in var result: OpaquePointer? - try checkError(signal_svr2_client_new(&result, - mrenclaveBuffer, - attestationMessageBuffer, - UInt64(currentDate.timeIntervalSince1970 * 1000))) + try checkError(signal_svr2_client_new( + &result, + mrenclaveBuffer, + attestationMessageBuffer, + UInt64(currentDate.timeIntervalSince1970 * 1000) + )) return result } } diff --git a/swift/Sources/LibSignalClient/Username.swift b/swift/Sources/LibSignalClient/Username.swift index e148241a..daaada7e 100644 --- a/swift/Sources/LibSignalClient/Username.swift +++ b/swift/Sources/LibSignalClient/Username.swift @@ -62,7 +62,7 @@ public struct Username { public func createLink(previousEntropy: [UInt8]? = nil) throws -> ([UInt8], [UInt8]) { let bytes = failOnError { - return try self.value.withCString { usernamePtr in + try self.value.withCString { usernamePtr in try (previousEntropy ?? []).withUnsafeBorrowedBuffer { entropyPtr in try invokeFnReturningArray { signal_username_link_create($0, usernamePtr, entropyPtr) @@ -84,8 +84,8 @@ public struct Username { } public static func candidates( - from nickname: String, - withValidLengthWithin lengthRange: ClosedRange = 3...32 + from nickname: String, + withValidLengthWithin lengthRange: ClosedRange = 3...32 ) throws -> [Username] { let allCandidates = try nickname.withCString { nicknamePtr in try invokeFnReturningStringArray { @@ -98,11 +98,11 @@ public struct Username { extension Username: CustomStringConvertible { public var description: String { - return value + return self.value } } -extension Username: Equatable { } +extension Username: Equatable {} private func generateHash(_ s: String) throws -> [UInt8] { try s.withCString { strPtr in diff --git a/swift/Sources/LibSignalClient/Utils.swift b/swift/Sources/LibSignalClient/Utils.swift index aa300643..25835645 100644 --- a/swift/Sources/LibSignalClient/Utils.swift +++ b/swift/Sources/LibSignalClient/Utils.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi #if canImport(Security) import Security @@ -114,7 +114,7 @@ internal func invokeFnReturningInteger(fn: (UnsafeMut } internal func invokeFnReturningBool(fn: (UnsafeMutablePointer?) -> SignalFfiErrorRef?) throws -> Bool { - var output: Bool = false + var output = false try checkError(fn(&output)) return output } @@ -161,7 +161,7 @@ internal func fillRandom(_ buffer: UnsafeMutableRawBufferPointer) throws { #if canImport(Security) let result = SecRandomCopyBytes(kSecRandomDefault, buffer.count, baseAddress) guard result == errSecSuccess else { - throw SignalError.internalError("SecRandomCopyBytes failed (error code \(result))") + throw SignalError.internalError("SecRandomCopyBytes failed (error code \(result))") } #else for i in buffer.indices { diff --git a/swift/Sources/LibSignalClient/messages/CiphertextMessage.swift b/swift/Sources/LibSignalClient/messages/CiphertextMessage.swift index 0bd4c8b4..2ab7c716 100644 --- a/swift/Sources/LibSignalClient/messages/CiphertextMessage.swift +++ b/swift/Sources/LibSignalClient/messages/CiphertextMessage.swift @@ -19,18 +19,21 @@ public class CiphertextMessage: NativeHandleOwner { public static var whisper: Self { return Self(SignalCiphertextMessageTypeWhisper) } + public static var preKey: Self { return Self(SignalCiphertextMessageTypePreKey) } + public static var senderKey: Self { return Self(SignalCiphertextMessageTypeSenderKey) } + public static var plaintext: Self { return Self(SignalCiphertextMessageTypePlaintext) } } - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_ciphertext_message_destroy(handle) } diff --git a/swift/Sources/LibSignalClient/messages/PlaintextContent.swift b/swift/Sources/LibSignalClient/messages/PlaintextContent.swift index 03641d8c..3b5041f8 100644 --- a/swift/Sources/LibSignalClient/messages/PlaintextContent.swift +++ b/swift/Sources/LibSignalClient/messages/PlaintextContent.swift @@ -3,11 +3,11 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class PlaintextContent: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_plaintext_content_destroy(handle) } @@ -49,7 +49,7 @@ public class PlaintextContent: NativeHandleOwner { } public class DecryptionErrorMessage: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_decryption_error_message_destroy(handle) } diff --git a/swift/Sources/LibSignalClient/messages/PreKeySignalMessage.swift b/swift/Sources/LibSignalClient/messages/PreKeySignalMessage.swift index fe1358f7..c3aeb38f 100644 --- a/swift/Sources/LibSignalClient/messages/PreKeySignalMessage.swift +++ b/swift/Sources/LibSignalClient/messages/PreKeySignalMessage.swift @@ -3,11 +3,11 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class PreKeySignalMessage: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_pre_key_signal_message_destroy(handle) } @@ -50,7 +50,7 @@ public class PreKeySignalMessage: NativeHandleOwner { } } - if id == 0xFFFFFFFF { + if id == 0xFFFF_FFFF { return nil } else { return id diff --git a/swift/Sources/LibSignalClient/messages/SenderKeyDistributionMessage.swift b/swift/Sources/LibSignalClient/messages/SenderKeyDistributionMessage.swift index 95382c5f..13f2d2b7 100644 --- a/swift/Sources/LibSignalClient/messages/SenderKeyDistributionMessage.swift +++ b/swift/Sources/LibSignalClient/messages/SenderKeyDistributionMessage.swift @@ -3,26 +3,30 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class SenderKeyDistributionMessage: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_sender_key_distribution_message_destroy(handle) } - public convenience init(from sender: ProtocolAddress, - distributionId: UUID, - store: SenderKeyStore, - context: StoreContext) throws { + public convenience init( + from sender: ProtocolAddress, + distributionId: UUID, + store: SenderKeyStore, + context: StoreContext + ) throws { var result: OpaquePointer? try sender.withNativeHandle { senderHandle in try withUnsafePointer(to: distributionId.uuid) { distributionId in try withSenderKeyStore(store, context) { - try checkError(signal_sender_key_distribution_message_create(&result, - senderHandle, - distributionId, - $0)) + try checkError(signal_sender_key_distribution_message_create( + &result, + senderHandle, + distributionId, + $0 + )) } } } diff --git a/swift/Sources/LibSignalClient/messages/SenderKeyMessage.swift b/swift/Sources/LibSignalClient/messages/SenderKeyMessage.swift index eb80fd57..06f94b6d 100644 --- a/swift/Sources/LibSignalClient/messages/SenderKeyMessage.swift +++ b/swift/Sources/LibSignalClient/messages/SenderKeyMessage.swift @@ -3,11 +3,11 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class SenderKeyMessage: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_sender_key_message_destroy(handle) } @@ -70,7 +70,7 @@ public class SenderKeyMessage: NativeHandleOwner { } public func verifySignature(against key: PublicKey) throws -> Bool { - var result: Bool = false + var result = false try withNativeHandles(self, key) { messageHandle, keyHandle in try checkError(signal_sender_key_message_verify_signature(&result, messageHandle, keyHandle)) } diff --git a/swift/Sources/LibSignalClient/messages/SignalMessage.swift b/swift/Sources/LibSignalClient/messages/SignalMessage.swift index e7827ee0..07b2f02a 100644 --- a/swift/Sources/LibSignalClient/messages/SignalMessage.swift +++ b/swift/Sources/LibSignalClient/messages/SignalMessage.swift @@ -3,11 +3,11 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class SignalMessage: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_message_destroy(handle) } @@ -69,17 +69,21 @@ public class SignalMessage: NativeHandleOwner { } } - public func verifyMac(sender: PublicKey, - receiver: PublicKey, - macKey: Bytes) throws -> Bool { + public func verifyMac( + sender: PublicKey, + receiver: PublicKey, + macKey: Bytes + ) throws -> Bool { return try withNativeHandles(self, sender, receiver) { messageHandle, senderHandle, receiverHandle in try macKey.withUnsafeBorrowedBuffer { var result: Bool = false - try checkError(signal_message_verify_mac(&result, - messageHandle, - senderHandle, - receiverHandle, - $0)) + try checkError(signal_message_verify_mac( + &result, + messageHandle, + senderHandle, + receiverHandle, + $0 + )) return result } } diff --git a/swift/Sources/LibSignalClient/state/KyberPreKeyRecord.swift b/swift/Sources/LibSignalClient/state/KyberPreKeyRecord.swift index 3830db28..bc5b0e7f 100644 --- a/swift/Sources/LibSignalClient/state/KyberPreKeyRecord.swift +++ b/swift/Sources/LibSignalClient/state/KyberPreKeyRecord.swift @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class KyberPreKeyRecord: ClonableHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_kyber_pre_key_record_destroy(handle) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_kyber_pre_key_record_clone(&newHandle, currentHandle) } diff --git a/swift/Sources/LibSignalClient/state/PreKeyBundle.swift b/swift/Sources/LibSignalClient/state/PreKeyBundle.swift index c2fe375a..beb5d5b9 100644 --- a/swift/Sources/LibSignalClient/state/PreKeyBundle.swift +++ b/swift/Sources/LibSignalClient/state/PreKeyBundle.swift @@ -3,39 +3,43 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class PreKeyBundle: NativeHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_pre_key_bundle_destroy(handle) } // with a prekey - public convenience init(registrationId: UInt32, - deviceId: UInt32, - prekeyId: UInt32, - prekey: PublicKey, - signedPrekeyId: UInt32, - signedPrekey: PublicKey, - signedPrekeySignature: Bytes, - identity identityKey: IdentityKey) throws { + public convenience init( + registrationId: UInt32, + deviceId: UInt32, + prekeyId: UInt32, + prekey: PublicKey, + signedPrekeyId: UInt32, + signedPrekey: PublicKey, + signedPrekeySignature: Bytes, + identity identityKey: IdentityKey + ) throws { var result: OpaquePointer? try withNativeHandles(prekey, signedPrekey, identityKey.publicKey) { prekeyHandle, signedPrekeyHandle, identityKeyHandle in try signedPrekeySignature.withUnsafeBorrowedBuffer { signedSignatureBuffer in try [].withUnsafeBorrowedBuffer { kyberSignatureBuffer in - try checkError(signal_pre_key_bundle_new(&result, - registrationId, - deviceId, - prekeyId, - prekeyHandle, - signedPrekeyId, - signedPrekeyHandle, - signedSignatureBuffer, - identityKeyHandle, - ~0, - nil, - kyberSignatureBuffer)) + try checkError(signal_pre_key_bundle_new( + &result, + registrationId, + deviceId, + prekeyId, + prekeyHandle, + signedPrekeyId, + signedPrekeyHandle, + signedSignatureBuffer, + identityKeyHandle, + ~0, + nil, + kyberSignatureBuffer + )) } } } @@ -43,28 +47,32 @@ public class PreKeyBundle: NativeHandleOwner { } // without a prekey - public convenience init(registrationId: UInt32, - deviceId: UInt32, - signedPrekeyId: UInt32, - signedPrekey: PublicKey, - signedPrekeySignature: Bytes, - identity identityKey: IdentityKey) throws { + public convenience init( + registrationId: UInt32, + deviceId: UInt32, + signedPrekeyId: UInt32, + signedPrekey: PublicKey, + signedPrekeySignature: Bytes, + identity identityKey: IdentityKey + ) throws { var result: OpaquePointer? try withNativeHandles(signedPrekey, identityKey.publicKey) { signedPrekeyHandle, identityKeyHandle in try signedPrekeySignature.withUnsafeBorrowedBuffer { signedSignatureBuffer in try [].withUnsafeBorrowedBuffer { kyberSignatureBuffer in - try checkError(signal_pre_key_bundle_new(&result, - registrationId, - deviceId, - ~0, - nil, - signedPrekeyId, - signedPrekeyHandle, - signedSignatureBuffer, - identityKeyHandle, - ~0, - nil, - kyberSignatureBuffer)) + try checkError(signal_pre_key_bundle_new( + &result, + registrationId, + deviceId, + ~0, + nil, + signedPrekeyId, + signedPrekeyHandle, + signedSignatureBuffer, + identityKeyHandle, + ~0, + nil, + kyberSignatureBuffer + )) } } } @@ -87,23 +95,25 @@ public class PreKeyBundle: NativeHandleOwner { kyberPrekeyId: UInt32, kyberPrekey: KEMPublicKey, kyberPrekeySignature: KEMBytes - ) throws { + ) throws { var result: OpaquePointer? try withNativeHandles(prekey, signedPrekey, identityKey.publicKey, kyberPrekey) { prekeyHandle, signedPrekeyHandle, identityKeyHandle, kyberKeyHandle in try signedPrekeySignature.withUnsafeBorrowedBuffer { ecSignatureBuffer in try kyberPrekeySignature.withUnsafeBorrowedBuffer { kyberSignatureBuffer in - try checkError(signal_pre_key_bundle_new(&result, - registrationId, - deviceId, - prekeyId, - prekeyHandle, - signedPrekeyId, - signedPrekeyHandle, - ecSignatureBuffer, - identityKeyHandle, - kyberPrekeyId, - kyberKeyHandle, - kyberSignatureBuffer)) + try checkError(signal_pre_key_bundle_new( + &result, + registrationId, + deviceId, + prekeyId, + prekeyHandle, + signedPrekeyId, + signedPrekeyHandle, + ecSignatureBuffer, + identityKeyHandle, + kyberPrekeyId, + kyberKeyHandle, + kyberSignatureBuffer + )) } } } @@ -124,23 +134,25 @@ public class PreKeyBundle: NativeHandleOwner { kyberPrekeyId: UInt32, kyberPrekey: KEMPublicKey, kyberPrekeySignature: KEMBytes - ) throws { + ) throws { var result: OpaquePointer? try withNativeHandles(signedPrekey, identityKey.publicKey, kyberPrekey) { signedPrekeyHandle, identityKeyHandle, kyberKeyHandle in try signedPrekeySignature.withUnsafeBorrowedBuffer { ecSignatureBuffer in try kyberPrekeySignature.withUnsafeBorrowedBuffer { kyberSignatureBuffer in - try checkError(signal_pre_key_bundle_new(&result, - registrationId, - deviceId, - ~0, - nil, - signedPrekeyId, - signedPrekeyHandle, - ecSignatureBuffer, - identityKeyHandle, - kyberPrekeyId, - kyberKeyHandle, - kyberSignatureBuffer)) + try checkError(signal_pre_key_bundle_new( + &result, + registrationId, + deviceId, + ~0, + nil, + signedPrekeyId, + signedPrekeyHandle, + ecSignatureBuffer, + identityKeyHandle, + kyberPrekeyId, + kyberKeyHandle, + kyberSignatureBuffer + )) } } } diff --git a/swift/Sources/LibSignalClient/state/PreKeyRecord.swift b/swift/Sources/LibSignalClient/state/PreKeyRecord.swift index 593ffc81..c4196d80 100644 --- a/swift/Sources/LibSignalClient/state/PreKeyRecord.swift +++ b/swift/Sources/LibSignalClient/state/PreKeyRecord.swift @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class PreKeyRecord: ClonableHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_pre_key_record_destroy(handle) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_pre_key_record_clone(&newHandle, currentHandle) } @@ -24,9 +24,11 @@ public class PreKeyRecord: ClonableHandleOwner { self.init(owned: handle!) } - public convenience init(id: UInt32, - publicKey: PublicKey, - privateKey: PrivateKey) throws { + public convenience init( + id: UInt32, + publicKey: PublicKey, + privateKey: PrivateKey + ) throws { var handle: OpaquePointer? try withNativeHandles(publicKey, privateKey) { publicKeyHandle, privateKeyHandle in try checkError(signal_pre_key_record_new(&handle, id, publicKeyHandle, privateKeyHandle)) diff --git a/swift/Sources/LibSignalClient/state/SenderKeyRecord.swift b/swift/Sources/LibSignalClient/state/SenderKeyRecord.swift index 0f7fcfeb..837861d5 100644 --- a/swift/Sources/LibSignalClient/state/SenderKeyRecord.swift +++ b/swift/Sources/LibSignalClient/state/SenderKeyRecord.swift @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class SenderKeyRecord: ClonableHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_sender_key_record_destroy(handle) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_sender_key_record_clone(&newHandle, currentHandle) } diff --git a/swift/Sources/LibSignalClient/state/SessionRecord.swift b/swift/Sources/LibSignalClient/state/SessionRecord.swift index 0445fa97..4c8193aa 100644 --- a/swift/Sources/LibSignalClient/state/SessionRecord.swift +++ b/swift/Sources/LibSignalClient/state/SessionRecord.swift @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class SessionRecord: ClonableHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_session_record_destroy(handle) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_session_record_clone(&newHandle, currentHandle) } @@ -61,7 +61,7 @@ public class SessionRecord: ClonableHandleOwner { } public func currentRatchetKeyMatches(_ key: PublicKey) throws -> Bool { - var result: Bool = false + var result = false try withNativeHandles(self, key) { sessionHandle, keyHandle in try checkError(signal_session_record_current_ratchet_key_matches(&result, sessionHandle, keyHandle)) } diff --git a/swift/Sources/LibSignalClient/state/SignedPreKeyRecord.swift b/swift/Sources/LibSignalClient/state/SignedPreKeyRecord.swift index 5795c476..d7bdc903 100644 --- a/swift/Sources/LibSignalClient/state/SignedPreKeyRecord.swift +++ b/swift/Sources/LibSignalClient/state/SignedPreKeyRecord.swift @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import SignalFfi import Foundation +import SignalFfi public class SignedPreKeyRecord: ClonableHandleOwner { - internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { + override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { return signal_signed_pre_key_record_destroy(handle) } - internal override class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { + override internal class func cloneNativeHandle(_ newHandle: inout OpaquePointer?, currentHandle: OpaquePointer?) -> SignalFfiErrorRef? { return signal_signed_pre_key_record_clone(&newHandle, currentHandle) } @@ -24,17 +24,24 @@ public class SignedPreKeyRecord: ClonableHandleOwner { self.init(owned: handle!) } - public convenience init(id: UInt32, - timestamp: UInt64, - privateKey: PrivateKey, - signature: Bytes) throws { + public convenience init( + id: UInt32, + timestamp: UInt64, + privateKey: PrivateKey, + signature: Bytes + ) throws { let publicKey = privateKey.publicKey var result: OpaquePointer? try withNativeHandles(publicKey, privateKey) { publicKeyHandle, privateKeyHandle in try signature.withUnsafeBorrowedBuffer { - try checkError(signal_signed_pre_key_record_new(&result, id, timestamp, - publicKeyHandle, privateKeyHandle, - $0)) + try checkError(signal_signed_pre_key_record_new( + &result, + id, + timestamp, + publicKeyHandle, + privateKeyHandle, + $0 + )) } } self.init(owned: result!) diff --git a/swift/Sources/LibSignalClient/zkgroup/AuthCredential.swift b/swift/Sources/LibSignalClient/zkgroup/AuthCredential.swift index f7f060e7..18ae7cc6 100644 --- a/swift/Sources/LibSignalClient/zkgroup/AuthCredential.swift +++ b/swift/Sources/LibSignalClient/zkgroup/AuthCredential.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class AuthCredential: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_auth_credential_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_auth_credential_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialPresentation.swift b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialPresentation.swift index f2225235..a18c71cd 100644 --- a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialPresentation.swift +++ b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialPresentation.swift @@ -7,34 +7,32 @@ import Foundation import SignalFfi public class AuthCredentialPresentation: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_auth_credential_presentation_check_valid_contents) - } - - public func getUuidCiphertext() throws -> UuidCiphertext { - return try withUnsafeBorrowedBuffer { buffer in - try invokeFnReturningSerialized { - signal_auth_credential_presentation_get_uuid_ciphertext($0, buffer) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_auth_credential_presentation_check_valid_contents) } - } - public func getPniCiphertext() throws -> UuidCiphertext? { - return try withUnsafeBorrowedBuffer { buffer in - try invokeFnReturningOptionalVariableLengthSerialized { - signal_auth_credential_presentation_get_pni_ciphertext_or_empty($0, buffer) - } + public func getUuidCiphertext() throws -> UuidCiphertext { + return try withUnsafeBorrowedBuffer { buffer in + try invokeFnReturningSerialized { + signal_auth_credential_presentation_get_uuid_ciphertext($0, buffer) + } + } } - } - public func getRedemptionTime() throws -> Date { - let secondsSinceEpoch = try withUnsafeBorrowedBuffer { buffer in - try invokeFnReturningInteger { - signal_auth_credential_presentation_get_redemption_time($0, buffer) - } + public func getPniCiphertext() throws -> UuidCiphertext? { + return try withUnsafeBorrowedBuffer { buffer in + try invokeFnReturningOptionalVariableLengthSerialized { + signal_auth_credential_presentation_get_pni_ciphertext_or_empty($0, buffer) + } + } } - return Date(timeIntervalSince1970: TimeInterval(secondsSinceEpoch)) - } + public func getRedemptionTime() throws -> Date { + let secondsSinceEpoch = try withUnsafeBorrowedBuffer { buffer in + try invokeFnReturningInteger { + signal_auth_credential_presentation_get_redemption_time($0, buffer) + } + } + return Date(timeIntervalSince1970: TimeInterval(secondsSinceEpoch)) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialResponse.swift b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialResponse.swift index c843e679..762f5360 100644 --- a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialResponse.swift +++ b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialResponse.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class AuthCredentialResponse: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_auth_credential_response_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_auth_credential_response_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPni.swift b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPni.swift index 3b122cdc..30e3b9d0 100644 --- a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPni.swift +++ b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPni.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class AuthCredentialWithPni: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_auth_credential_with_pni_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_auth_credential_with_pni_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPniResponse.swift b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPniResponse.swift index 20deccab..6c08f02b 100644 --- a/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPniResponse.swift +++ b/swift/Sources/LibSignalClient/zkgroup/AuthCredentialWithPniResponse.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class AuthCredentialWithPniResponse: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_auth_credential_with_pni_response_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_auth_credential_with_pni_response_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredential.swift b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredential.swift index 382b93e7..073be88c 100644 --- a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredential.swift +++ b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredential.swift @@ -7,14 +7,13 @@ import Foundation import SignalFfi public class BackupAuthCredential: ByteArray { - public required init(contents: [UInt8]) throws { try super.init(contents, checkValid: signal_backup_auth_credential_check_valid_contents) } public func present(serverParams: GenericServerPublicParams) -> BackupAuthCredentialPresentation { return failOnError { - present(serverParams: serverParams, randomness: try .generate()) + self.present(serverParams: serverParams, randomness: try .generate()) } } diff --git a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialPresentation.swift b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialPresentation.swift index 5dace5a2..bbc7cabe 100644 --- a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialPresentation.swift +++ b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialPresentation.swift @@ -7,7 +7,6 @@ import Foundation import SignalFfi public class BackupAuthCredentialPresentation: ByteArray { - public required init(contents: [UInt8]) throws { try super.init(contents, checkValid: signal_backup_auth_credential_presentation_check_valid_contents) } diff --git a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequest.swift b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequest.swift index 568dc412..8c26e930 100644 --- a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequest.swift +++ b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequest.swift @@ -13,7 +13,7 @@ public class BackupAuthCredentialRequest: ByteArray { public func issueCredential(timestamp: Date, receiptLevel: UInt64, params: GenericServerSecretParams) -> BackupAuthCredentialResponse { return failOnError { - issueCredential(timestamp: timestamp, receiptLevel: receiptLevel, params: params, randomness: try .generate()) + self.issueCredential(timestamp: timestamp, receiptLevel: receiptLevel, params: params, randomness: try .generate()) } } diff --git a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequestContext.swift b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequestContext.swift index a2667229..6a1cc377 100644 --- a/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequestContext.swift +++ b/swift/Sources/LibSignalClient/zkgroup/BackupAuthCredentialRequestContext.swift @@ -7,7 +7,6 @@ import Foundation import SignalFfi public class BackupAuthCredentialRequestContext: ByteArray { - public required init(contents: [UInt8]) throws { try super.init(contents, checkValid: signal_backup_auth_credential_request_context_check_valid_contents) } @@ -47,5 +46,4 @@ public class BackupAuthCredentialRequestContext: ByteArray { } } } - } diff --git a/swift/Sources/LibSignalClient/zkgroup/ByteArray.swift b/swift/Sources/LibSignalClient/zkgroup/ByteArray.swift index 6496a27f..d7f9e1dc 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ByteArray.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ByteArray.swift @@ -10,8 +10,8 @@ public class ByteArray { private let contents: [UInt8] init(_ newContents: [UInt8], checkValid: (SignalBorrowedBuffer) -> SignalFfiErrorRef?) throws { - contents = newContents - try withUnsafeBorrowedBuffer { buffer in + self.contents = newContents + try self.withUnsafeBorrowedBuffer { buffer in try checkError(checkValid(buffer)) } } @@ -20,7 +20,7 @@ public class ByteArray { if newContents.count != expectedLength { throw SignalError.invalidType("\(type(of: self)) uses \(expectedLength) bytes, but tried to deserialize from an array of \(newContents.count) bytes") } - contents = newContents + self.contents = newContents } required init(contents: [UInt8]) throws { @@ -28,7 +28,7 @@ public class ByteArray { } public func serialize() -> [UInt8] { - return contents + return self.contents } /// Passes a pointer to the serialized contents to `callback`. @@ -45,7 +45,7 @@ public class ByteArray { func withUnsafePointerToSerialized(_ callback: (UnsafePointer) throws -> Result) throws -> Result { precondition(MemoryLayout.alignment == 1, "not a fixed-sized array (tuple) of UInt8") - return try contents.withUnsafeBytes { buffer in + return try self.contents.withUnsafeBytes { buffer in let expectedSize = MemoryLayout.size guard expectedSize == buffer.count else { throw SignalError.invalidType("\(type(of: self)) uses \(buffer.count) bytes, but was passed to a callback that uses \(expectedSize) bytes") @@ -64,6 +64,6 @@ public class ByteArray { /// /// Used for types that don't have a fixed-length representation. func withUnsafeBorrowedBuffer(_ callback: (SignalBorrowedBuffer) throws -> Result) throws -> Result { - return try contents.withUnsafeBorrowedBuffer(callback) + return try self.contents.withUnsafeBorrowedBuffer(callback) } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredential.swift b/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredential.swift index aba94c04..fc68d300 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredential.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredential.swift @@ -7,33 +7,31 @@ import Foundation import SignalFfi public class CallLinkAuthCredential: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_call_link_auth_credential_check_valid_contents) - } - - public func present(userId: Aci, redemptionTime: Date, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams) -> CallLinkAuthCredentialPresentation { - return failOnError { - present(userId: userId, redemptionTime: redemptionTime, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate()) + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_call_link_auth_credential_check_valid_contents) } - } - public func present(userId: Aci, redemptionTime: Date, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams, randomness: Randomness) -> CallLinkAuthCredentialPresentation { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try userId.withPointerToFixedWidthBinary { userId in - try serverParams.withUnsafeBorrowedBuffer { serverParams in - try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_call_link_auth_credential_present_deterministic($0, contents, userId, UInt64(redemptionTime.timeIntervalSince1970), serverParams, callLinkParams, randomness) - } - } - } - } + public func present(userId: Aci, redemptionTime: Date, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams) -> CallLinkAuthCredentialPresentation { + return failOnError { + self.present(userId: userId, redemptionTime: redemptionTime, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate()) } - } } - } + public func present(userId: Aci, redemptionTime: Date, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams, randomness: Randomness) -> CallLinkAuthCredentialPresentation { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try userId.withPointerToFixedWidthBinary { userId in + try serverParams.withUnsafeBorrowedBuffer { serverParams in + try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_call_link_auth_credential_present_deterministic($0, contents, userId, UInt64(redemptionTime.timeIntervalSince1970), serverParams, callLinkParams, randomness) + } + } + } + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialPresentation.swift b/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialPresentation.swift index c4d64fb9..cea298fa 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialPresentation.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialPresentation.swift @@ -7,28 +7,27 @@ import Foundation import SignalFfi public class CallLinkAuthCredentialPresentation: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_call_link_auth_credential_presentation_check_valid_contents) - } - - public func verify(now: Date = Date(), serverParams: GenericServerSecretParams, callLinkParams: CallLinkPublicParams) throws { - try withUnsafeBorrowedBuffer { contents in - try serverParams.withUnsafeBorrowedBuffer { serverParams in - try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in - try checkError(signal_call_link_auth_credential_presentation_verify(contents, UInt64(now.timeIntervalSince1970), serverParams, callLinkParams)) - } - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_call_link_auth_credential_presentation_check_valid_contents) } - } - public var userId: UuidCiphertext { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try invokeFnReturningSerialized { - signal_call_link_auth_credential_presentation_get_user_id($0, contents) + public func verify(now: Date = Date(), serverParams: GenericServerSecretParams, callLinkParams: CallLinkPublicParams) throws { + try withUnsafeBorrowedBuffer { contents in + try serverParams.withUnsafeBorrowedBuffer { serverParams in + try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in + try checkError(signal_call_link_auth_credential_presentation_verify(contents, UInt64(now.timeIntervalSince1970), serverParams, callLinkParams)) + } + } + } + } + + public var userId: UuidCiphertext { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try invokeFnReturningSerialized { + signal_call_link_auth_credential_presentation_get_user_id($0, contents) + } + } } - } } - } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialResponse.swift b/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialResponse.swift index 3338ff0c..f105e124 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialResponse.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CallLinkAuthCredentialResponse.swift @@ -7,39 +7,39 @@ import Foundation import SignalFfi public class CallLinkAuthCredentialResponse: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_call_link_auth_credential_response_check_valid_contents) - } - - public static func issueCredential(userId: Aci, redemptionTime: Date, params: GenericServerSecretParams) -> CallLinkAuthCredentialResponse { - return failOnError { - issueCredential(userId: userId, redemptionTime: redemptionTime, params: params, randomness: try .generate()) + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_call_link_auth_credential_response_check_valid_contents) } - } - public static func issueCredential(userId: Aci, redemptionTime: Date, params: GenericServerSecretParams, randomness: Randomness) -> CallLinkAuthCredentialResponse { - return failOnError { - try userId.withPointerToFixedWidthBinary { userId in - try params.withUnsafeBorrowedBuffer { params in - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_call_link_auth_credential_response_issue_deterministic($0, userId, UInt64(redemptionTime.timeIntervalSince1970), params, randomness) + public static func issueCredential(userId: Aci, redemptionTime: Date, params: GenericServerSecretParams) -> CallLinkAuthCredentialResponse { + return failOnError { + self.issueCredential(userId: userId, redemptionTime: redemptionTime, params: params, randomness: try .generate()) + } + } + + public static func issueCredential(userId: Aci, redemptionTime: Date, params: GenericServerSecretParams, randomness: Randomness) -> CallLinkAuthCredentialResponse { + return failOnError { + try userId.withPointerToFixedWidthBinary { userId in + try params.withUnsafeBorrowedBuffer { params in + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_call_link_auth_credential_response_issue_deterministic($0, userId, UInt64(redemptionTime.timeIntervalSince1970), params, randomness) + } + } + } } - } } - } } - } - public func receive(userId: Aci, redemptionTime: Date, params: GenericServerPublicParams) throws -> CallLinkAuthCredential { - return try withUnsafeBorrowedBuffer { contents in - try userId.withPointerToFixedWidthBinary { userId in - try params.withUnsafeBorrowedBuffer { params in - try invokeFnReturningVariableLengthSerialized { - signal_call_link_auth_credential_response_receive($0, contents, userId, UInt64(redemptionTime.timeIntervalSince1970), params) - } + public func receive(userId: Aci, redemptionTime: Date, params: GenericServerPublicParams) throws -> CallLinkAuthCredential { + return try withUnsafeBorrowedBuffer { contents in + try userId.withPointerToFixedWidthBinary { userId in + try params.withUnsafeBorrowedBuffer { params in + try invokeFnReturningVariableLengthSerialized { + signal_call_link_auth_credential_response_receive($0, contents, userId, UInt64(redemptionTime.timeIntervalSince1970), params) + } + } + } } - } } - } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CallLinkPublicParams.swift b/swift/Sources/LibSignalClient/zkgroup/CallLinkPublicParams.swift index 90d9a8da..4327685d 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CallLinkPublicParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CallLinkPublicParams.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class CallLinkPublicParams: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_call_link_public_params_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_call_link_public_params_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CallLinkSecretParams.swift b/swift/Sources/LibSignalClient/zkgroup/CallLinkSecretParams.swift index eaa45f7f..cbf08663 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CallLinkSecretParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CallLinkSecretParams.swift @@ -7,39 +7,37 @@ import Foundation import SignalFfi public class CallLinkSecretParams: ByteArray { - - public static func deriveFromRootKey(_ rootKey: RootKey) -> CallLinkSecretParams { - return failOnError { - try rootKey.withUnsafeBorrowedBuffer { rootKey in - try invokeFnReturningVariableLengthSerialized { - signal_call_link_secret_params_derive_from_root_key($0, rootKey) + public static func deriveFromRootKey(_ rootKey: RootKey) -> CallLinkSecretParams { + return failOnError { + try rootKey.withUnsafeBorrowedBuffer { rootKey in + try invokeFnReturningVariableLengthSerialized { + signal_call_link_secret_params_derive_from_root_key($0, rootKey) + } + } } - } } - } - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_call_link_secret_params_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_call_link_secret_params_check_valid_contents) + } - public func getPublicParams() -> CallLinkPublicParams { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try invokeFnReturningVariableLengthSerialized { - signal_call_link_secret_params_get_public_params($0, contents) + public func getPublicParams() -> CallLinkPublicParams { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try invokeFnReturningVariableLengthSerialized { + signal_call_link_secret_params_get_public_params($0, contents) + } + } } - } } - } - public func decrypt(_ ciphertext: UuidCiphertext) throws -> Aci { - return try withUnsafeBorrowedBuffer { contents in - try ciphertext.withUnsafePointerToSerialized { ciphertext in - try invokeFnReturningServiceId { - signal_call_link_secret_params_decrypt_user_id($0, contents, ciphertext) + public func decrypt(_ ciphertext: UuidCiphertext) throws -> Aci { + return try withUnsafeBorrowedBuffer { contents in + try ciphertext.withUnsafePointerToSerialized { ciphertext in + try invokeFnReturningServiceId { + signal_call_link_secret_params_decrypt_user_id($0, contents, ciphertext) + } + } } - } } - } - } diff --git a/swift/Sources/LibSignalClient/zkgroup/ClientZkAuthOperations.swift b/swift/Sources/LibSignalClient/zkgroup/ClientZkAuthOperations.swift index 2d7e512b..2e64b285 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ClientZkAuthOperations.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ClientZkAuthOperations.swift @@ -7,96 +7,94 @@ import Foundation import SignalFfi public class ClientZkAuthOperations { + let serverPublicParams: ServerPublicParams - let serverPublicParams: ServerPublicParams - - public init(serverPublicParams: ServerPublicParams) { - self.serverPublicParams = serverPublicParams - } - - public func receiveAuthCredential(aci: Aci, redemptionTime: UInt32, authCredentialResponse: AuthCredentialResponse) throws -> AuthCredential { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try aci.withPointerToFixedWidthBinary { uuid in - try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in - try invokeFnReturningSerialized { - signal_server_public_params_receive_auth_credential($0, serverPublicParams, uuid, redemptionTime, authCredentialResponse) - } - } - } + public init(serverPublicParams: ServerPublicParams) { + self.serverPublicParams = serverPublicParams } - } - /// Produces the `AuthCredentialWithPni` from a server-generated `AuthCredentialWithPniResponse`. - /// - /// - parameter redemptionTime: This is provided by the server as an integer, and should be passed through directly. - public func receiveAuthCredentialWithPniAsServiceId(aci: Aci, pni: Pni, redemptionTime: UInt64, authCredentialResponse: AuthCredentialWithPniResponse) throws -> AuthCredentialWithPni { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try aci.withPointerToFixedWidthBinary { aci in - try pni.withPointerToFixedWidthBinary { pni in - try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in - try invokeFnReturningSerialized { - signal_server_public_params_receive_auth_credential_with_pni_as_service_id($0, serverPublicParams, aci, pni, redemptionTime, authCredentialResponse) + public func receiveAuthCredential(aci: Aci, redemptionTime: UInt32, authCredentialResponse: AuthCredentialResponse) throws -> AuthCredential { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try aci.withPointerToFixedWidthBinary { uuid in + try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in + try invokeFnReturningSerialized { + signal_server_public_params_receive_auth_credential($0, serverPublicParams, uuid, redemptionTime, authCredentialResponse) + } + } } - } } - } } - } - /// Produces the `AuthCredentialWithPni` from a server-generated `AuthCredentialWithPniResponse`. - /// - /// This older style of AuthCredentialWithPni will not actually have a usable PNI field, - /// but can still be used for authenticating with an ACI. - /// - /// - parameter redemptionTime: This is provided by the server as an integer, and should be passed through directly. - public func receiveAuthCredentialWithPniAsAci(aci: Aci, pni: Pni, redemptionTime: UInt64, authCredentialResponse: AuthCredentialWithPniResponse) throws -> AuthCredentialWithPni { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try aci.withPointerToFixedWidthBinary { aci in - try pni.withPointerToFixedWidthBinary { pni in - try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in - try invokeFnReturningSerialized { - signal_server_public_params_receive_auth_credential_with_pni_as_aci($0, serverPublicParams, aci, pni, redemptionTime, authCredentialResponse) + /// Produces the `AuthCredentialWithPni` from a server-generated `AuthCredentialWithPniResponse`. + /// + /// - parameter redemptionTime: This is provided by the server as an integer, and should be passed through directly. + public func receiveAuthCredentialWithPniAsServiceId(aci: Aci, pni: Pni, redemptionTime: UInt64, authCredentialResponse: AuthCredentialWithPniResponse) throws -> AuthCredentialWithPni { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try aci.withPointerToFixedWidthBinary { aci in + try pni.withPointerToFixedWidthBinary { pni in + try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in + try invokeFnReturningSerialized { + signal_server_public_params_receive_auth_credential_with_pni_as_service_id($0, serverPublicParams, aci, pni, redemptionTime, authCredentialResponse) + } + } + } } - } } - } } - } - public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation { - return try createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential) - } - - public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation { - return try serverPublicParams.withUnsafePointerToSerialized { contents in - try randomness.withUnsafePointerToBytes { randomness in - try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try authCredential.withUnsafePointerToSerialized { authCredential in - try invokeFnReturningVariableLengthSerialized { - signal_server_public_params_create_auth_credential_presentation_deterministic($0, contents, randomness, groupSecretParams, authCredential) + /// Produces the `AuthCredentialWithPni` from a server-generated `AuthCredentialWithPniResponse`. + /// + /// This older style of AuthCredentialWithPni will not actually have a usable PNI field, + /// but can still be used for authenticating with an ACI. + /// + /// - parameter redemptionTime: This is provided by the server as an integer, and should be passed through directly. + public func receiveAuthCredentialWithPniAsAci(aci: Aci, pni: Pni, redemptionTime: UInt64, authCredentialResponse: AuthCredentialWithPniResponse) throws -> AuthCredentialWithPni { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try aci.withPointerToFixedWidthBinary { aci in + try pni.withPointerToFixedWidthBinary { pni in + try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in + try invokeFnReturningSerialized { + signal_server_public_params_receive_auth_credential_with_pni_as_aci($0, serverPublicParams, aci, pni, redemptionTime, authCredentialResponse) + } + } + } } - } } - } } - } - public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation { - return try createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential) - } + public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation { + return try self.createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential) + } - public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation { - return try serverPublicParams.withUnsafePointerToSerialized { contents in - try randomness.withUnsafePointerToBytes { randomness in - try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try authCredential.withUnsafePointerToSerialized { authCredential in - try invokeFnReturningVariableLengthSerialized { - signal_server_public_params_create_auth_credential_with_pni_presentation_deterministic($0, contents, randomness, groupSecretParams, authCredential) + public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation { + return try self.serverPublicParams.withUnsafePointerToSerialized { contents in + try randomness.withUnsafePointerToBytes { randomness in + try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try authCredential.withUnsafePointerToSerialized { authCredential in + try invokeFnReturningVariableLengthSerialized { + signal_server_public_params_create_auth_credential_presentation_deterministic($0, contents, randomness, groupSecretParams, authCredential) + } + } + } } - } } - } } - } + public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation { + return try self.createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential) + } + + public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation { + return try self.serverPublicParams.withUnsafePointerToSerialized { contents in + try randomness.withUnsafePointerToBytes { randomness in + try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try authCredential.withUnsafePointerToSerialized { authCredential in + try invokeFnReturningVariableLengthSerialized { + signal_server_public_params_create_auth_credential_with_pni_presentation_deterministic($0, contents, randomness, groupSecretParams, authCredential) + } + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ClientZkGroupCipher.swift b/swift/Sources/LibSignalClient/zkgroup/ClientZkGroupCipher.swift index 20a3435b..827b6369 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ClientZkGroupCipher.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ClientZkGroupCipher.swift @@ -7,81 +7,79 @@ import Foundation import SignalFfi public class ClientZkGroupCipher { + let groupSecretParams: GroupSecretParams - let groupSecretParams: GroupSecretParams - - public init(groupSecretParams: GroupSecretParams) { - self.groupSecretParams = groupSecretParams - } - - public func encrypt(_ serviceId: ServiceId) throws -> UuidCiphertext { - return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try serviceId.withPointerToFixedWidthBinary { serviceId in - try invokeFnReturningSerialized { - signal_group_secret_params_encrypt_service_id($0, groupSecretParams, serviceId) - } - } + public init(groupSecretParams: GroupSecretParams) { + self.groupSecretParams = groupSecretParams } - } - public func decrypt(_ uuidCiphertext: UuidCiphertext) throws -> ServiceId { - return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try uuidCiphertext.withUnsafePointerToSerialized { uuidCiphertext in - try invokeFnReturningServiceId { - signal_group_secret_params_decrypt_service_id($0, groupSecretParams, uuidCiphertext) + public func encrypt(_ serviceId: ServiceId) throws -> UuidCiphertext { + return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try serviceId.withPointerToFixedWidthBinary { serviceId in + try invokeFnReturningSerialized { + signal_group_secret_params_encrypt_service_id($0, groupSecretParams, serviceId) + } + } } - } } - } - public func encryptProfileKey(profileKey: ProfileKey, userId: Aci) throws -> ProfileKeyCiphertext { - return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try profileKey.withUnsafePointerToSerialized { profileKey in - try userId.withPointerToFixedWidthBinary { userId in - try invokeFnReturningSerialized { - signal_group_secret_params_encrypt_profile_key($0, groupSecretParams, profileKey, userId) - } + public func decrypt(_ uuidCiphertext: UuidCiphertext) throws -> ServiceId { + return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try uuidCiphertext.withUnsafePointerToSerialized { uuidCiphertext in + try invokeFnReturningServiceId { + signal_group_secret_params_decrypt_service_id($0, groupSecretParams, uuidCiphertext) + } + } } - } } - } - public func decryptProfileKey(profileKeyCiphertext: ProfileKeyCiphertext, userId: Aci) throws -> ProfileKey { - return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try profileKeyCiphertext.withUnsafePointerToSerialized { profileKeyCiphertext in - try userId.withPointerToFixedWidthBinary { userId in - try invokeFnReturningSerialized { - signal_group_secret_params_decrypt_profile_key($0, groupSecretParams, profileKeyCiphertext, userId ) - } + public func encryptProfileKey(profileKey: ProfileKey, userId: Aci) throws -> ProfileKeyCiphertext { + return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try profileKey.withUnsafePointerToSerialized { profileKey in + try userId.withPointerToFixedWidthBinary { userId in + try invokeFnReturningSerialized { + signal_group_secret_params_encrypt_profile_key($0, groupSecretParams, profileKey, userId) + } + } + } } - } } - } - public func encryptBlob(plaintext: [UInt8]) throws -> [UInt8] { - return try encryptBlob(randomness: Randomness.generate(), plaintext: plaintext) - } - - public func encryptBlob(randomness: Randomness, plaintext: [UInt8]) throws -> [UInt8] { - return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try randomness.withUnsafePointerToBytes { randomness in - try plaintext.withUnsafeBorrowedBuffer { plaintext in - try invokeFnReturningArray { - signal_group_secret_params_encrypt_blob_with_padding_deterministic($0, groupSecretParams, randomness, plaintext, 0) - } + public func decryptProfileKey(profileKeyCiphertext: ProfileKeyCiphertext, userId: Aci) throws -> ProfileKey { + return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try profileKeyCiphertext.withUnsafePointerToSerialized { profileKeyCiphertext in + try userId.withPointerToFixedWidthBinary { userId in + try invokeFnReturningSerialized { + signal_group_secret_params_decrypt_profile_key($0, groupSecretParams, profileKeyCiphertext, userId) + } + } + } } - } } - } - public func decryptBlob(blobCiphertext: [UInt8]) throws -> [UInt8] { - return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try blobCiphertext.withUnsafeBorrowedBuffer { blobCiphertext in - try invokeFnReturningArray { - signal_group_secret_params_decrypt_blob_with_padding($0, groupSecretParams, blobCiphertext) + public func encryptBlob(plaintext: [UInt8]) throws -> [UInt8] { + return try self.encryptBlob(randomness: Randomness.generate(), plaintext: plaintext) + } + + public func encryptBlob(randomness: Randomness, plaintext: [UInt8]) throws -> [UInt8] { + return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try randomness.withUnsafePointerToBytes { randomness in + try plaintext.withUnsafeBorrowedBuffer { plaintext in + try invokeFnReturningArray { + signal_group_secret_params_encrypt_blob_with_padding_deterministic($0, groupSecretParams, randomness, plaintext, 0) + } + } + } } - } } - } + public func decryptBlob(blobCiphertext: [UInt8]) throws -> [UInt8] { + return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try blobCiphertext.withUnsafeBorrowedBuffer { blobCiphertext in + try invokeFnReturningArray { + signal_group_secret_params_decrypt_blob_with_padding($0, groupSecretParams, blobCiphertext) + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ClientZkProfileOperations.swift b/swift/Sources/LibSignalClient/zkgroup/ClientZkProfileOperations.swift index aa526dc6..1340715f 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ClientZkProfileOperations.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ClientZkProfileOperations.swift @@ -7,63 +7,61 @@ import Foundation import SignalFfi public class ClientZkProfileOperations { + let serverPublicParams: ServerPublicParams - let serverPublicParams: ServerPublicParams + public init(serverPublicParams: ServerPublicParams) { + self.serverPublicParams = serverPublicParams + } - public init(serverPublicParams: ServerPublicParams) { - self.serverPublicParams = serverPublicParams - } + public func createProfileKeyCredentialRequestContext(userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext { + return try self.createProfileKeyCredentialRequestContext(randomness: Randomness.generate(), userId: userId, profileKey: profileKey) + } - public func createProfileKeyCredentialRequestContext(userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext { - return try createProfileKeyCredentialRequestContext(randomness: Randomness.generate(), userId: userId, profileKey: profileKey) - } - - public func createProfileKeyCredentialRequestContext(randomness: Randomness, userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try randomness.withUnsafePointerToBytes { randomness in - try userId.withPointerToFixedWidthBinary { userId in - try profileKey.withUnsafePointerToSerialized { profileKey in - try invokeFnReturningSerialized { - signal_server_public_params_create_profile_key_credential_request_context_deterministic($0, serverPublicParams, randomness, userId, profileKey) + public func createProfileKeyCredentialRequestContext(randomness: Randomness, userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try randomness.withUnsafePointerToBytes { randomness in + try userId.withPointerToFixedWidthBinary { userId in + try profileKey.withUnsafePointerToSerialized { profileKey in + try invokeFnReturningSerialized { + signal_server_public_params_create_profile_key_credential_request_context_deterministic($0, serverPublicParams, randomness, userId, profileKey) + } + } + } } - } } - } } - } - public func receiveExpiringProfileKeyCredential( - profileKeyCredentialRequestContext: ProfileKeyCredentialRequestContext, - profileKeyCredentialResponse: ExpiringProfileKeyCredentialResponse, - now: Date = Date() - ) throws -> ExpiringProfileKeyCredential { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try profileKeyCredentialRequestContext.withUnsafePointerToSerialized { requestContext in - try profileKeyCredentialResponse.withUnsafePointerToSerialized { response in - try invokeFnReturningSerialized { - signal_server_public_params_receive_expiring_profile_key_credential($0, serverPublicParams, requestContext, response, UInt64(now.timeIntervalSince1970)) - } - } - } - } - } - - public func createProfileKeyCredentialPresentation(groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation { - return try createProfileKeyCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, profileKeyCredential: profileKeyCredential) - } - - public func createProfileKeyCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try randomness.withUnsafePointerToBytes { randomness in - try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in - try profileKeyCredential.withUnsafePointerToSerialized { profileKeyCredential in - try invokeFnReturningVariableLengthSerialized { - signal_server_public_params_create_expiring_profile_key_credential_presentation_deterministic($0, serverPublicParams, randomness, groupSecretParams, profileKeyCredential) + public func receiveExpiringProfileKeyCredential( + profileKeyCredentialRequestContext: ProfileKeyCredentialRequestContext, + profileKeyCredentialResponse: ExpiringProfileKeyCredentialResponse, + now: Date = Date() + ) throws -> ExpiringProfileKeyCredential { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try profileKeyCredentialRequestContext.withUnsafePointerToSerialized { requestContext in + try profileKeyCredentialResponse.withUnsafePointerToSerialized { response in + try invokeFnReturningSerialized { + signal_server_public_params_receive_expiring_profile_key_credential($0, serverPublicParams, requestContext, response, UInt64(now.timeIntervalSince1970)) + } + } } - } } - } } - } + public func createProfileKeyCredentialPresentation(groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation { + return try self.createProfileKeyCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, profileKeyCredential: profileKeyCredential) + } + + public func createProfileKeyCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try randomness.withUnsafePointerToBytes { randomness in + try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in + try profileKeyCredential.withUnsafePointerToSerialized { profileKeyCredential in + try invokeFnReturningVariableLengthSerialized { + signal_server_public_params_create_expiring_profile_key_credential_presentation_deterministic($0, serverPublicParams, randomness, groupSecretParams, profileKeyCredential) + } + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ClientZkReceiptOperations.swift b/swift/Sources/LibSignalClient/zkgroup/ClientZkReceiptOperations.swift index 98983795..42462a79 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ClientZkReceiptOperations.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ClientZkReceiptOperations.swift @@ -7,55 +7,53 @@ import Foundation import SignalFfi public class ClientZkReceiptOperations { + let serverPublicParams: ServerPublicParams - let serverPublicParams: ServerPublicParams - - public init(serverPublicParams: ServerPublicParams) { - self.serverPublicParams = serverPublicParams - } - - public func createReceiptCredentialRequestContext(receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext { - return try createReceiptCredentialRequestContext(randomness: Randomness.generate(), receiptSerial: receiptSerial) - } - - public func createReceiptCredentialRequestContext(randomness: Randomness, receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try randomness.withUnsafePointerToBytes { randomness in - try receiptSerial.withUnsafePointerToSerialized { receiptSerial in - try invokeFnReturningSerialized { - signal_server_public_params_create_receipt_credential_request_context_deterministic($0, serverPublicParams, randomness, receiptSerial) - } - } - } + public init(serverPublicParams: ServerPublicParams) { + self.serverPublicParams = serverPublicParams } - } - public func receiveReceiptCredential(receiptCredentialRequestContext: ReceiptCredentialRequestContext, receiptCredentialResponse: ReceiptCredentialResponse) throws -> ReceiptCredential { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try receiptCredentialRequestContext.withUnsafePointerToSerialized { requestContext in - try receiptCredentialResponse.withUnsafePointerToSerialized { response in - try invokeFnReturningSerialized { - signal_server_public_params_receive_receipt_credential($0, serverPublicParams, requestContext, response) - } - } - } + public func createReceiptCredentialRequestContext(receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext { + return try self.createReceiptCredentialRequestContext(randomness: Randomness.generate(), receiptSerial: receiptSerial) } - } - public func createReceiptCredentialPresentation(receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation { - return try createReceiptCredentialPresentation(randomness: Randomness.generate(), receiptCredential: receiptCredential) - } - - public func createReceiptCredentialPresentation(randomness: Randomness, receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation { - return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in - try randomness.withUnsafePointerToBytes { randomness in - try receiptCredential.withUnsafePointerToSerialized { receiptCredential in - try invokeFnReturningSerialized { - signal_server_public_params_create_receipt_credential_presentation_deterministic($0, serverPublicParams, randomness, receiptCredential) - } + public func createReceiptCredentialRequestContext(randomness: Randomness, receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try randomness.withUnsafePointerToBytes { randomness in + try receiptSerial.withUnsafePointerToSerialized { receiptSerial in + try invokeFnReturningSerialized { + signal_server_public_params_create_receipt_credential_request_context_deterministic($0, serverPublicParams, randomness, receiptSerial) + } + } + } } - } } - } + public func receiveReceiptCredential(receiptCredentialRequestContext: ReceiptCredentialRequestContext, receiptCredentialResponse: ReceiptCredentialResponse) throws -> ReceiptCredential { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try receiptCredentialRequestContext.withUnsafePointerToSerialized { requestContext in + try receiptCredentialResponse.withUnsafePointerToSerialized { response in + try invokeFnReturningSerialized { + signal_server_public_params_receive_receipt_credential($0, serverPublicParams, requestContext, response) + } + } + } + } + } + + public func createReceiptCredentialPresentation(receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation { + return try self.createReceiptCredentialPresentation(randomness: Randomness.generate(), receiptCredential: receiptCredential) + } + + public func createReceiptCredentialPresentation(randomness: Randomness, receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation { + return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in + try randomness.withUnsafePointerToBytes { randomness in + try receiptCredential.withUnsafePointerToSerialized { receiptCredential in + try invokeFnReturningSerialized { + signal_server_public_params_create_receipt_credential_presentation_deterministic($0, serverPublicParams, randomness, receiptCredential) + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredential.swift b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredential.swift index d8d76f58..86248bd1 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredential.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredential.swift @@ -7,35 +7,33 @@ import Foundation import SignalFfi public class CreateCallLinkCredential: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_create_call_link_credential_check_valid_contents) - } - - public func present(roomId: RoomId, userId: Aci, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams) -> CreateCallLinkCredentialPresentation { - return failOnError { - present(roomId: roomId, userId: userId, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate()) + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_create_call_link_credential_check_valid_contents) } - } - public func present(roomId: RoomId, userId: Aci, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams, randomness: Randomness) -> CreateCallLinkCredentialPresentation { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try roomId.withUnsafeBorrowedBuffer { roomId in - try userId.withPointerToFixedWidthBinary { userId in - try serverParams.withUnsafeBorrowedBuffer { serverParams in - try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_create_call_link_credential_present_deterministic($0, contents, roomId, userId, serverParams, callLinkParams, randomness) - } - } - } - } - } + public func present(roomId: RoomId, userId: Aci, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams) -> CreateCallLinkCredentialPresentation { + return failOnError { + self.present(roomId: roomId, userId: userId, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate()) } - } } - } + public func present(roomId: RoomId, userId: Aci, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams, randomness: Randomness) -> CreateCallLinkCredentialPresentation { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try roomId.withUnsafeBorrowedBuffer { roomId in + try userId.withPointerToFixedWidthBinary { userId in + try serverParams.withUnsafeBorrowedBuffer { serverParams in + try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_create_call_link_credential_present_deterministic($0, contents, roomId, userId, serverParams, callLinkParams, randomness) + } + } + } + } + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialPresentation.swift b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialPresentation.swift index 5befb7bf..abfeced6 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialPresentation.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialPresentation.swift @@ -7,21 +7,19 @@ import Foundation import SignalFfi public class CreateCallLinkCredentialPresentation: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_create_call_link_credential_presentation_check_valid_contents) - } - - public func verify(roomId: RoomId, now: Date = Date(), serverParams: GenericServerSecretParams, callLinkParams: CallLinkPublicParams) throws { - try withUnsafeBorrowedBuffer { contents in - try roomId.withUnsafeBorrowedBuffer { roomId in - try serverParams.withUnsafeBorrowedBuffer { serverParams in - try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in - try checkError(signal_create_call_link_credential_presentation_verify(contents, roomId, UInt64(now.timeIntervalSince1970), serverParams, callLinkParams)) - } - } - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_create_call_link_credential_presentation_check_valid_contents) } - } + public func verify(roomId: RoomId, now: Date = Date(), serverParams: GenericServerSecretParams, callLinkParams: CallLinkPublicParams) throws { + try withUnsafeBorrowedBuffer { contents in + try roomId.withUnsafeBorrowedBuffer { roomId in + try serverParams.withUnsafeBorrowedBuffer { serverParams in + try callLinkParams.withUnsafeBorrowedBuffer { callLinkParams in + try checkError(signal_create_call_link_credential_presentation_verify(contents, roomId, UInt64(now.timeIntervalSince1970), serverParams, callLinkParams)) + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequest.swift b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequest.swift index 5894ff84..ba149f58 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequest.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequest.swift @@ -7,29 +7,29 @@ import Foundation import SignalFfi public class CreateCallLinkCredentialRequest: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_create_call_link_credential_request_check_valid_contents) - } - - public func issueCredential(userId: Aci, timestamp: Date, params: GenericServerSecretParams) -> CreateCallLinkCredentialResponse { - return failOnError { - issueCredential(userId: userId, timestamp: timestamp, params: params, randomness: try .generate()) + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_create_call_link_credential_request_check_valid_contents) } - } - public func issueCredential(userId: Aci, timestamp: Date, params: GenericServerSecretParams, randomness: Randomness) -> CreateCallLinkCredentialResponse { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try userId.withPointerToFixedWidthBinary { userId in - try params.withUnsafeBorrowedBuffer { params in - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_create_call_link_credential_request_issue_deterministic($0, contents, userId, UInt64(timestamp.timeIntervalSince1970), params, randomness) - } - } - } + public func issueCredential(userId: Aci, timestamp: Date, params: GenericServerSecretParams) -> CreateCallLinkCredentialResponse { + return failOnError { + self.issueCredential(userId: userId, timestamp: timestamp, params: params, randomness: try .generate()) + } + } + + public func issueCredential(userId: Aci, timestamp: Date, params: GenericServerSecretParams, randomness: Randomness) -> CreateCallLinkCredentialResponse { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try userId.withPointerToFixedWidthBinary { userId in + try params.withUnsafeBorrowedBuffer { params in + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_create_call_link_credential_request_issue_deterministic($0, contents, userId, UInt64(timestamp.timeIntervalSince1970), params, randomness) + } + } + } + } + } } - } } - } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequestContext.swift b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequestContext.swift index 156a583b..2428ce53 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequestContext.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialRequestContext.swift @@ -7,51 +7,49 @@ import Foundation import SignalFfi public class CreateCallLinkCredentialRequestContext: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_create_call_link_credential_request_context_check_valid_contents) - } - - public static func forRoomId(_ roomId: RoomId) -> Self { - return failOnError { - self.forRoomId(roomId, randomness: try .generate()) + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_create_call_link_credential_request_context_check_valid_contents) } - } - public static func forRoomId(_ roomId: RoomId, randomness: Randomness) -> Self { - return failOnError { - try roomId.withUnsafeBorrowedBuffer { roomId in - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_create_call_link_credential_request_context_new_deterministic($0, roomId, randomness) - } + public static func forRoomId(_ roomId: RoomId) -> Self { + return failOnError { + self.forRoomId(roomId, randomness: try .generate()) } - } } - } - public func getRequest() -> CreateCallLinkCredentialRequest { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try invokeFnReturningVariableLengthSerialized { - signal_create_call_link_credential_request_context_get_request($0, contents) - } - } - } - } - - public func receive(_ response: CreateCallLinkCredentialResponse, userId: Aci, params: GenericServerPublicParams) throws -> CreateCallLinkCredential { - return try withUnsafeBorrowedBuffer { contents in - try response.withUnsafeBorrowedBuffer { response in - try userId.withPointerToFixedWidthBinary { userId in - try params.withUnsafeBorrowedBuffer { params in - try invokeFnReturningVariableLengthSerialized { - signal_create_call_link_credential_request_context_receive_response($0, contents, response, userId, params) + public static func forRoomId(_ roomId: RoomId, randomness: Randomness) -> Self { + return failOnError { + try roomId.withUnsafeBorrowedBuffer { roomId in + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_create_call_link_credential_request_context_new_deterministic($0, roomId, randomness) + } + } } - } } - } } - } + public func getRequest() -> CreateCallLinkCredentialRequest { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try invokeFnReturningVariableLengthSerialized { + signal_create_call_link_credential_request_context_get_request($0, contents) + } + } + } + } + + public func receive(_ response: CreateCallLinkCredentialResponse, userId: Aci, params: GenericServerPublicParams) throws -> CreateCallLinkCredential { + return try withUnsafeBorrowedBuffer { contents in + try response.withUnsafeBorrowedBuffer { response in + try userId.withPointerToFixedWidthBinary { userId in + try params.withUnsafeBorrowedBuffer { params in + try invokeFnReturningVariableLengthSerialized { + signal_create_call_link_credential_request_context_receive_response($0, contents, response, userId, params) + } + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialResponse.swift b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialResponse.swift index 7cbd769b..919f7f0d 100644 --- a/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialResponse.swift +++ b/swift/Sources/LibSignalClient/zkgroup/CreateCallLinkCredentialResponse.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class CreateCallLinkCredentialResponse: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_create_call_link_credential_response_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_create_call_link_credential_response_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredential.swift b/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredential.swift index 65c93c18..202e5826 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredential.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredential.swift @@ -7,18 +7,18 @@ import Foundation import SignalFfi public class ExpiringProfileKeyCredential: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_expiring_profile_key_credential_check_valid_contents) - } - - public var expirationTime: Date { - let timestampInSeconds = failOnError { - try self.withUnsafePointerToSerialized { contents in - try invokeFnReturningInteger { - signal_expiring_profile_key_credential_get_expiration_time($0, contents) - } - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_expiring_profile_key_credential_check_valid_contents) + } + + public var expirationTime: Date { + let timestampInSeconds = failOnError { + try self.withUnsafePointerToSerialized { contents in + try invokeFnReturningInteger { + signal_expiring_profile_key_credential_get_expiration_time($0, contents) + } + } + } + return Date(timeIntervalSince1970: TimeInterval(timestampInSeconds)) } - return Date(timeIntervalSince1970: TimeInterval(timestampInSeconds)) - } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredentialResponse.swift b/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredentialResponse.swift index afa21064..1ad6ad12 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredentialResponse.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ExpiringProfileKeyCredentialResponse.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class ExpiringProfileKeyCredentialResponse: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_expiring_profile_key_credential_response_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_expiring_profile_key_credential_response_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GenericServerPublicParams.swift b/swift/Sources/LibSignalClient/zkgroup/GenericServerPublicParams.swift index 84f8f455..362175bb 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GenericServerPublicParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GenericServerPublicParams.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class GenericServerPublicParams: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_generic_server_public_params_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_generic_server_public_params_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GenericServerSecretParams.swift b/swift/Sources/LibSignalClient/zkgroup/GenericServerSecretParams.swift index 3b11d55e..24454701 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GenericServerSecretParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GenericServerSecretParams.swift @@ -7,35 +7,33 @@ import Foundation import SignalFfi public class GenericServerSecretParams: ByteArray { - - public static func generate() -> Self { - return failOnError { - generate(randomness: try .generate()) - } - } - - public static func generate(randomness: Randomness) -> Self { - return failOnError { - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_generic_server_secret_params_generate_deterministic($0, randomness) + public static func generate() -> Self { + return failOnError { + self.generate(randomness: try .generate()) } - } } - } - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_generic_server_secret_params_check_valid_contents) - } - - public func getPublicParams() -> GenericServerPublicParams { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try invokeFnReturningVariableLengthSerialized { - signal_generic_server_secret_params_get_public_params($0, contents) + public static func generate(randomness: Randomness) -> Self { + return failOnError { + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_generic_server_secret_params_generate_deterministic($0, randomness) + } + } } - } } - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_generic_server_secret_params_check_valid_contents) + } + + public func getPublicParams() -> GenericServerPublicParams { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try invokeFnReturningVariableLengthSerialized { + signal_generic_server_secret_params_get_public_params($0, contents) + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GroupIdentifier.swift b/swift/Sources/LibSignalClient/zkgroup/GroupIdentifier.swift index 367c80a7..b567dad0 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GroupIdentifier.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GroupIdentifier.swift @@ -4,11 +4,9 @@ // public class GroupIdentifier: ByteArray { + public static let SIZE: Int = 32 - public static let SIZE: Int = 32 - - public required init(contents: [UInt8]) throws { - try super.init(newContents: contents, expectedLength: GroupIdentifier.SIZE) - } - + public required init(contents: [UInt8]) throws { + try super.init(newContents: contents, expectedLength: GroupIdentifier.SIZE) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GroupMasterKey.swift b/swift/Sources/LibSignalClient/zkgroup/GroupMasterKey.swift index e48bea05..507cbff1 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GroupMasterKey.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GroupMasterKey.swift @@ -4,11 +4,9 @@ // public class GroupMasterKey: ByteArray { + public static let SIZE: Int = 32 - public static let SIZE: Int = 32 - - public required init(contents: [UInt8]) throws { - try super.init(newContents: contents, expectedLength: GroupMasterKey.SIZE) - } - + public required init(contents: [UInt8]) throws { + try super.init(newContents: contents, expectedLength: GroupMasterKey.SIZE) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GroupPublicParams.swift b/swift/Sources/LibSignalClient/zkgroup/GroupPublicParams.swift index d87cd5a0..7f159e70 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GroupPublicParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GroupPublicParams.swift @@ -7,17 +7,15 @@ import Foundation import SignalFfi public class GroupPublicParams: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_group_public_params_check_valid_contents) - } - - public func getGroupIdentifier() throws -> GroupIdentifier { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningSerialized { - signal_group_public_params_get_group_identifier($0, contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_group_public_params_check_valid_contents) } - } + public func getGroupIdentifier() throws -> GroupIdentifier { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningSerialized { + signal_group_public_params_get_group_identifier($0, contents) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GroupSecretParams.swift b/swift/Sources/LibSignalClient/zkgroup/GroupSecretParams.swift index ae3cae6d..0e898021 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GroupSecretParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GroupSecretParams.swift @@ -7,45 +7,43 @@ import Foundation import SignalFfi public class GroupSecretParams: ByteArray { - - public static func generate() throws -> GroupSecretParams { - return try generate(randomness: Randomness.generate()) - } - - public static func generate(randomness: Randomness) throws -> GroupSecretParams { - return try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningSerialized { - signal_group_secret_params_generate_deterministic($0, randomness) - } + public static func generate() throws -> GroupSecretParams { + return try self.generate(randomness: Randomness.generate()) } - } - public static func deriveFromMasterKey(groupMasterKey: GroupMasterKey) throws -> GroupSecretParams { - return try groupMasterKey.withUnsafePointerToSerialized { groupMasterKey in - try invokeFnReturningSerialized { - signal_group_secret_params_derive_from_master_key($0, groupMasterKey) - } + public static func generate(randomness: Randomness) throws -> GroupSecretParams { + return try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningSerialized { + signal_group_secret_params_generate_deterministic($0, randomness) + } + } } - } - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_group_secret_params_check_valid_contents) - } - - public func getMasterKey() throws -> GroupMasterKey { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningSerialized { - signal_group_secret_params_get_master_key($0, contents) - } + public static func deriveFromMasterKey(groupMasterKey: GroupMasterKey) throws -> GroupSecretParams { + return try groupMasterKey.withUnsafePointerToSerialized { groupMasterKey in + try invokeFnReturningSerialized { + signal_group_secret_params_derive_from_master_key($0, groupMasterKey) + } + } } - } - public func getPublicParams() throws -> GroupPublicParams { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningSerialized { - signal_group_secret_params_get_public_params($0, contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_group_secret_params_check_valid_contents) } - } + public func getMasterKey() throws -> GroupMasterKey { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningSerialized { + signal_group_secret_params_get_master_key($0, contents) + } + } + } + + public func getPublicParams() throws -> GroupPublicParams { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningSerialized { + signal_group_secret_params_get_public_params($0, contents) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GroupSendCredential.swift b/swift/Sources/LibSignalClient/zkgroup/GroupSendCredential.swift index da63946b..341a43c7 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GroupSendCredential.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GroupSendCredential.swift @@ -16,38 +16,37 @@ import SignalFfi * - SeeAlso: ``GroupSendCredentialResponse``, ``GroupSendCredentialPresentation`` */ public class GroupSendCredential: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_group_send_credential_check_valid_contents) - } - - /** - * Generates a new presentation, so that multiple uses of this credential are harder to link. - */ - public func present(serverParams: ServerPublicParams) -> GroupSendCredentialPresentation { - return failOnError { - present(serverParams: serverParams, randomness: try .generate()) + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_group_send_credential_check_valid_contents) } - } - /** - * Generates a new presentation with a dedicated source of randomness. - * - * Should only be used for testing purposes. - * - * - SeeAlso: ``present(serverParams:)`` - */ - public func present(serverParams: ServerPublicParams, randomness: Randomness) -> GroupSendCredentialPresentation { - return failOnError { - try withUnsafeBorrowedBuffer { contents in - try serverParams.withUnsafePointerToSerialized { serverParams in - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_group_send_credential_present_deterministic($0, contents, serverParams, randomness) - } - } + /** + * Generates a new presentation, so that multiple uses of this credential are harder to link. + */ + public func present(serverParams: ServerPublicParams) -> GroupSendCredentialPresentation { + return failOnError { + self.present(serverParams: serverParams, randomness: try .generate()) + } + } + + /** + * Generates a new presentation with a dedicated source of randomness. + * + * Should only be used for testing purposes. + * + * - SeeAlso: ``present(serverParams:)`` + */ + public func present(serverParams: ServerPublicParams, randomness: Randomness) -> GroupSendCredentialPresentation { + return failOnError { + try withUnsafeBorrowedBuffer { contents in + try serverParams.withUnsafePointerToSerialized { serverParams in + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_group_send_credential_present_deterministic($0, contents, serverParams, randomness) + } + } + } + } } - } } - } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialPresentation.swift b/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialPresentation.swift index fadd9fc9..4df5a65c 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialPresentation.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialPresentation.swift @@ -16,23 +16,22 @@ import SignalFfi * - SeeAlso: ``GroupSendCredentialResponse``, ``GroupSendCredential`` */ public class GroupSendCredentialPresentation: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_group_send_credential_presentation_check_valid_contents) - } - - /** - * Verifies that the credential is valid for a group containing the holder and `groupMembers`. - * - * - Throws: ``SignalError/verificationFailed(_:)`` if the credential is not valid for any reason - */ - public func verify(groupMembers: [ServiceId], now: Date = Date(), serverParams: ServerSecretParams) throws { - try withUnsafeBorrowedBuffer { contents in - try ServiceId.concatenatedFixedWidthBinary(groupMembers).withUnsafeBorrowedBuffer { groupMembers in - try serverParams.withUnsafePointerToSerialized { serverParams in - try checkError(signal_group_send_credential_presentation_verify(contents, groupMembers, UInt64(now.timeIntervalSince1970), serverParams)) - } - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_group_send_credential_presentation_check_valid_contents) + } + + /** + * Verifies that the credential is valid for a group containing the holder and `groupMembers`. + * + * - Throws: ``SignalError/verificationFailed(_:)`` if the credential is not valid for any reason + */ + public func verify(groupMembers: [ServiceId], now: Date = Date(), serverParams: ServerSecretParams) throws { + try withUnsafeBorrowedBuffer { contents in + try ServiceId.concatenatedFixedWidthBinary(groupMembers).withUnsafeBorrowedBuffer { groupMembers in + try serverParams.withUnsafePointerToSerialized { serverParams in + try checkError(signal_group_send_credential_presentation_verify(contents, groupMembers, UInt64(now.timeIntervalSince1970), serverParams)) + } + } + } } - } } diff --git a/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialResponse.swift b/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialResponse.swift index 54ae665e..535c47cc 100644 --- a/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialResponse.swift +++ b/swift/Sources/LibSignalClient/zkgroup/GroupSendCredentialResponse.swift @@ -16,119 +16,120 @@ import SignalFfi * - SeeAlso: ``GroupSendCredential``, ``GroupSendCredentialPresentation`` */ public class GroupSendCredentialResponse: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_group_send_credential_response_check_valid_contents) - } - - public static func defaultExpiration() -> Date { - let expiration = failOnError { - try invokeFnReturningInteger { - signal_group_send_credential_response_default_expiration_based_on_current_time($0) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_group_send_credential_response_check_valid_contents) } - return Date(timeIntervalSince1970: TimeInterval(expiration)) - } - /** - * Issues a new credential stating that `requestingMember` is a member of a group containing - * `groupMembers`. - * - * `groupMembers` should include `requestingMember` as well. - */ - public static func issueCredential(groupMembers: [UuidCiphertext], requestingMember: UuidCiphertext, expiration: Date = GroupSendCredentialResponse.defaultExpiration(), params: ServerSecretParams) -> GroupSendCredentialResponse { - return failOnError { - issueCredential(groupMembers: groupMembers, requestingMember: requestingMember, expiration: expiration, params: params, randomness: try .generate()) - } - } - - /** - * Issues a new credential stating that `requestingMember` is a member of a group containing - * `groupMembers`, with an explictly-chosen source of randomness. - * - * Should only be used for testing purposes. - * - * - SeeAlso: ``issueCredential(groupMembers:requestingMember:expiration:params:)`` - */ - public static func issueCredential(groupMembers: [UuidCiphertext], requestingMember: UuidCiphertext, expiration: Date = GroupSendCredentialResponse.defaultExpiration(), params: ServerSecretParams, randomness: Randomness) -> GroupSendCredentialResponse { - let concatenated = groupMembers.flatMap { $0.serialize() } - - return failOnError { - return try concatenated.withUnsafeBorrowedBuffer { concatenated in - try requestingMember.withUnsafePointerToSerialized { requestingMember in - try params.withUnsafePointerToSerialized { params in - try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningVariableLengthSerialized { - signal_group_send_credential_response_issue_deterministic( - $0, - concatenated, - requestingMember, - UInt64(expiration.timeIntervalSince1970), - params, - randomness) - } + public static func defaultExpiration() -> Date { + let expiration = failOnError { + try invokeFnReturningInteger { + signal_group_send_credential_response_default_expiration_based_on_current_time($0) } - } } - } + return Date(timeIntervalSince1970: TimeInterval(expiration)) } - } - /** - * Receives, validates, and extracts the credential from a response. - * - * Note that the `receive` operation is provided for both ``ServiceId``s and ``UuidCiphertext``s. - * If you already have the ciphertexts for the group members available, - * ``receive(groupMembers:localUser:now:serverParams:groupParams:)-5ipwi`` will be *significantly* - * faster; if you don't, this method is faster than generating the ciphertexts and throwing them - * away afterwards. - * - * `localUser` should be included in `groupMembers`. - * - * - Throws: ``SignalError/verificationFailed(_:)`` if the credential is not valid for any reason - */ - public func receive(groupMembers: [ServiceId], localUser: Aci, now: Date = Date(), serverParams: ServerPublicParams, groupParams: GroupSecretParams) throws -> GroupSendCredential { - return try withUnsafeBorrowedBuffer { response in - try ServiceId.concatenatedFixedWidthBinary(groupMembers).withUnsafeBorrowedBuffer { groupMembers in - try localUser.withPointerToFixedWidthBinary { localUser in - try serverParams.withUnsafePointerToSerialized { serverParams in - try groupParams.withUnsafePointerToSerialized { groupParams in - try invokeFnReturningVariableLengthSerialized { - signal_group_send_credential_response_receive($0, response, groupMembers, localUser, UInt64(now.timeIntervalSince1970), serverParams, groupParams) - } - } - } + /** + * Issues a new credential stating that `requestingMember` is a member of a group containing + * `groupMembers`. + * + * `groupMembers` should include `requestingMember` as well. + */ + public static func issueCredential(groupMembers: [UuidCiphertext], requestingMember: UuidCiphertext, expiration: Date = GroupSendCredentialResponse.defaultExpiration(), params: ServerSecretParams) -> GroupSendCredentialResponse { + return failOnError { + self.issueCredential(groupMembers: groupMembers, requestingMember: requestingMember, expiration: expiration, params: params, randomness: try .generate()) } - } } - } - /** - * Receives, validates, and extracts the credential from a response. - * - * Note that the `receive` operation is provided for both ``ServiceId``s and ``UuidCiphertext``s. - * If you already have the ciphertexts for the group members available, this method will be - * *significantly* faster; if you don't, - * ``receive(groupMembers:localUser:now:serverParams:groupParams:)-4eco5`` is faster than - * generating the ciphertexts and - * throwing them away afterwards. - * - * `localUser` should be included in `groupMembers`. - * - * - Throws: ``SignalError/verificationFailed(_:)`` if the credential is not valid for any reason - */ - public func receive(groupMembers: [UuidCiphertext], localUser: UuidCiphertext, now: Date = Date(), serverParams: ServerPublicParams, groupParams: GroupSecretParams) throws -> GroupSendCredential { - return try withUnsafeBorrowedBuffer { response in - try groupMembers.flatMap { $0.serialize() }.withUnsafeBorrowedBuffer { groupMembers in - try localUser.withUnsafePointerToSerialized { localUser in - try serverParams.withUnsafePointerToSerialized { serverParams in - try groupParams.withUnsafePointerToSerialized { groupParams in - try invokeFnReturningVariableLengthSerialized { - signal_group_send_credential_response_receive_with_ciphertexts($0, response, groupMembers, localUser, UInt64(now.timeIntervalSince1970), serverParams, groupParams) - } + /** + * Issues a new credential stating that `requestingMember` is a member of a group containing + * `groupMembers`, with an explictly-chosen source of randomness. + * + * Should only be used for testing purposes. + * + * - SeeAlso: ``issueCredential(groupMembers:requestingMember:expiration:params:)`` + */ + public static func issueCredential(groupMembers: [UuidCiphertext], requestingMember: UuidCiphertext, expiration: Date = GroupSendCredentialResponse.defaultExpiration(), params: ServerSecretParams, randomness: Randomness) -> GroupSendCredentialResponse { + let concatenated = groupMembers.flatMap { $0.serialize() } + + return failOnError { + try concatenated.withUnsafeBorrowedBuffer { concatenated in + try requestingMember.withUnsafePointerToSerialized { requestingMember in + try params.withUnsafePointerToSerialized { params in + try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningVariableLengthSerialized { + signal_group_send_credential_response_issue_deterministic( + $0, + concatenated, + requestingMember, + UInt64(expiration.timeIntervalSince1970), + params, + randomness + ) + } + } + } + } + } + } + } + + /** + * Receives, validates, and extracts the credential from a response. + * + * Note that the `receive` operation is provided for both ``ServiceId``s and ``UuidCiphertext``s. + * If you already have the ciphertexts for the group members available, + * ``receive(groupMembers:localUser:now:serverParams:groupParams:)-5ipwi`` will be *significantly* + * faster; if you don't, this method is faster than generating the ciphertexts and throwing them + * away afterwards. + * + * `localUser` should be included in `groupMembers`. + * + * - Throws: ``SignalError/verificationFailed(_:)`` if the credential is not valid for any reason + */ + public func receive(groupMembers: [ServiceId], localUser: Aci, now: Date = Date(), serverParams: ServerPublicParams, groupParams: GroupSecretParams) throws -> GroupSendCredential { + return try withUnsafeBorrowedBuffer { response in + try ServiceId.concatenatedFixedWidthBinary(groupMembers).withUnsafeBorrowedBuffer { groupMembers in + try localUser.withPointerToFixedWidthBinary { localUser in + try serverParams.withUnsafePointerToSerialized { serverParams in + try groupParams.withUnsafePointerToSerialized { groupParams in + try invokeFnReturningVariableLengthSerialized { + signal_group_send_credential_response_receive($0, response, groupMembers, localUser, UInt64(now.timeIntervalSince1970), serverParams, groupParams) + } + } + } + } + } + } + } + + /** + * Receives, validates, and extracts the credential from a response. + * + * Note that the `receive` operation is provided for both ``ServiceId``s and ``UuidCiphertext``s. + * If you already have the ciphertexts for the group members available, this method will be + * *significantly* faster; if you don't, + * ``receive(groupMembers:localUser:now:serverParams:groupParams:)-4eco5`` is faster than + * generating the ciphertexts and + * throwing them away afterwards. + * + * `localUser` should be included in `groupMembers`. + * + * - Throws: ``SignalError/verificationFailed(_:)`` if the credential is not valid for any reason + */ + public func receive(groupMembers: [UuidCiphertext], localUser: UuidCiphertext, now: Date = Date(), serverParams: ServerPublicParams, groupParams: GroupSecretParams) throws -> GroupSendCredential { + return try withUnsafeBorrowedBuffer { response in + try groupMembers.flatMap { $0.serialize() }.withUnsafeBorrowedBuffer { groupMembers in + try localUser.withUnsafePointerToSerialized { localUser in + try serverParams.withUnsafePointerToSerialized { serverParams in + try groupParams.withUnsafePointerToSerialized { groupParams in + try invokeFnReturningVariableLengthSerialized { + signal_group_send_credential_response_receive_with_ciphertexts($0, response, groupMembers, localUser, UInt64(now.timeIntervalSince1970), serverParams, groupParams) + } + } + } + } } - } } - } } - } } diff --git a/swift/Sources/LibSignalClient/zkgroup/NotarySignature.swift b/swift/Sources/LibSignalClient/zkgroup/NotarySignature.swift index dc5cfc9d..ca1ce1a8 100644 --- a/swift/Sources/LibSignalClient/zkgroup/NotarySignature.swift +++ b/swift/Sources/LibSignalClient/zkgroup/NotarySignature.swift @@ -4,11 +4,9 @@ // public class NotarySignature: ByteArray { + public static let SIZE: Int = 64 - public static let SIZE: Int = 64 - - public required init(contents: [UInt8]) throws { - try super.init(newContents: contents, expectedLength: NotarySignature.SIZE) - } - + public required init(contents: [UInt8]) throws { + try super.init(newContents: contents, expectedLength: NotarySignature.SIZE) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ProfileKey.swift b/swift/Sources/LibSignalClient/zkgroup/ProfileKey.swift index 8bc92d1a..26822e57 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ProfileKey.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ProfileKey.swift @@ -7,41 +7,39 @@ import Foundation import SignalFfi public class ProfileKey: ByteArray { + public static let SIZE: Int = 32 - public static let SIZE: Int = 32 - - public required init(contents: [UInt8]) throws { - try super.init(newContents: contents, expectedLength: ProfileKey.SIZE) - } - - public func getCommitment(userId: Aci) throws -> ProfileKeyCommitment { - return try withUnsafePointerToSerialized { contents in - try userId.withPointerToFixedWidthBinary { userId in - try invokeFnReturningSerialized { - signal_profile_key_get_commitment($0, contents, userId) - } - } + public required init(contents: [UInt8]) throws { + try super.init(newContents: contents, expectedLength: ProfileKey.SIZE) } - } - public func getProfileKeyVersion(userId: Aci) throws -> ProfileKeyVersion { - return try withUnsafePointerToSerialized { contents in - try userId.withPointerToFixedWidthBinary { userId in - try invokeFnReturningSerialized { - signal_profile_key_get_profile_key_version($0, contents, userId) + public func getCommitment(userId: Aci) throws -> ProfileKeyCommitment { + return try withUnsafePointerToSerialized { contents in + try userId.withPointerToFixedWidthBinary { userId in + try invokeFnReturningSerialized { + signal_profile_key_get_commitment($0, contents, userId) + } + } } - } } - } - public func deriveAccessKey() -> [UInt8] { - return failOnError { - try withUnsafePointerToSerialized { contents in - try invokeFnReturningFixedLengthArray { - signal_profile_key_derive_access_key($0, contents) + public func getProfileKeyVersion(userId: Aci) throws -> ProfileKeyVersion { + return try withUnsafePointerToSerialized { contents in + try userId.withPointerToFixedWidthBinary { userId in + try invokeFnReturningSerialized { + signal_profile_key_get_profile_key_version($0, contents, userId) + } + } } - } } - } + public func deriveAccessKey() -> [UInt8] { + return failOnError { + try withUnsafePointerToSerialized { contents in + try invokeFnReturningFixedLengthArray { + signal_profile_key_derive_access_key($0, contents) + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCiphertext.swift b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCiphertext.swift index c1cfc1ef..3064de5d 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCiphertext.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCiphertext.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class ProfileKeyCiphertext: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_profile_key_ciphertext_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_profile_key_ciphertext_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCommitment.swift b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCommitment.swift index 27da1994..c8f6be70 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCommitment.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCommitment.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class ProfileKeyCommitment: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_profile_key_commitment_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_profile_key_commitment_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialPresentation.swift b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialPresentation.swift index 9bbc697a..a8359783 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialPresentation.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialPresentation.swift @@ -7,25 +7,23 @@ import Foundation import SignalFfi public class ProfileKeyCredentialPresentation: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_profile_key_credential_presentation_check_valid_contents) - } - - public func getUuidCiphertext() throws -> UuidCiphertext { - return try withUnsafeBorrowedBuffer { buffer in - try invokeFnReturningSerialized { - signal_profile_key_credential_presentation_get_uuid_ciphertext($0, buffer) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_profile_key_credential_presentation_check_valid_contents) } - } - public func getProfileKeyCiphertext() throws -> ProfileKeyCiphertext { - return try withUnsafeBorrowedBuffer { buffer in - try invokeFnReturningSerialized { - signal_profile_key_credential_presentation_get_profile_key_ciphertext($0, buffer) - } + public func getUuidCiphertext() throws -> UuidCiphertext { + return try withUnsafeBorrowedBuffer { buffer in + try invokeFnReturningSerialized { + signal_profile_key_credential_presentation_get_uuid_ciphertext($0, buffer) + } + } } - } + public func getProfileKeyCiphertext() throws -> ProfileKeyCiphertext { + return try withUnsafeBorrowedBuffer { buffer in + try invokeFnReturningSerialized { + signal_profile_key_credential_presentation_get_profile_key_ciphertext($0, buffer) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequest.swift b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequest.swift index 9013c02c..27516b86 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequest.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequest.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class ProfileKeyCredentialRequest: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_profile_key_credential_request_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_profile_key_credential_request_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequestContext.swift b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequestContext.swift index 832a0d9e..c6677ca1 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequestContext.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyCredentialRequestContext.swift @@ -7,17 +7,15 @@ import Foundation import SignalFfi public class ProfileKeyCredentialRequestContext: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_profile_key_credential_request_context_check_valid_contents) - } - - public func getRequest() throws -> ProfileKeyCredentialRequest { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningSerialized { - signal_profile_key_credential_request_context_get_request($0, contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_profile_key_credential_request_context_check_valid_contents) } - } + public func getRequest() throws -> ProfileKeyCredentialRequest { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningSerialized { + signal_profile_key_credential_request_context_get_request($0, contents) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyVersion.swift b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyVersion.swift index baf8062f..595398cc 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ProfileKeyVersion.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ProfileKeyVersion.swift @@ -4,11 +4,9 @@ // public class ProfileKeyVersion: ByteArray { + public static let SIZE: Int = 64 - public static let SIZE: Int = 64 - - public required init(contents: [UInt8]) throws { - try super.init(newContents: contents, expectedLength: ProfileKeyVersion.SIZE) - } - + public required init(contents: [UInt8]) throws { + try super.init(newContents: contents, expectedLength: ProfileKeyVersion.SIZE) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredential.swift b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredential.swift index 26d79508..a10439d6 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredential.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredential.swift @@ -7,25 +7,23 @@ import Foundation import SignalFfi public class ReceiptCredential: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_receipt_credential_check_valid_contents) - } - - public func getReceiptExpirationTime() throws -> UInt64 { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningInteger { - signal_receipt_credential_get_receipt_expiration_time($0, contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_receipt_credential_check_valid_contents) } - } - public func getReceiptLevel() throws -> UInt64 { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningInteger { - signal_receipt_credential_get_receipt_level($0, contents) - } + public func getReceiptExpirationTime() throws -> UInt64 { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningInteger { + signal_receipt_credential_get_receipt_expiration_time($0, contents) + } + } } - } + public func getReceiptLevel() throws -> UInt64 { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningInteger { + signal_receipt_credential_get_receipt_level($0, contents) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialPresentation.swift b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialPresentation.swift index df8a60f9..4b0353d1 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialPresentation.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialPresentation.swift @@ -7,33 +7,31 @@ import Foundation import SignalFfi public class ReceiptCredentialPresentation: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_receipt_credential_presentation_check_valid_contents) - } - - public func getReceiptExpirationTime() throws -> UInt64 { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningInteger { - signal_receipt_credential_presentation_get_receipt_expiration_time($0, contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_receipt_credential_presentation_check_valid_contents) } - } - public func getReceiptLevel() throws -> UInt64 { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningInteger { - signal_receipt_credential_presentation_get_receipt_level($0, contents) - } + public func getReceiptExpirationTime() throws -> UInt64 { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningInteger { + signal_receipt_credential_presentation_get_receipt_expiration_time($0, contents) + } + } } - } - public func getReceiptSerial() throws -> ReceiptSerial { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningSerialized { - signal_receipt_credential_presentation_get_receipt_serial($0, contents) - } + public func getReceiptLevel() throws -> UInt64 { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningInteger { + signal_receipt_credential_presentation_get_receipt_level($0, contents) + } + } } - } + public func getReceiptSerial() throws -> ReceiptSerial { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningSerialized { + signal_receipt_credential_presentation_get_receipt_serial($0, contents) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequest.swift b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequest.swift index a23c5c39..4ad12a0e 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequest.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequest.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class ReceiptCredentialRequest: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_receipt_credential_request_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_receipt_credential_request_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequestContext.swift b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequestContext.swift index b4766ec1..0d185b8e 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequestContext.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialRequestContext.swift @@ -7,17 +7,15 @@ import Foundation import SignalFfi public class ReceiptCredentialRequestContext: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_receipt_credential_request_context_check_valid_contents) - } - - public func getRequest() throws -> ReceiptCredentialRequest { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningSerialized { - signal_receipt_credential_request_context_get_request($0, contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_receipt_credential_request_context_check_valid_contents) } - } + public func getRequest() throws -> ReceiptCredentialRequest { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningSerialized { + signal_receipt_credential_request_context_get_request($0, contents) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialResponse.swift b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialResponse.swift index 31f087ed..d2eb64f9 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialResponse.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ReceiptCredentialResponse.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class ReceiptCredentialResponse: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_receipt_credential_response_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_receipt_credential_response_check_valid_contents) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ReceiptSerial.swift b/swift/Sources/LibSignalClient/zkgroup/ReceiptSerial.swift index 0e7a2f0c..bced03a1 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ReceiptSerial.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ReceiptSerial.swift @@ -4,11 +4,9 @@ // public class ReceiptSerial: ByteArray { + public static let SIZE: Int = 16 - public static let SIZE: Int = 16 - - public required init(contents: [UInt8]) throws { - try super.init(newContents: contents, expectedLength: ReceiptSerial.SIZE) - } - + public required init(contents: [UInt8]) throws { + try super.init(newContents: contents, expectedLength: ReceiptSerial.SIZE) + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ServerPublicParams.swift b/swift/Sources/LibSignalClient/zkgroup/ServerPublicParams.swift index 86fccb87..d9357d3d 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ServerPublicParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ServerPublicParams.swift @@ -7,19 +7,17 @@ import Foundation import SignalFfi public class ServerPublicParams: ByteArray { - - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_server_public_params_check_valid_contents) - } - - public func verifySignature(message: [UInt8], notarySignature: NotarySignature) throws { - try withUnsafePointerToSerialized { contents in - try message.withUnsafeBorrowedBuffer { message in - try notarySignature.withUnsafePointerToSerialized { notarySignature in - try checkError(signal_server_public_params_verify_signature(contents, message, notarySignature)) - } - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_server_public_params_check_valid_contents) } - } + public func verifySignature(message: [UInt8], notarySignature: NotarySignature) throws { + try withUnsafePointerToSerialized { contents in + try message.withUnsafeBorrowedBuffer { message in + try notarySignature.withUnsafePointerToSerialized { notarySignature in + try checkError(signal_server_public_params_verify_signature(contents, message, notarySignature)) + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ServerSecretParams.swift b/swift/Sources/LibSignalClient/zkgroup/ServerSecretParams.swift index 5847ae2c..2f71c940 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ServerSecretParams.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ServerSecretParams.swift @@ -7,45 +7,43 @@ import Foundation import SignalFfi public class ServerSecretParams: ByteArray { - - public static func generate() throws -> ServerSecretParams { - return try generate(randomness: Randomness.generate()) - } - - public static func generate(randomness: Randomness) throws -> ServerSecretParams { - return try randomness.withUnsafePointerToBytes { randomness in - try invokeFnReturningSerialized { - signal_server_secret_params_generate_deterministic($0, randomness) - } + public static func generate() throws -> ServerSecretParams { + return try self.generate(randomness: Randomness.generate()) } - } - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_server_secret_params_check_valid_contents) - } - - public func getPublicParams() throws -> ServerPublicParams { - return try withUnsafePointerToSerialized { contents in - try invokeFnReturningSerialized { - signal_server_secret_params_get_public_params($0, contents) - } - } - } - - public func sign(message: [UInt8]) throws -> NotarySignature { - return try sign(randomness: Randomness.generate(), message: message) - } - - public func sign(randomness: Randomness, message: [UInt8]) throws -> NotarySignature { - return try withUnsafePointerToSerialized { contents in - try randomness.withUnsafePointerToBytes { randomness in - try message.withUnsafeBorrowedBuffer { message in - try invokeFnReturningSerialized { - signal_server_secret_params_sign_deterministic($0, contents, randomness, message) - } + public static func generate(randomness: Randomness) throws -> ServerSecretParams { + return try randomness.withUnsafePointerToBytes { randomness in + try invokeFnReturningSerialized { + signal_server_secret_params_generate_deterministic($0, randomness) + } } - } } - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_server_secret_params_check_valid_contents) + } + + public func getPublicParams() throws -> ServerPublicParams { + return try withUnsafePointerToSerialized { contents in + try invokeFnReturningSerialized { + signal_server_secret_params_get_public_params($0, contents) + } + } + } + + public func sign(message: [UInt8]) throws -> NotarySignature { + return try self.sign(randomness: Randomness.generate(), message: message) + } + + public func sign(randomness: Randomness, message: [UInt8]) throws -> NotarySignature { + return try withUnsafePointerToSerialized { contents in + try randomness.withUnsafePointerToBytes { randomness in + try message.withUnsafeBorrowedBuffer { message in + try invokeFnReturningSerialized { + signal_server_secret_params_sign_deterministic($0, contents, randomness, message) + } + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ServerZkAuthOperations.swift b/swift/Sources/LibSignalClient/zkgroup/ServerZkAuthOperations.swift index 0c1191ea..9685b4f4 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ServerZkAuthOperations.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ServerZkAuthOperations.swift @@ -7,73 +7,71 @@ import Foundation import SignalFfi public class ServerZkAuthOperations { + let serverSecretParams: ServerSecretParams - let serverSecretParams: ServerSecretParams - - public init(serverSecretParams: ServerSecretParams) { - self.serverSecretParams = serverSecretParams - } - - public func issueAuthCredential(aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse { - return try issueAuthCredential(randomness: Randomness.generate(), aci: aci, redemptionTime: redemptionTime) - } - - public func issueAuthCredential(randomness: Randomness, aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse { - return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try randomness.withUnsafePointerToBytes { randomness in - try aci.withPointerToFixedWidthBinary { aci in - try invokeFnReturningSerialized { - signal_server_secret_params_issue_auth_credential_deterministic($0, serverSecretParams, randomness, aci, redemptionTime) - } - } - } + public init(serverSecretParams: ServerSecretParams) { + self.serverSecretParams = serverSecretParams } - } - public func issueAuthCredentialWithPniAsServiceId(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { - return try issueAuthCredentialWithPniAsServiceId(randomness: Randomness.generate(), aci: aci, pni: pni, redemptionTime: redemptionTime) - } + public func issueAuthCredential(aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse { + return try self.issueAuthCredential(randomness: Randomness.generate(), aci: aci, redemptionTime: redemptionTime) + } - public func issueAuthCredentialWithPniAsServiceId(randomness: Randomness, aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { - return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try randomness.withUnsafePointerToBytes { randomness in - try aci.withPointerToFixedWidthBinary { aci in - try pni.withPointerToFixedWidthBinary { pni in - try invokeFnReturningSerialized { - signal_server_secret_params_issue_auth_credential_with_pni_as_service_id_deterministic($0, serverSecretParams, randomness, aci, pni, redemptionTime) + public func issueAuthCredential(randomness: Randomness, aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse { + return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try randomness.withUnsafePointerToBytes { randomness in + try aci.withPointerToFixedWidthBinary { aci in + try invokeFnReturningSerialized { + signal_server_secret_params_issue_auth_credential_deterministic($0, serverSecretParams, randomness, aci, redemptionTime) + } + } } - } } - } } - } - public func issueAuthCredentialWithPniAsAci(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { - return try issueAuthCredentialWithPniAsAci(randomness: Randomness.generate(), aci: aci, pni: pni, redemptionTime: redemptionTime) - } + public func issueAuthCredentialWithPniAsServiceId(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { + return try self.issueAuthCredentialWithPniAsServiceId(randomness: Randomness.generate(), aci: aci, pni: pni, redemptionTime: redemptionTime) + } - public func issueAuthCredentialWithPniAsAci(randomness: Randomness, aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { - return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try randomness.withUnsafePointerToBytes { randomness in - try aci.withPointerToFixedWidthBinary { aci in - try pni.withPointerToFixedWidthBinary { pni in - try invokeFnReturningSerialized { - signal_server_secret_params_issue_auth_credential_with_pni_as_aci_deterministic($0, serverSecretParams, randomness, aci, pni, redemptionTime) + public func issueAuthCredentialWithPniAsServiceId(randomness: Randomness, aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { + return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try randomness.withUnsafePointerToBytes { randomness in + try aci.withPointerToFixedWidthBinary { aci in + try pni.withPointerToFixedWidthBinary { pni in + try invokeFnReturningSerialized { + signal_server_secret_params_issue_auth_credential_with_pni_as_service_id_deterministic($0, serverSecretParams, randomness, aci, pni, redemptionTime) + } + } + } } - } } - } } - } - public func verifyAuthCredentialPresentation(groupPublicParams: GroupPublicParams, authCredentialPresentation: AuthCredentialPresentation, now: Date = Date()) throws { - try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in - try authCredentialPresentation.withUnsafeBorrowedBuffer { authCredentialPresentation in - try checkError(signal_server_secret_params_verify_auth_credential_presentation(serverSecretParams, groupPublicParams, authCredentialPresentation, UInt64(now.timeIntervalSince1970))) + public func issueAuthCredentialWithPniAsAci(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { + return try self.issueAuthCredentialWithPniAsAci(randomness: Randomness.generate(), aci: aci, pni: pni, redemptionTime: redemptionTime) + } + + public func issueAuthCredentialWithPniAsAci(randomness: Randomness, aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { + return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try randomness.withUnsafePointerToBytes { randomness in + try aci.withPointerToFixedWidthBinary { aci in + try pni.withPointerToFixedWidthBinary { pni in + try invokeFnReturningSerialized { + signal_server_secret_params_issue_auth_credential_with_pni_as_aci_deterministic($0, serverSecretParams, randomness, aci, pni, redemptionTime) + } + } + } + } } - } } - } + public func verifyAuthCredentialPresentation(groupPublicParams: GroupPublicParams, authCredentialPresentation: AuthCredentialPresentation, now: Date = Date()) throws { + try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in + try authCredentialPresentation.withUnsafeBorrowedBuffer { authCredentialPresentation in + try checkError(signal_server_secret_params_verify_auth_credential_presentation(serverSecretParams, groupPublicParams, authCredentialPresentation, UInt64(now.timeIntervalSince1970))) + } + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/ServerZkProfileOperations.swift b/swift/Sources/LibSignalClient/zkgroup/ServerZkProfileOperations.swift index 1a8ebd0c..41a114b7 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ServerZkProfileOperations.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ServerZkProfileOperations.swift @@ -7,45 +7,43 @@ import Foundation import SignalFfi public class ServerZkProfileOperations { + let serverSecretParams: ServerSecretParams - let serverSecretParams: ServerSecretParams + public init(serverSecretParams: ServerSecretParams) { + self.serverSecretParams = serverSecretParams + } - public init(serverSecretParams: ServerSecretParams) { - self.serverSecretParams = serverSecretParams - } + public func issueExpiringProfileKeyCredential(profileKeyCredentialRequest: ProfileKeyCredentialRequest, userId: Aci, profileKeyCommitment: ProfileKeyCommitment, expiration: UInt64) throws -> ExpiringProfileKeyCredentialResponse { + return try self.issueExpiringProfileKeyCredential(randomness: Randomness.generate(), profileKeyCredentialRequest: profileKeyCredentialRequest, userId: userId, profileKeyCommitment: profileKeyCommitment, expiration: expiration) + } - public func issueExpiringProfileKeyCredential(profileKeyCredentialRequest: ProfileKeyCredentialRequest, userId: Aci, profileKeyCommitment: ProfileKeyCommitment, expiration: UInt64) throws -> ExpiringProfileKeyCredentialResponse { - return try issueExpiringProfileKeyCredential(randomness: Randomness.generate(), profileKeyCredentialRequest: profileKeyCredentialRequest, userId: userId, profileKeyCommitment: profileKeyCommitment, expiration: expiration) - } - - public func issueExpiringProfileKeyCredential(randomness: Randomness, profileKeyCredentialRequest: ProfileKeyCredentialRequest, userId: Aci, profileKeyCommitment: ProfileKeyCommitment, expiration: UInt64) throws -> ExpiringProfileKeyCredentialResponse { - return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try randomness.withUnsafePointerToBytes { randomness in - try profileKeyCredentialRequest.withUnsafePointerToSerialized { request in - try userId.withPointerToFixedWidthBinary { userId in - try profileKeyCommitment.withUnsafePointerToSerialized { commitment in - try invokeFnReturningSerialized { - signal_server_secret_params_issue_expiring_profile_key_credential_deterministic($0, serverSecretParams, randomness, request, userId, commitment, expiration) - } + public func issueExpiringProfileKeyCredential(randomness: Randomness, profileKeyCredentialRequest: ProfileKeyCredentialRequest, userId: Aci, profileKeyCommitment: ProfileKeyCommitment, expiration: UInt64) throws -> ExpiringProfileKeyCredentialResponse { + return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try randomness.withUnsafePointerToBytes { randomness in + try profileKeyCredentialRequest.withUnsafePointerToSerialized { request in + try userId.withPointerToFixedWidthBinary { userId in + try profileKeyCommitment.withUnsafePointerToSerialized { commitment in + try invokeFnReturningSerialized { + signal_server_secret_params_issue_expiring_profile_key_credential_deterministic($0, serverSecretParams, randomness, request, userId, commitment, expiration) + } + } + } + } } - } } - } } - } - public func verifyProfileKeyCredentialPresentation( - groupPublicParams: GroupPublicParams, - profileKeyCredentialPresentation: ProfileKeyCredentialPresentation, - now: Date = Date() - ) throws { - try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in - try profileKeyCredentialPresentation.withUnsafeBorrowedBuffer { presentation in - try checkError(signal_server_secret_params_verify_profile_key_credential_presentation(serverSecretParams, groupPublicParams, presentation, UInt64(now.timeIntervalSince1970))) + public func verifyProfileKeyCredentialPresentation( + groupPublicParams: GroupPublicParams, + profileKeyCredentialPresentation: ProfileKeyCredentialPresentation, + now: Date = Date() + ) throws { + try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in + try profileKeyCredentialPresentation.withUnsafeBorrowedBuffer { presentation in + try checkError(signal_server_secret_params_verify_profile_key_credential_presentation(serverSecretParams, groupPublicParams, presentation, UInt64(now.timeIntervalSince1970))) + } + } } - } } - } - } diff --git a/swift/Sources/LibSignalClient/zkgroup/ServerZkReceiptOperations.swift b/swift/Sources/LibSignalClient/zkgroup/ServerZkReceiptOperations.swift index 16a8c904..51bbaae8 100644 --- a/swift/Sources/LibSignalClient/zkgroup/ServerZkReceiptOperations.swift +++ b/swift/Sources/LibSignalClient/zkgroup/ServerZkReceiptOperations.swift @@ -7,35 +7,33 @@ import Foundation import SignalFfi public class ServerZkReceiptOperations { + let serverSecretParams: ServerSecretParams - let serverSecretParams: ServerSecretParams - - public init(serverSecretParams: ServerSecretParams) { - self.serverSecretParams = serverSecretParams - } - - public func issueReceiptCredential(receiptCredentialRequest: ReceiptCredentialRequest, receiptExpirationTime: UInt64, receiptLevel: UInt64) throws -> ReceiptCredentialResponse { - return try issueReceiptCredential(randomness: Randomness.generate(), receiptCredentialRequest: receiptCredentialRequest, receiptExpirationTime: receiptExpirationTime, receiptLevel: receiptLevel) - } - - public func issueReceiptCredential(randomness: Randomness, receiptCredentialRequest: ReceiptCredentialRequest, receiptExpirationTime: UInt64, receiptLevel: UInt64) throws -> ReceiptCredentialResponse { - return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try randomness.withUnsafePointerToBytes { randomness in - try receiptCredentialRequest.withUnsafePointerToSerialized { receiptCredentialRequest in - try invokeFnReturningSerialized { - signal_server_secret_params_issue_receipt_credential_deterministic($0, serverSecretParams, randomness, receiptCredentialRequest, receiptExpirationTime, receiptLevel) - } - } - } + public init(serverSecretParams: ServerSecretParams) { + self.serverSecretParams = serverSecretParams } - } - public func verifyReceiptCredentialPresentation(receiptCredentialPresentation: ReceiptCredentialPresentation) throws { - try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in - try receiptCredentialPresentation.withUnsafePointerToSerialized { receiptCredentialPresentation in - try checkError(signal_server_secret_params_verify_receipt_credential_presentation(serverSecretParams, receiptCredentialPresentation)) + public func issueReceiptCredential(receiptCredentialRequest: ReceiptCredentialRequest, receiptExpirationTime: UInt64, receiptLevel: UInt64) throws -> ReceiptCredentialResponse { + return try self.issueReceiptCredential(randomness: Randomness.generate(), receiptCredentialRequest: receiptCredentialRequest, receiptExpirationTime: receiptExpirationTime, receiptLevel: receiptLevel) + } + + public func issueReceiptCredential(randomness: Randomness, receiptCredentialRequest: ReceiptCredentialRequest, receiptExpirationTime: UInt64, receiptLevel: UInt64) throws -> ReceiptCredentialResponse { + return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try randomness.withUnsafePointerToBytes { randomness in + try receiptCredentialRequest.withUnsafePointerToSerialized { receiptCredentialRequest in + try invokeFnReturningSerialized { + signal_server_secret_params_issue_receipt_credential_deterministic($0, serverSecretParams, randomness, receiptCredentialRequest, receiptExpirationTime, receiptLevel) + } + } + } } } - } + public func verifyReceiptCredentialPresentation(receiptCredentialPresentation: ReceiptCredentialPresentation) throws { + try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in + try receiptCredentialPresentation.withUnsafePointerToSerialized { receiptCredentialPresentation in + try checkError(signal_server_secret_params_verify_receipt_credential_presentation(serverSecretParams, receiptCredentialPresentation)) + } + } + } } diff --git a/swift/Sources/LibSignalClient/zkgroup/UuidCiphertext.swift b/swift/Sources/LibSignalClient/zkgroup/UuidCiphertext.swift index 30348c62..5862f87c 100644 --- a/swift/Sources/LibSignalClient/zkgroup/UuidCiphertext.swift +++ b/swift/Sources/LibSignalClient/zkgroup/UuidCiphertext.swift @@ -7,7 +7,7 @@ import Foundation import SignalFfi public class UuidCiphertext: ByteArray { - public required init(contents: [UInt8]) throws { - try super.init(contents, checkValid: signal_uuid_ciphertext_check_valid_contents) - } + public required init(contents: [UInt8]) throws { + try super.init(contents, checkValid: signal_uuid_ciphertext_check_valid_contents) + } } diff --git a/swift/Tests/LibSignalClientTests/AsyncTests.swift b/swift/Tests/LibSignalClientTests/AsyncTests.swift index 3f99ea87..37a61435 100644 --- a/swift/Tests/LibSignalClientTests/AsyncTests.swift +++ b/swift/Tests/LibSignalClientTests/AsyncTests.swift @@ -6,9 +6,9 @@ // These testing endpoints aren't generated in device builds, to save on code size. #if !os(iOS) || targetEnvironment(simulator) -import XCTest @testable import LibSignalClient import SignalFfi +import XCTest final class AsyncTests: XCTestCase { func testSuccess() async throws { @@ -39,7 +39,8 @@ final class AsyncTests: XCTestCase { XCTAssertEqual( try invokeFnReturningInteger { result in signal_testing_testing_handle_type_get_value(result, handle) - }, value) + }, value + ) } do { @@ -52,7 +53,8 @@ final class AsyncTests: XCTestCase { XCTAssertEqual( try invokeFnReturningString { result in signal_testing_other_testing_handle_type_get_value(result, otherHandle) - }, value) + }, value + ) } } } diff --git a/swift/Tests/LibSignalClientTests/BridgingTests.swift b/swift/Tests/LibSignalClientTests/BridgingTests.swift index 7c0bdddc..8cb986af 100644 --- a/swift/Tests/LibSignalClientTests/BridgingTests.swift +++ b/swift/Tests/LibSignalClientTests/BridgingTests.swift @@ -6,9 +6,9 @@ // These testing endpoints aren't generated in device builds, to save on code size. #if !os(iOS) || targetEnvironment(simulator) -import XCTest @testable import LibSignalClient import SignalFfi +import XCTest private func fakeAsyncRuntime() -> OpaquePointer! { OpaquePointer(bitPattern: -1) diff --git a/swift/Tests/LibSignalClientTests/ClonableHandleOwnerTests.swift b/swift/Tests/LibSignalClientTests/ClonableHandleOwnerTests.swift index 47dd971c..5591b893 100644 --- a/swift/Tests/LibSignalClientTests/ClonableHandleOwnerTests.swift +++ b/swift/Tests/LibSignalClientTests/ClonableHandleOwnerTests.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest @testable import LibSignalClient +import XCTest private struct FakeHandle { // We're using the tuple to guarantee in-memory layout for this test. diff --git a/swift/Tests/LibSignalClientTests/CryptoTests.swift b/swift/Tests/LibSignalClientTests/CryptoTests.swift index 238e8aa9..2f42d529 100644 --- a/swift/Tests/LibSignalClientTests/CryptoTests.swift +++ b/swift/Tests/LibSignalClientTests/CryptoTests.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest @testable import LibSignalClient +import XCTest class CryptoTests: TestCaseBase { func generateAesKey() -> [UInt8] { @@ -17,10 +17,42 @@ class CryptoTests: TestCaseBase { func testAesGcmSiv() { let ptext: [UInt8] = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - let expected_ctext: [UInt8] = [0x1d, 0xe2, 0x29, 0x67, 0x23, 0x7a, 0x81, 0x32, 0x91, 0x21, 0x3f, 0x26, 0x7e, 0x3b, 0x45, 0x2f, 0x02, 0xd0, 0x1a, 0xe3, 0x3e, 0x4e, 0xc8, 0x54] + let expected_ctext: [UInt8] = [0x1D, 0xE2, 0x29, 0x67, 0x23, 0x7A, 0x81, 0x32, 0x91, 0x21, 0x3F, 0x26, 0x7E, 0x3B, 0x45, 0x2F, 0x02, 0xD0, 0x1A, 0xE3, 0x3E, 0x4E, 0xC8, 0x54] let ad: [UInt8] = [0x01] - let key: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + let key: [UInt8] = [ + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ] let nonce: [UInt8] = [0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] let gcm_siv = try! Aes256GcmSiv(key: key) @@ -39,7 +71,7 @@ class CryptoTests: TestCaseBase { let plainTextData = Data("Super🔥secret🔥test🔥data🏁🏁".utf8) XCTAssertEqual(39, plainTextData.count) - let key = generateAesKey() + let key = self.generateAesKey() let encryptedParts = try! Aes256GcmEncryptedData.encrypt(plainTextData, key: key) let encryptedData = encryptedParts.concatenate() XCTAssertEqual(Aes256GcmEncryptedData.nonceLength + plainTextData.count + Aes256GcmEncryptedData.authenticationTagLength, encryptedData.count) @@ -54,7 +86,7 @@ class CryptoTests: TestCaseBase { XCTAssertEqual(plainTextData, decryptedData) var encryptedWithBadTag = encryptedData - encryptedWithBadTag[encryptedWithBadTag.count - 1] ^= 0xff + encryptedWithBadTag[encryptedWithBadTag.count - 1] ^= 0xFF XCTAssertThrowsError(try Aes256GcmEncryptedData(concatenated: encryptedWithBadTag).decrypt(key: key)) { guard case SignalError.invalidMessage(_) = $0 else { XCTFail("wrong error: \($0)") @@ -64,12 +96,12 @@ class CryptoTests: TestCaseBase { } func testAesGcmKat() { - let key: [UInt8] = [0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08] - let plaintext = Data([0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39]) - let expectedCiphertext = Data([0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62]) - let expectedTag = Data([0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68, 0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b]) - let nonce: [UInt8] = [0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88] - let ad: [UInt8] = [0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2] + let key: [UInt8] = [0xFE, 0xFF, 0xE9, 0x92, 0x86, 0x65, 0x73, 0x1C, 0x6D, 0x6A, 0x8F, 0x94, 0x67, 0x30, 0x83, 0x08, 0xFE, 0xFF, 0xE9, 0x92, 0x86, 0x65, 0x73, 0x1C, 0x6D, 0x6A, 0x8F, 0x94, 0x67, 0x30, 0x83, 0x08] + let plaintext = Data([0xD9, 0x31, 0x32, 0x25, 0xF8, 0x84, 0x06, 0xE5, 0xA5, 0x59, 0x09, 0xC5, 0xAF, 0xF5, 0x26, 0x9A, 0x86, 0xA7, 0xA9, 0x53, 0x15, 0x34, 0xF7, 0xDA, 0x2E, 0x4C, 0x30, 0x3D, 0x8A, 0x31, 0x8A, 0x72, 0x1C, 0x3C, 0x0C, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2F, 0xCF, 0x0E, 0x24, 0x49, 0xA6, 0xB5, 0x25, 0xB1, 0x6A, 0xED, 0xF5, 0xAA, 0x0D, 0xE6, 0x57, 0xBA, 0x63, 0x7B, 0x39]) + let expectedCiphertext = Data([0x52, 0x2D, 0xC1, 0xF0, 0x99, 0x56, 0x7D, 0x07, 0xF4, 0x7F, 0x37, 0xA3, 0x2A, 0x84, 0x42, 0x7D, 0x64, 0x3A, 0x8C, 0xDC, 0xBF, 0xE5, 0xC0, 0xC9, 0x75, 0x98, 0xA2, 0xBD, 0x25, 0x55, 0xD1, 0xAA, 0x8C, 0xB0, 0x8E, 0x48, 0x59, 0x0D, 0xBB, 0x3D, 0xA7, 0xB0, 0x8B, 0x10, 0x56, 0x82, 0x88, 0x38, 0xC5, 0xF6, 0x1E, 0x63, 0x93, 0xBA, 0x7A, 0x0A, 0xBC, 0xC9, 0xF6, 0x62]) + let expectedTag = Data([0x76, 0xFC, 0x6E, 0xCE, 0x0F, 0x4E, 0x17, 0x68, 0xCD, 0xDF, 0x88, 0x53, 0xBB, 0x2D, 0x55, 0x1B]) + let nonce: [UInt8] = [0xCA, 0xFE, 0xBA, 0xBE, 0xFA, 0xCE, 0xDB, 0xAD, 0xDE, 0xCA, 0xF8, 0x88] + let ad: [UInt8] = [0xFE, 0xED, 0xFA, 0xCE, 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED, 0xFA, 0xCE, 0xDE, 0xAD, 0xBE, 0xEF, 0xAB, 0xAD, 0xDA, 0xD2] let gcmEnc = try! Aes256GcmEncryption(key: key, nonce: nonce, associatedData: ad) var ciphertext = plaintext @@ -102,7 +134,7 @@ class CryptoTests: TestCaseBase { func testAesCtr() { let plainTextData = Data("Super🔥secret🔥test🔥data🏁🏁".utf8) - let key = generateAesKey() + let key = self.generateAesKey() var nonce = Array(repeating: UInt8(0), count: Aes256Ctr32.nonceLength) nonce.withUnsafeMutableBytes { try! fillRandom($0) @@ -116,10 +148,10 @@ class CryptoTests: TestCaseBase { } func testAesCtrKat() { - let key: [UInt8] = [0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4] - let plaintext = Data([0xfd, 0x4c, 0x14, 0x72, 0x9f, 0x50, 0x04, 0xba, 0x49, 0xd8, 0x32, 0xad, 0x7b, 0xe8, 0x7c, 0x18, 0xf4, 0xfa, 0xfb, 0x58, 0x96, 0x2b, 0x9a, 0x43, 0xc3, 0xbe, 0x41, 0x71, 0x3d, 0xed, 0x93, 0xdb, 0xf8, 0x54, 0xac, 0x4c, 0xa2, 0x62, 0x85, 0xb7, 0xf7, 0x6e, 0x04, 0xb8, 0xf8, 0xd4, 0xe7, 0xd9, 0xf7, 0x54, 0x8f, 0x9b, 0x46, 0x5c, 0x8f, 0x71, 0x3c, 0x10, 0x6e, 0x9f, 0x63, 0xf5, 0x43, 0x05, 0x33, 0x1a, 0x49, 0x83, 0xa2, 0xf4, 0xb7, 0x18, 0xde, 0x29, 0xfa, 0x79, 0x4d, 0xa1, 0x2e, 0xee, 0x80, 0x86, 0x42, 0xfa, 0xef, 0xf8, 0x27, 0x1a, 0x0e, 0xa2, 0x8e, 0x3c, 0xc8, 0x0e, 0xeb, 0x65, 0xa8, 0xeb, 0x61, 0xf6, 0x9d, 0x8b, 0xa9, 0x7f, 0x6b, 0xf9, 0x05, 0x44, 0x53, 0xf5, 0x5e, 0xfb, 0x8f, 0x94, 0x22, 0x08, 0x1f, 0x16, 0x20, 0xfe, 0x44, 0xac, 0xf9, 0x9e, 0x81, 0x12, 0x2f, 0x73, 0xd3, 0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1, 0x23, 0xfc, 0x13, 0x56, 0xde, 0xa2, 0x23, 0x71, 0x25, 0x99, 0x75, 0x8a, 0x2f, 0x6f, 0xfe, 0x91, 0x92, 0x1c, 0x1a, 0xce, 0xe3, 0xec, 0x6c, 0x7b, 0x7a, 0x29, 0xa1, 0xd3, 0xc5, 0xf8, 0x8a, 0xe6, 0xfb, 0x50, 0xb4, 0x2e, 0x36, 0xc0, 0x77, 0x37, 0x31, 0xe2, 0x8c, 0xa3, 0xc9, 0x3a, 0x18, 0x62, 0x7d, 0x28, 0x7e, 0xd5, 0xf5, 0x38, 0x69, 0x14, 0x21, 0xdf, 0xfd, 0x36, 0xe3, 0xbb, 0x87, 0x18, 0x54, 0xbc, 0x58, 0x5f, 0x36, 0x7e, 0xdb, 0xe7, 0x0b, 0x02, 0x9f, 0x81, 0xf3, 0x60, 0x59, 0x82, 0xea, 0xfa, 0x41, 0x35, 0xe5, 0x4b, 0x78, 0xd0, 0xc6, 0xcd, 0xf1, 0x8a, 0xfe, 0x22, 0xff, 0x73, 0x08, 0xda, 0x70, 0x11, 0xf1, 0x5d, 0x35, 0x24, 0x90, 0x6f, 0x10, 0xfb, 0x6b, 0x78, 0x0f, 0xa9, 0xcc, 0x4b]) - let nonce: [UInt8] = [0xa6, 0xaa, 0xd9, 0xec, 0xed, 0x14, 0xbf, 0x1c, 0x61, 0x91, 0x0d, 0xba, 0, 0, 0, 35] + let key: [UInt8] = [0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81, 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4] + let plaintext = Data([0xFD, 0x4C, 0x14, 0x72, 0x9F, 0x50, 0x04, 0xBA, 0x49, 0xD8, 0x32, 0xAD, 0x7B, 0xE8, 0x7C, 0x18, 0xF4, 0xFA, 0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x14, 0x21, 0xDF, 0xFD, 0x36, 0xE3, 0xBB, 0x87, 0x18, 0x54, 0xBC, 0x58, 0x5F, 0x36, 0x7E, 0xDB, 0xE7, 0x0B, 0x02, 0x9F, 0x81, 0xF3, 0x60, 0x59, 0x82, 0xEA, 0xFA, 0x41, 0x35, 0xE5, 0x4B, 0x78, 0xD0, 0xC6, 0xCD, 0xF1, 0x8A, 0xFE, 0x22, 0xFF, 0x73, 0x08, 0xDA, 0x70, 0x11, 0xF1, 0x5D, 0x35, 0x24, 0x90, 0x6F, 0x10, 0xFB, 0x6B, 0x78, 0x0F, 0xA9, 0xCC, 0x4B]) + let nonce: [UInt8] = [0xA6, 0xAA, 0xD9, 0xEC, 0xED, 0x14, 0xBF, 0x1C, 0x61, 0x91, 0x0D, 0xBA, 0, 0, 0, 35] var ciphertext = plaintext try! Aes256Ctr32.process(&ciphertext, key: key, nonce: nonce) diff --git a/swift/Tests/LibSignalClientTests/HsmEnclaveTests.swift b/swift/Tests/LibSignalClientTests/HsmEnclaveTests.swift index ea6e7030..fee59ff5 100644 --- a/swift/Tests/LibSignalClientTests/HsmEnclaveTests.swift +++ b/swift/Tests/LibSignalClientTests/HsmEnclaveTests.swift @@ -3,11 +3,10 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest import LibSignalClient +import XCTest class HsmEnclaveTests: TestCaseBase { - func testCreateClient() { let validKey = IdentityKeyPair.generate().publicKey var hashes = HsmCodeHashList() diff --git a/swift/Tests/LibSignalClientTests/IasTests.swift b/swift/Tests/LibSignalClientTests/IasTests.swift index d8aa5114..69dca978 100644 --- a/swift/Tests/LibSignalClientTests/IasTests.swift +++ b/swift/Tests/LibSignalClientTests/IasTests.swift @@ -3,21 +3,20 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest import LibSignalClient +import XCTest class IasTests: TestCaseBase { - func testSignatureValidation() throws { let signatureData = Data(base64Encoded: goodSignature)! let messageData = Data(base64Encoded: goodMessage)! let pemBytes = Array(goodPem.utf8) XCTAssertTrue(Ias.verify( - signature: signatureData, - of: messageData, - withCertificatesPem: pemBytes, - at: Date() + signature: signatureData, + of: messageData, + withCertificatesPem: pemBytes, + at: Date() )) } @@ -28,10 +27,10 @@ class IasTests: TestCaseBase { pemBytes.swapAt(129, 140) XCTAssertFalse(Ias.verify( - signature: signatureData, - of: messageData, - withCertificatesPem: pemBytes, - at: Date() + signature: signatureData, + of: messageData, + withCertificatesPem: pemBytes, + at: Date() )) } @@ -42,10 +41,10 @@ class IasTests: TestCaseBase { let pemBytes = Array(goodPem.utf8) XCTAssertFalse(Ias.verify( - signature: signatureData, - of: messageData, - withCertificatesPem: pemBytes, - at: Date() + signature: signatureData, + of: messageData, + withCertificatesPem: pemBytes, + at: Date() )) } @@ -55,10 +54,10 @@ class IasTests: TestCaseBase { let pemBytes = Array(goodPem.utf8) XCTAssertFalse(Ias.verify( - signature: signatureData, - of: messageData, - withCertificatesPem: pemBytes, - at: .distantFuture + signature: signatureData, + of: messageData, + withCertificatesPem: pemBytes, + at: .distantFuture )) } diff --git a/swift/Tests/LibSignalClientTests/IncrementalMacTests.swift b/swift/Tests/LibSignalClientTests/IncrementalMacTests.swift index 568e4055..29cd777f 100644 --- a/swift/Tests/LibSignalClientTests/IncrementalMacTests.swift +++ b/swift/Tests/LibSignalClientTests/IncrementalMacTests.swift @@ -4,8 +4,8 @@ // import Foundation -import XCTest import LibSignalClient +import XCTest class IncrementalMacTests: TestCaseBase { private let TEST_KEY = Data(base64Encoded: "qDSBRX7+zGmtE0LiHZwCl/cd679ckwS0wbLkM8Gnj5g=")! @@ -15,24 +15,24 @@ class IncrementalMacTests: TestCaseBase { func testIncrementalDigestCreation() throws { let mac = try IncrementalMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE) - for d in TEST_INPUT { + for d in self.TEST_INPUT { try mac.update(d) } let digest = try mac.finalize() - XCTAssertEqual(TEST_DIGEST, digest) + XCTAssertEqual(self.TEST_DIGEST, digest) } func testIncrementalValidationSuccess() throws { let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST) - for d in TEST_INPUT { - _ = try mac.update(d) - } + for d in self.TEST_INPUT { + _ = try mac.update(d) + } _ = try mac.finalize() } func testNoBytesCanBeConsumedWithoutValidation() throws { - var corruptInput = TEST_INPUT - corruptInput[0][1] ^= 0xff + var corruptInput = self.TEST_INPUT + corruptInput[0][1] ^= 0xFF let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST) XCTAssertEqual(0, try mac.update(corruptInput[0])) @@ -46,8 +46,8 @@ class IncrementalMacTests: TestCaseBase { } func testIncrementalValidationFailureInFinalize() throws { - var corruptInput = TEST_INPUT - corruptInput[2][0] ^= 0xff + var corruptInput = self.TEST_INPUT + corruptInput[2][0] ^= 0xFF let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST) XCTAssertEqual(0, try mac.update(corruptInput[0])) diff --git a/swift/Tests/LibSignalClientTests/IoUtils.swift b/swift/Tests/LibSignalClientTests/IoUtils.swift index 78796f3a..d1a761f5 100644 --- a/swift/Tests/LibSignalClientTests/IoUtils.swift +++ b/swift/Tests/LibSignalClientTests/IoUtils.swift @@ -25,30 +25,30 @@ public class ThrowsAfterInputStream: SignalInputStream { } public func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int { - if readBeforeThrow == 0 { + if self.readBeforeThrow == 0 { throw TestIoError() } var target = buffer - if buffer.count > readBeforeThrow { - target = UnsafeMutableRawBufferPointer(rebasing: buffer[.. self.readBeforeThrow { + target = UnsafeMutableRawBufferPointer(rebasing: buffer[.. 0 { - readBeforeThrow -= UInt64(read) + self.readBeforeThrow -= UInt64(read) } return read } public func skip(by amount: UInt64) throws { - if readBeforeThrow < amount { - readBeforeThrow = 0 + if self.readBeforeThrow < amount { + self.readBeforeThrow = 0 throw TestIoError() } - try inner.skip(by: amount) - readBeforeThrow -= amount + try self.inner.skip(by: amount) + self.readBeforeThrow -= amount } private var inner: SignalInputStream diff --git a/swift/Tests/LibSignalClientTests/MediaSanitizerTests.swift b/swift/Tests/LibSignalClientTests/MediaSanitizerTests.swift index ede511c0..13c5618c 100644 --- a/swift/Tests/LibSignalClientTests/MediaSanitizerTests.swift +++ b/swift/Tests/LibSignalClientTests/MediaSanitizerTests.swift @@ -5,8 +5,8 @@ #if SIGNAL_MEDIA_SUPPORTED -import XCTest @testable import LibSignalClient +import XCTest class Mp4SanitizerTests: TestCaseBase { func testEmptyMp4() { @@ -129,7 +129,7 @@ private func webp() -> [UInt8] { webp.append(contentsOf: "VP8L") // chunk type webp.append(contentsOf: [8, 0, 0, 0]) // chunk size - webp.append(contentsOf: [0x2f, 0, 0, 0, 0, 0x88, 0x88, 8]) // VP8L data + webp.append(contentsOf: [0x2F, 0, 0, 0, 0, 0x88, 0x88, 8]) // VP8L data return webp } diff --git a/swift/Tests/LibSignalClientTests/MessageBackupTests.swift b/swift/Tests/LibSignalClientTests/MessageBackupTests.swift index be379f85..b329fd7e 100644 --- a/swift/Tests/LibSignalClientTests/MessageBackupTests.swift +++ b/swift/Tests/LibSignalClientTests/MessageBackupTests.swift @@ -8,61 +8,59 @@ import XCTest @testable import LibSignalClient class MessageBackupTests: TestCaseBase { - func testValidInput() throws { - let validBackupContents = readResource(forName: "new_account.binproto.encrypted") + func testValidInput() throws { + let validBackupContents = readResource(forName: "new_account.binproto.encrypted") - let outcome = try Self.validateBackup(bytes: validBackupContents) - XCTAssertEqual(outcome.fields, []) - } - - func testInvalidInput() throws { - // Start with a valid file, then overwrite some bytes - var bytes = readResource(forName: "new_account.binproto.encrypted") - bytes.replaceSubrange(0..<32, with: Array(repeating: 0, count: 32)) - // Validation failed, so this should throw. - XCTAssertThrowsError(try Self.validateBackup(bytes: bytes)) { error in - if let error = error as? MessageBackupValidationError { - XCTAssertEqual(error.errorMessage, "HMAC doesn't match") - } else { - XCTFail("\(error)") - } + let outcome = try Self.validateBackup(bytes: validBackupContents) + XCTAssertEqual(outcome.fields, []) } - } - func testEmptyInput() throws { - XCTAssertThrowsError(try Self.validateBackup(bytes: [])) { error in - if let error = error as? MessageBackupValidationError { - XCTAssertEqual(error.errorMessage, "not enough bytes for an HMAC") - } else { - XCTFail("\(error)") - } + func testInvalidInput() throws { + // Start with a valid file, then overwrite some bytes + var bytes = readResource(forName: "new_account.binproto.encrypted") + bytes.replaceSubrange(0..<32, with: Array(repeating: 0, count: 32)) + // Validation failed, so this should throw. + XCTAssertThrowsError(try Self.validateBackup(bytes: bytes)) { error in + if let error = error as? MessageBackupValidationError { + XCTAssertEqual(error.errorMessage, "HMAC doesn't match") + } else { + XCTFail("\(error)") + } + } } - } - func testInputThrowsAfter() { - let bytes = readResource(forName: "new_account.binproto.encrypted") - let makeStream = { ThrowsAfterInputStream(inner: SignalInputStreamAdapter(bytes), readBeforeThrow: UInt64(bytes.count) - 1) } - XCTAssertThrowsError( - try validateMessageBackup(key: MessageBackupKey.testKey(), length: UInt64(bytes.count), makeStream: makeStream) - ) { error in - if error is TestIoError {} else { XCTFail("\(error)") } + func testEmptyInput() throws { + XCTAssertThrowsError(try Self.validateBackup(bytes: [])) { error in + if let error = error as? MessageBackupValidationError { + XCTAssertEqual(error.errorMessage, "not enough bytes for an HMAC") + } else { + XCTFail("\(error)") + } + } } - } - static func validateBackup(bytes: Input) throws -> MessageBackupUnknownFields - where Input: Collection { - try validateMessageBackup(key: MessageBackupKey.testKey(), length: UInt64(bytes.count), makeStream: { SignalInputStreamAdapter(bytes) }) - } + func testInputThrowsAfter() { + let bytes = readResource(forName: "new_account.binproto.encrypted") + let makeStream = { ThrowsAfterInputStream(inner: SignalInputStreamAdapter(bytes), readBeforeThrow: UInt64(bytes.count) - 1) } + XCTAssertThrowsError( + try validateMessageBackup(key: MessageBackupKey.testKey(), length: UInt64(bytes.count), makeStream: makeStream) + ) { error in + if error is TestIoError {} else { XCTFail("\(error)") } + } + } + + static func validateBackup(bytes: some Collection) throws -> MessageBackupUnknownFields { + try validateMessageBackup(key: MessageBackupKey.testKey(), length: UInt64(bytes.count), makeStream: { SignalInputStreamAdapter(bytes) }) + } } extension MessageBackupKey { - public static func testKey() -> MessageBackupKey { - let masterKey = Array(repeating: Character("M").asciiValue!, count: 32) - let uuid: uuid_t = ( - 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 - ) - let aci = Aci(fromUUID: UUID(uuid: uuid)) - return try! MessageBackupKey(masterKey: masterKey, aci: aci) - } - + public static func testKey() -> MessageBackupKey { + let masterKey = Array(repeating: Character("M").asciiValue!, count: 32) + let uuid: uuid_t = ( + 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 + ) + let aci = Aci(fromUUID: UUID(uuid: uuid)) + return try! MessageBackupKey(masterKey: masterKey, aci: aci) + } } diff --git a/swift/Tests/LibSignalClientTests/NetTests.swift b/swift/Tests/LibSignalClientTests/NetTests.swift index 56ce419d..cd996d53 100644 --- a/swift/Tests/LibSignalClientTests/NetTests.swift +++ b/swift/Tests/LibSignalClientTests/NetTests.swift @@ -6,12 +6,11 @@ // These testing endpoints aren't generated in device builds, to save on code size. #if !os(iOS) || targetEnvironment(simulator) -import XCTest @testable import LibSignalClient import SignalFfi +import XCTest final class NetTests: XCTestCase { - func testCdsiLookupResultConversion() async throws { let ACI_UUID = "9d0652a3-dcc3-4d11-975f-74d61598733f" let PNI_UUID = "796abedb-ca4e-4f18-8803-1fde5b921f9f" @@ -30,13 +29,13 @@ final class NetTests: XCTestCase { let entryList = LookupResponseEntryList(owned: output.entries) let expected = [SignalFfiCdsiLookupResponseEntry( - e164: 18005551011, + e164: 18_005_551_011, aci, pni ), SignalFfiCdsiLookupResponseEntry( - e164: 18005551012, + e164: 18_005_551_012, nil, pni - ) ] + )] XCTAssertEqual(expected, Array(entryList)) } diff --git a/swift/Tests/LibSignalClientTests/PinTests.swift b/swift/Tests/LibSignalClientTests/PinTests.swift index 119521da..92694046 100644 --- a/swift/Tests/LibSignalClientTests/PinTests.swift +++ b/swift/Tests/LibSignalClientTests/PinTests.swift @@ -8,7 +8,6 @@ import LibSignalClient import XCTest class PinTests: TestCaseBase { - func testBadSaltLength() { XCTAssertThrowsError(try PinHash(normalizedPin: Array("password".utf8), salt: [0xFF])) { guard case SignalError.invalidType(_) = $0 else { diff --git a/swift/Tests/LibSignalClientTests/PublicAPITests.swift b/swift/Tests/LibSignalClientTests/PublicAPITests.swift index 14e97135..c665b9cb 100644 --- a/swift/Tests/LibSignalClientTests/PublicAPITests.swift +++ b/swift/Tests/LibSignalClientTests/PublicAPITests.swift @@ -3,42 +3,124 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest import LibSignalClient +import XCTest class PublicAPITests: TestCaseBase { func testHkdfSimple() { let ikm: [UInt8] = [ - 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, - 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, + 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, ] let info: [UInt8] = [] let salt: [UInt8] = [] - let okm: [UInt8] = [0x8d, 0xa4, 0xe7, 0x75] + let okm: [UInt8] = [0x8D, 0xA4, 0xE7, 0x75] - let derived = try! hkdf(outputLength: okm.count, - inputKeyMaterial: ikm, - salt: salt, - info: info) + let derived = try! hkdf( + outputLength: okm.count, + inputKeyMaterial: ikm, + salt: salt, + info: info + ) XCTAssertEqual(derived, okm) } func testHkdfUsingRFCExample() { // https://tools.ietf.org/html/rfc5869 A.2 - let ikm: [UInt8] = Array(0...0x4f) - let salt: [UInt8] = Array(0x60...0xaf) - let info: [UInt8] = Array(0xb0...0xff) - let okm: [UInt8] = [0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a, 0x49, 0x34, - 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf, 0xa9, 0x7c, - 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09, - 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, - 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, - 0x1d, 0x87] + let ikm: [UInt8] = Array(0...0x4F) + let salt: [UInt8] = Array(0x60...0xAF) + let info: [UInt8] = Array(0xB0...0xFF) + let okm: [UInt8] = [ + 0xB1, + 0x1E, + 0x39, + 0x8D, + 0xC8, + 0x03, + 0x27, + 0xA1, + 0xC8, + 0xE7, + 0xF7, + 0x8C, + 0x59, + 0x6A, + 0x49, + 0x34, + 0x4F, + 0x01, + 0x2E, + 0xDA, + 0x2D, + 0x4E, + 0xFA, + 0xD8, + 0xA0, + 0x50, + 0xCC, + 0x4C, + 0x19, + 0xAF, + 0xA9, + 0x7C, + 0x59, + 0x04, + 0x5A, + 0x99, + 0xCA, + 0xC7, + 0x82, + 0x72, + 0x71, + 0xCB, + 0x41, + 0xC6, + 0x5E, + 0x59, + 0x0E, + 0x09, + 0xDA, + 0x32, + 0x75, + 0x60, + 0x0C, + 0x2F, + 0x09, + 0xB8, + 0x36, + 0x77, + 0x93, + 0xA9, + 0xAC, + 0xA3, + 0xDB, + 0x71, + 0xCC, + 0x30, + 0xC5, + 0x81, + 0x79, + 0xEC, + 0x3E, + 0x87, + 0xC1, + 0x4C, + 0x01, + 0xD5, + 0xC1, + 0xF3, + 0x43, + 0x4F, + 0x1D, + 0x87, + ] - let derived = try! hkdf(outputLength: okm.count, - inputKeyMaterial: ikm, - salt: salt, - info: info) + let derived = try! hkdf( + outputLength: okm.count, + inputKeyMaterial: ikm, + salt: salt, + info: info + ) XCTAssertEqual(derived, okm) } @@ -103,40 +185,43 @@ class PublicAPITests: TestCaseBase { } func testFingerprint() { + let ALICE_IDENTITY: [UInt8] = [0x05, 0x06, 0x86, 0x3B, 0xC6, 0x6D, 0x02, 0xB4, 0x0D, 0x27, 0xB8, 0xD4, 0x9C, 0xA7, 0xC0, 0x9E, 0x92, 0x39, 0x23, 0x6F, 0x9D, 0x7D, 0x25, 0xD6, 0xFC, 0xCA, 0x5C, 0xE1, 0x3C, 0x70, 0x64, 0xD8, 0x68] + let BOB_IDENTITY: [UInt8] = [0x05, 0xF7, 0x81, 0xB6, 0xFB, 0x32, 0xFE, 0xD9, 0xBA, 0x1C, 0xF2, 0xDE, 0x97, 0x8D, 0x4D, 0x5D, 0xA2, 0x8D, 0xC3, 0x40, 0x46, 0xAE, 0x81, 0x44, 0x02, 0xB5, 0xC0, 0xDB, 0xD9, 0x6F, 0xDA, 0x90, 0x7B] - let ALICE_IDENTITY: [UInt8] = [0x05, 0x06, 0x86, 0x3b, 0xc6, 0x6d, 0x02, 0xb4, 0x0d, 0x27, 0xb8, 0xd4, 0x9c, 0xa7, 0xc0, 0x9e, 0x92, 0x39, 0x23, 0x6f, 0x9d, 0x7d, 0x25, 0xd6, 0xfc, 0xca, 0x5c, 0xe1, 0x3c, 0x70, 0x64, 0xd8, 0x68] - let BOB_IDENTITY: [UInt8] = [0x05, 0xf7, 0x81, 0xb6, 0xfb, 0x32, 0xfe, 0xd9, 0xba, 0x1c, 0xf2, 0xde, 0x97, 0x8d, 0x4d, 0x5d, 0xa2, 0x8d, 0xc3, 0x40, 0x46, 0xae, 0x81, 0x44, 0x02, 0xb5, 0xc0, 0xdb, 0xd9, 0x6f, 0xda, 0x90, 0x7b] + let VERSION_1 = 1 + let DISPLAYABLE_FINGERPRINT_V1 = "300354477692869396892869876765458257569162576843440918079131" + let ALICE_SCANNABLE_FINGERPRINT_V1: [UInt8] = [0x08, 0x01, 0x12, 0x22, 0x0A, 0x20, 0x1E, 0x30, 0x1A, 0x03, 0x53, 0xDC, 0xE3, 0xDB, 0xE7, 0x68, 0x4C, 0xB8, 0x33, 0x6E, 0x85, 0x13, 0x6C, 0xDC, 0x0E, 0xE9, 0x62, 0x19, 0x49, 0x4A, 0xDA, 0x30, 0x5D, 0x62, 0xA7, 0xBD, 0x61, 0xDF, 0x1A, 0x22, 0x0A, 0x20, 0xD6, 0x2C, 0xBF, 0x73, 0xA1, 0x15, 0x92, 0x01, 0x5B, 0x6B, 0x9F, 0x16, 0x82, 0xAC, 0x30, 0x6F, 0xEA, 0x3A, 0xAF, 0x38, 0x85, 0xB8, 0x4D, 0x12, 0xBC, 0xA6, 0x31, 0xE9, 0xD4, 0xFB, 0x3A, 0x4D] + let BOB_SCANNABLE_FINGERPRINT_V1: [UInt8] = [0x08, 0x01, 0x12, 0x22, 0x0A, 0x20, 0xD6, 0x2C, 0xBF, 0x73, 0xA1, 0x15, 0x92, 0x01, 0x5B, 0x6B, 0x9F, 0x16, 0x82, 0xAC, 0x30, 0x6F, 0xEA, 0x3A, 0xAF, 0x38, 0x85, 0xB8, 0x4D, 0x12, 0xBC, 0xA6, 0x31, 0xE9, 0xD4, 0xFB, 0x3A, 0x4D, 0x1A, 0x22, 0x0A, 0x20, 0x1E, 0x30, 0x1A, 0x03, 0x53, 0xDC, 0xE3, 0xDB, 0xE7, 0x68, 0x4C, 0xB8, 0x33, 0x6E, 0x85, 0x13, 0x6C, 0xDC, 0x0E, 0xE9, 0x62, 0x19, 0x49, 0x4A, 0xDA, 0x30, 0x5D, 0x62, 0xA7, 0xBD, 0x61, 0xDF] - let VERSION_1 = 1 - let DISPLAYABLE_FINGERPRINT_V1 = "300354477692869396892869876765458257569162576843440918079131" - let ALICE_SCANNABLE_FINGERPRINT_V1: [UInt8] = [0x08, 0x01, 0x12, 0x22, 0x0a, 0x20, 0x1e, 0x30, 0x1a, 0x03, 0x53, 0xdc, 0xe3, 0xdb, 0xe7, 0x68, 0x4c, 0xb8, 0x33, 0x6e, 0x85, 0x13, 0x6c, 0xdc, 0x0e, 0xe9, 0x62, 0x19, 0x49, 0x4a, 0xda, 0x30, 0x5d, 0x62, 0xa7, 0xbd, 0x61, 0xdf, 0x1a, 0x22, 0x0a, 0x20, 0xd6, 0x2c, 0xbf, 0x73, 0xa1, 0x15, 0x92, 0x01, 0x5b, 0x6b, 0x9f, 0x16, 0x82, 0xac, 0x30, 0x6f, 0xea, 0x3a, 0xaf, 0x38, 0x85, 0xb8, 0x4d, 0x12, 0xbc, 0xa6, 0x31, 0xe9, 0xd4, 0xfb, 0x3a, 0x4d] - let BOB_SCANNABLE_FINGERPRINT_V1: [UInt8] = [0x08, 0x01, 0x12, 0x22, 0x0a, 0x20, 0xd6, 0x2c, 0xbf, 0x73, 0xa1, 0x15, 0x92, 0x01, 0x5b, 0x6b, 0x9f, 0x16, 0x82, 0xac, 0x30, 0x6f, 0xea, 0x3a, 0xaf, 0x38, 0x85, 0xb8, 0x4d, 0x12, 0xbc, 0xa6, 0x31, 0xe9, 0xd4, 0xfb, 0x3a, 0x4d, 0x1a, 0x22, 0x0a, 0x20, 0x1e, 0x30, 0x1a, 0x03, 0x53, 0xdc, 0xe3, 0xdb, 0xe7, 0x68, 0x4c, 0xb8, 0x33, 0x6e, 0x85, 0x13, 0x6c, 0xdc, 0x0e, 0xe9, 0x62, 0x19, 0x49, 0x4a, 0xda, 0x30, 0x5d, 0x62, 0xa7, 0xbd, 0x61, 0xdf] - - let VERSION_2 = 2 - let DISPLAYABLE_FINGERPRINT_V2 = DISPLAYABLE_FINGERPRINT_V1 - let ALICE_SCANNABLE_FINGERPRINT_V2: [UInt8] = [0x08, 0x02, 0x12, 0x22, 0x0a, 0x20, 0x1e, 0x30, 0x1a, 0x03, 0x53, 0xdc, 0xe3, 0xdb, 0xe7, 0x68, 0x4c, 0xb8, 0x33, 0x6e, 0x85, 0x13, 0x6c, 0xdc, 0x0e, 0xe9, 0x62, 0x19, 0x49, 0x4a, 0xda, 0x30, 0x5d, 0x62, 0xa7, 0xbd, 0x61, 0xdf, 0x1a, 0x22, 0x0a, 0x20, 0xd6, 0x2c, 0xbf, 0x73, 0xa1, 0x15, 0x92, 0x01, 0x5b, 0x6b, 0x9f, 0x16, 0x82, 0xac, 0x30, 0x6f, 0xea, 0x3a, 0xaf, 0x38, 0x85, 0xb8, 0x4d, 0x12, 0xbc, 0xa6, 0x31, 0xe9, 0xd4, 0xfb, 0x3a, 0x4d] - let BOB_SCANNABLE_FINGERPRINT_V2: [UInt8] = [0x08, 0x02, 0x12, 0x22, 0x0a, 0x20, 0xd6, 0x2c, 0xbf, 0x73, 0xa1, 0x15, 0x92, 0x01, 0x5b, 0x6b, 0x9f, 0x16, 0x82, 0xac, 0x30, 0x6f, 0xea, 0x3a, 0xaf, 0x38, 0x85, 0xb8, 0x4d, 0x12, 0xbc, 0xa6, 0x31, 0xe9, 0xd4, 0xfb, 0x3a, 0x4d, 0x1a, 0x22, 0x0a, 0x20, 0x1e, 0x30, 0x1a, 0x03, 0x53, 0xdc, 0xe3, 0xdb, 0xe7, 0x68, 0x4c, 0xb8, 0x33, 0x6e, 0x85, 0x13, 0x6c, 0xdc, 0x0e, 0xe9, 0x62, 0x19, 0x49, 0x4a, 0xda, 0x30, 0x5d, 0x62, 0xa7, 0xbd, 0x61, 0xdf] + let VERSION_2 = 2 + let DISPLAYABLE_FINGERPRINT_V2 = DISPLAYABLE_FINGERPRINT_V1 + let ALICE_SCANNABLE_FINGERPRINT_V2: [UInt8] = [0x08, 0x02, 0x12, 0x22, 0x0A, 0x20, 0x1E, 0x30, 0x1A, 0x03, 0x53, 0xDC, 0xE3, 0xDB, 0xE7, 0x68, 0x4C, 0xB8, 0x33, 0x6E, 0x85, 0x13, 0x6C, 0xDC, 0x0E, 0xE9, 0x62, 0x19, 0x49, 0x4A, 0xDA, 0x30, 0x5D, 0x62, 0xA7, 0xBD, 0x61, 0xDF, 0x1A, 0x22, 0x0A, 0x20, 0xD6, 0x2C, 0xBF, 0x73, 0xA1, 0x15, 0x92, 0x01, 0x5B, 0x6B, 0x9F, 0x16, 0x82, 0xAC, 0x30, 0x6F, 0xEA, 0x3A, 0xAF, 0x38, 0x85, 0xB8, 0x4D, 0x12, 0xBC, 0xA6, 0x31, 0xE9, 0xD4, 0xFB, 0x3A, 0x4D] + let BOB_SCANNABLE_FINGERPRINT_V2: [UInt8] = [0x08, 0x02, 0x12, 0x22, 0x0A, 0x20, 0xD6, 0x2C, 0xBF, 0x73, 0xA1, 0x15, 0x92, 0x01, 0x5B, 0x6B, 0x9F, 0x16, 0x82, 0xAC, 0x30, 0x6F, 0xEA, 0x3A, 0xAF, 0x38, 0x85, 0xB8, 0x4D, 0x12, 0xBC, 0xA6, 0x31, 0xE9, 0xD4, 0xFB, 0x3A, 0x4D, 0x1A, 0x22, 0x0A, 0x20, 0x1E, 0x30, 0x1A, 0x03, 0x53, 0xDC, 0xE3, 0xDB, 0xE7, 0x68, 0x4C, 0xB8, 0x33, 0x6E, 0x85, 0x13, 0x6C, 0xDC, 0x0E, 0xE9, 0x62, 0x19, 0x49, 0x4A, 0xDA, 0x30, 0x5D, 0x62, 0xA7, 0xBD, 0x61, 0xDF] // testVectorsVersion1 - let aliceStableId: [UInt8] = [UInt8]("+14152222222".utf8) - let bobStableId: [UInt8] = [UInt8]("+14153333333".utf8) + let aliceStableId = [UInt8]("+14152222222".utf8) + let bobStableId = [UInt8]("+14153333333".utf8) let aliceIdentityKey = try! PublicKey(ALICE_IDENTITY) let bobIdentityKey = try! PublicKey(BOB_IDENTITY) let generator = NumericFingerprintGenerator(iterations: 5200) - let aliceFingerprint = try! generator.create(version: VERSION_1, - localIdentifier: aliceStableId, - localKey: aliceIdentityKey, - remoteIdentifier: bobStableId, - remoteKey: bobIdentityKey) + let aliceFingerprint = try! generator.create( + version: VERSION_1, + localIdentifier: aliceStableId, + localKey: aliceIdentityKey, + remoteIdentifier: bobStableId, + remoteKey: bobIdentityKey + ) - let bobFingerprint = try! generator.create(version: VERSION_1, - localIdentifier: bobStableId, - localKey: bobIdentityKey, - remoteIdentifier: aliceStableId, - remoteKey: aliceIdentityKey) + let bobFingerprint = try! generator.create( + version: VERSION_1, + localIdentifier: bobStableId, + localKey: bobIdentityKey, + remoteIdentifier: aliceStableId, + remoteKey: aliceIdentityKey + ) XCTAssertEqual(aliceFingerprint.displayable.formatted, DISPLAYABLE_FINGERPRINT_V1) XCTAssertEqual(bobFingerprint.displayable.formatted, DISPLAYABLE_FINGERPRINT_V1) @@ -149,17 +234,21 @@ class PublicAPITests: TestCaseBase { // testVectorsVersion2 - let aliceFingerprint2 = try! generator.create(version: VERSION_2, - localIdentifier: aliceStableId, - localKey: aliceIdentityKey, - remoteIdentifier: bobStableId, - remoteKey: bobIdentityKey) + let aliceFingerprint2 = try! generator.create( + version: VERSION_2, + localIdentifier: aliceStableId, + localKey: aliceIdentityKey, + remoteIdentifier: bobStableId, + remoteKey: bobIdentityKey + ) - let bobFingerprint2 = try! generator.create(version: VERSION_2, - localIdentifier: bobStableId, - localKey: bobIdentityKey, - remoteIdentifier: aliceStableId, - remoteKey: aliceIdentityKey) + let bobFingerprint2 = try! generator.create( + version: VERSION_2, + localIdentifier: bobStableId, + localKey: bobIdentityKey, + remoteIdentifier: aliceStableId, + remoteKey: aliceIdentityKey + ) XCTAssertEqual(aliceFingerprint2.displayable.formatted, DISPLAYABLE_FINGERPRINT_V2) XCTAssertEqual(bobFingerprint2.displayable.formatted, DISPLAYABLE_FINGERPRINT_V2) @@ -177,20 +266,26 @@ class PublicAPITests: TestCaseBase { let mitmIdentityKey = PrivateKey.generate().publicKey - let aliceFingerprintM = try! generator.create(version: VERSION_1, - localIdentifier: aliceStableId, - localKey: aliceIdentityKey, - remoteIdentifier: bobStableId, - remoteKey: mitmIdentityKey) + let aliceFingerprintM = try! generator.create( + version: VERSION_1, + localIdentifier: aliceStableId, + localKey: aliceIdentityKey, + remoteIdentifier: bobStableId, + remoteKey: mitmIdentityKey + ) - let bobFingerprintM = try! generator.create(version: VERSION_1, - localIdentifier: bobStableId, - localKey: bobIdentityKey, - remoteIdentifier: aliceStableId, - remoteKey: aliceIdentityKey) + let bobFingerprintM = try! generator.create( + version: VERSION_1, + localIdentifier: bobStableId, + localKey: bobIdentityKey, + remoteIdentifier: aliceStableId, + remoteKey: aliceIdentityKey + ) - XCTAssertNotEqual(aliceFingerprintM.displayable.formatted, - bobFingerprintM.displayable.formatted) + XCTAssertNotEqual( + aliceFingerprintM.displayable.formatted, + bobFingerprintM.displayable.formatted + ) XCTAssertFalse(try! bobFingerprintM.scannable.compare(againstEncoding: aliceFingerprintM.scannable.encoding)) XCTAssertFalse(try! aliceFingerprintM.scannable.compare(againstEncoding: bobFingerprintM.scannable.encoding)) @@ -199,22 +294,28 @@ class PublicAPITests: TestCaseBase { // testMismatchingIdentifiers - let badBobStableId: [UInt8] = [UInt8]("+14153333334".utf8) + let badBobStableId = [UInt8]("+14153333334".utf8) - let aliceFingerprintI = try! generator.create(version: VERSION_1, - localIdentifier: aliceStableId, - localKey: aliceIdentityKey, - remoteIdentifier: badBobStableId, - remoteKey: bobIdentityKey) + let aliceFingerprintI = try! generator.create( + version: VERSION_1, + localIdentifier: aliceStableId, + localKey: aliceIdentityKey, + remoteIdentifier: badBobStableId, + remoteKey: bobIdentityKey + ) - let bobFingerprintI = try! generator.create(version: VERSION_1, - localIdentifier: bobStableId, - localKey: bobIdentityKey, - remoteIdentifier: aliceStableId, - remoteKey: aliceIdentityKey) + let bobFingerprintI = try! generator.create( + version: VERSION_1, + localIdentifier: bobStableId, + localKey: bobIdentityKey, + remoteIdentifier: aliceStableId, + remoteKey: aliceIdentityKey + ) - XCTAssertNotEqual(aliceFingerprintI.displayable.formatted, - bobFingerprintI.displayable.formatted) + XCTAssertNotEqual( + aliceFingerprintI.displayable.formatted, + bobFingerprintI.displayable.formatted + ) XCTAssertFalse(try! bobFingerprintI.scannable.compare(againstEncoding: aliceFingerprintI.scannable.encoding)) XCTAssertFalse(try! aliceFingerprintI.scannable.compare(againstEncoding: bobFingerprintI.scannable.encoding)) @@ -224,7 +325,6 @@ class PublicAPITests: TestCaseBase { } func testGroupCipher() { - let sender = try! ProtocolAddress(name: "+14159999111", deviceId: 4) let distribution_id = UUID(uuidString: "d1d1d1d1-7000-11eb-b32a-33b8a8a487a6")! @@ -239,10 +339,12 @@ class PublicAPITests: TestCaseBase { let a_ctext = try! groupEncrypt([1, 2, 3], from: sender, distributionId: distribution_id, store: a_store, context: NullContext()).serialize() let b_store = InMemorySignalProtocolStore() - try! processSenderKeyDistributionMessage(skdm_r, - from: sender, - store: b_store, - context: NullContext()) + try! processSenderKeyDistributionMessage( + skdm_r, + from: sender, + store: b_store, + context: NullContext() + ) let b_ptext = try! groupDecrypt(a_ctext, from: sender, store: b_store, context: NullContext()) XCTAssertEqual(b_ptext, [1, 2, 3]) @@ -258,7 +360,7 @@ class PublicAPITests: TestCaseBase { } override func loadSenderKey(from sender: ProtocolAddress, distributionId: UUID, context: StoreContext) throws -> SenderKeyRecord? { - XCTAssertIdentical(expectedContext, context as AnyObject) + XCTAssertIdentical(self.expectedContext, context as AnyObject) return try super.loadSenderKey(from: sender, distributionId: distributionId, context: context) } } @@ -281,25 +383,26 @@ class PublicAPITests: TestCaseBase { func testSenderCertificates() { let senderCertBits: [UInt8] = [ - 0x0a, 0xcd, 0x01, 0x0a, 0x0c, 0x2b, 0x31, 0x34, 0x31, 0x35, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x10, 0x2a, 0x19, - 0x2d, 0x63, 0xb5, 0x5f, 0x00, 0x00, 0x00, 0x00, 0x22, 0x21, 0x05, 0xbb, 0x25, 0x64, 0x9c, 0x79, 0x4b, 0xb4, 0x6c, 0x8c, - 0x57, 0x97, 0x69, 0x3c, 0xc8, 0x05, 0xb1, 0xb8, 0x46, 0xda, 0x91, 0x17, 0x6f, 0xec, 0x6a, 0x3e, 0xf2, 0x1f, 0x41, 0x0b, - 0xe9, 0x60, 0x43, 0x2a, 0x69, 0x0a, 0x25, 0x08, 0x01, 0x12, 0x21, 0x05, 0x4f, 0xbf, 0xfa, 0x55, 0xeb, 0xd5, 0x23, 0xd2, - 0x55, 0x16, 0x96, 0x0c, 0xed, 0x28, 0x99, 0xf2, 0x6a, 0x72, 0xfe, 0x26, 0xd0, 0xe0, 0x2a, 0x9d, 0xae, 0x81, 0x67, 0x1f, - 0x46, 0x5b, 0xa1, 0x1d, 0x12, 0x40, 0x7a, 0xbf, 0xdb, 0x83, 0x6c, 0x15, 0xcb, 0x3a, 0x8c, 0x61, 0x76, 0xb3, 0x30, 0x70, - 0xdf, 0xbc, 0x47, 0xea, 0x4a, 0x90, 0x52, 0x35, 0x3a, 0xc4, 0x2f, 0xb8, 0x7e, 0x4e, 0x4d, 0x33, 0x4f, 0x69, 0xa5, 0xe0, - 0xd4, 0xab, 0xd2, 0xdd, 0x81, 0x9f, 0x61, 0xa2, 0xc0, 0x2a, 0x51, 0xc2, 0x74, 0x51, 0xc9, 0x31, 0xaa, 0x85, 0x35, 0xf8, - 0x32, 0x8d, 0x1e, 0xc8, 0xce, 0x7a, 0x2b, 0x9a, 0x9e, 0x01, 0x32, 0x24, 0x39, 0x64, 0x30, 0x36, 0x35, 0x32, 0x61, 0x33, - 0x2d, 0x64, 0x63, 0x63, 0x33, 0x2d, 0x34, 0x64, 0x31, 0x31, 0x2d, 0x39, 0x37, 0x35, 0x66, 0x2d, 0x37, 0x34, 0x64, 0x36, - 0x31, 0x35, 0x39, 0x38, 0x37, 0x33, 0x33, 0x66, 0x12, 0x40, 0x06, 0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, 0xBC, 0x47, 0xEA, 0x4A, 0x90, 0x52, 0x35, 0x3A, 0xC4, 0x2F, 0xB8, 0x7E, 0x4E, 0x4D, 0x33, 0x4F, 0x69, 0xA5, 0xE0, + 0xD4, 0xAB, 0xD2, 0xDD, 0x81, 0x9F, 0x61, 0xA2, 0xC0, 0x2A, 0x51, 0xC2, 0x74, 0x51, 0xC9, 0x31, 0xAA, 0x85, 0x35, 0xF8, + 0x32, 0x8D, 0x1E, 0xC8, 0xCE, 0x7A, 0x2B, 0x9A, 0x9E, 0x01, 0x32, 0x24, 0x39, 0x64, 0x30, 0x36, 0x35, 0x32, 0x61, 0x33, + 0x2D, 0x64, 0x63, 0x63, 0x33, 0x2D, 0x34, 0x64, 0x31, 0x31, 0x2D, 0x39, 0x37, 0x35, 0x66, 0x2D, 0x37, 0x34, 0x64, 0x36, + 0x31, 0x35, 0x39, 0x38, 0x37, 0x33, 0x33, 0x66, 0x12, 0x40, 0x06, 0x8B, 0xF0, 0xC5, 0xE8, 0x99, 0x83, 0x81, 0x28, 0xBD, + 0x36, 0xD9, 0x2B, 0x01, 0xEC, 0xA9, 0x95, 0x9D, 0x00, 0xF2, 0xDB, 0x0B, 0xCB, 0xB6, 0x8B, 0x2A, 0x62, 0xD4, 0xDF, 0x46, + 0xDB, 0xB4, 0x50, 0x14, 0x9E, 0x9D, 0xCB, 0xC6, 0xBD, 0xDB, 0x2B, 0x28, 0x98, 0xFC, 0xD5, 0xFF, 0x5C, 0xAF, 0x1B, 0x8C, + 0xF7, 0x2B, 0x36, 0xFF, 0xFE, 0x2F, 0x55, 0xF3, 0xEC, 0xEB, 0xAB, 0x25, 0x47, 0x88, + ] let senderCert = try! SenderCertificate(senderCertBits) XCTAssertEqual(senderCert.serialize(), senderCertBits) - XCTAssertEqual(senderCert.expiration, 1605722925) + XCTAssertEqual(senderCert.expiration, 1_605_722_925) XCTAssertEqual(senderCert.deviceId, 42) @@ -322,11 +425,13 @@ class PublicAPITests: TestCaseBase { let serverKeys = IdentityKeyPair.generate() let serverCert = try! ServerCertificate(keyId: 1, publicKey: serverKeys.publicKey, trustRoot: trustRoot.privateKey) let senderAddr = try! SealedSenderAddress(aci: aci, deviceId: 1) - let senderCert = try! SenderCertificate(sender: senderAddr, - publicKey: IdentityKeyPair.generate().publicKey, - expiration: 31337, - signerCertificate: serverCert, - signerKey: serverKeys.privateKey) + let senderCert = try! SenderCertificate( + sender: senderAddr, + publicKey: IdentityKeyPair.generate().publicKey, + expiration: 31337, + signerCertificate: serverCert, + signerKey: serverKeys.privateKey + ) XCTAssertNil(senderCert.senderE164) XCTAssertEqual(aci, senderCert.senderAci) @@ -340,13 +445,13 @@ class PublicAPITests: TestCaseBase { func testSerializationRoundTrip() { let keyPair = IdentityKeyPair.generate() - testRoundTrip(keyPair, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) - testRoundTrip(keyPair.publicKey, serialize: { $0.serialize() }, deserialize: { try .init($0) }) - testRoundTrip(keyPair.privateKey, serialize: { $0.serialize() }, deserialize: { try .init($0) }) - testRoundTrip(keyPair.identityKey, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) + self.testRoundTrip(keyPair, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) + self.testRoundTrip(keyPair.publicKey, serialize: { $0.serialize() }, deserialize: { try .init($0) }) + self.testRoundTrip(keyPair.privateKey, serialize: { $0.serialize() }, deserialize: { try .init($0) }) + self.testRoundTrip(keyPair.identityKey, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) let preKeyRecord = try! PreKeyRecord(id: 7, publicKey: keyPair.publicKey, privateKey: keyPair.privateKey) - testRoundTrip(preKeyRecord, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) + self.testRoundTrip(preKeyRecord, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) let signedPreKeyRecord = try! SignedPreKeyRecord( id: 77, @@ -354,7 +459,7 @@ class PublicAPITests: TestCaseBase { privateKey: keyPair.privateKey, signature: keyPair.privateKey.generateSignature(message: keyPair.publicKey.serialize()) ) - testRoundTrip(signedPreKeyRecord, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) + self.testRoundTrip(signedPreKeyRecord, serialize: { $0.serialize() }, deserialize: { try .init(bytes: $0) }) } func testDeviceTransferKey() { diff --git a/swift/Tests/LibSignalClientTests/ServiceIdTests.swift b/swift/Tests/LibSignalClientTests/ServiceIdTests.swift index 6e6df641..9fdb0d38 100644 --- a/swift/Tests/LibSignalClientTests/ServiceIdTests.swift +++ b/swift/Tests/LibSignalClientTests/ServiceIdTests.swift @@ -12,8 +12,8 @@ class ServiceIdTests: TestCaseBase { static let TEST_UUID_STRING = "e36fdce7-36da-4c6f-a21b-9afe2b754650" static let TEST_UUID = UUID(uuidString: TEST_UUID_STRING)! static let TEST_UUID_BYTES: [UInt8] = [ - 0xe3, 0x6f, 0xdc, 0xe7, 0x36, 0xda, 0x4c, 0x6f, - 0xa2, 0x1b, 0x9a, 0xfe, 0x2b, 0x75, 0x46, 0x50 + 0xE3, 0x6F, 0xDC, 0xE7, 0x36, 0xDA, 0x4C, 0x6F, + 0xA2, 0x1B, 0x9A, 0xFE, 0x2B, 0x75, 0x46, 0x50, ] func testAciProperties() throws { @@ -55,11 +55,11 @@ class ServiceIdTests: TestCaseBase { do { _ = try ServiceId.parseFrom(serviceIdString: "ACI:" + Self.TEST_UUID_STRING) XCTFail("Should have failed") - } catch SignalError.invalidArgument { } + } catch SignalError.invalidArgument {} do { _ = try ServiceId.parseFrom(serviceIdString: "") XCTFail("Should have failed") - } catch SignalError.invalidArgument { } + } catch SignalError.invalidArgument {} } func testParseFromBinary() throws { @@ -76,11 +76,11 @@ class ServiceIdTests: TestCaseBase { do { _ = try ServiceId.parseFrom(serviceIdBinary: [0] + Self.TEST_UUID_BYTES) XCTFail("Should have failed") - } catch SignalError.invalidArgument { } + } catch SignalError.invalidArgument {} do { _ = try ServiceId.parseFrom(serviceIdBinary: []) XCTFail("Should have failed") - } catch SignalError.invalidArgument { } + } catch SignalError.invalidArgument {} } // swiftlint:enable force_cast } diff --git a/swift/Tests/LibSignalClientTests/SessionTests.swift b/swift/Tests/LibSignalClientTests/SessionTests.swift index 640b52f9..f3576b5a 100644 --- a/swift/Tests/LibSignalClientTests/SessionTests.swift +++ b/swift/Tests/LibSignalClientTests/SessionTests.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest import LibSignalClient +import XCTest typealias InitSession = ( _ aliceStore: InMemorySignalProtocolStore, @@ -29,45 +29,53 @@ class SessionTests: TestCaseBase { // Alice sends a message: let ptext_a: [UInt8] = [8, 6, 7, 5, 3, 0, 9] - let ctext_a = try! signalEncrypt(message: ptext_a, - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - context: NullContext()) + let ctext_a = try! signalEncrypt( + message: ptext_a, + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + context: NullContext() + ) XCTAssertEqual(ctext_a.messageType, .preKey) let ctext_b = try! PreKeySignalMessage(bytes: ctext_a.serialize()) - let ptext_b = try! signalDecryptPreKey(message: ctext_b, - from: alice_address, - sessionStore: bob_store, - identityStore: bob_store, - preKeyStore: bob_store, - signedPreKeyStore: bob_store, - kyberPreKeyStore: bob_store, - context: NullContext()) + let ptext_b = try! signalDecryptPreKey( + message: ctext_b, + from: alice_address, + sessionStore: bob_store, + identityStore: bob_store, + preKeyStore: bob_store, + signedPreKeyStore: bob_store, + kyberPreKeyStore: bob_store, + context: NullContext() + ) XCTAssertEqual(ptext_a, ptext_b) // Bob replies let ptext2_b: [UInt8] = [23] - let ctext2_b = try! signalEncrypt(message: ptext2_b, - for: alice_address, - sessionStore: bob_store, - identityStore: bob_store, - context: NullContext()) + let ctext2_b = try! signalEncrypt( + message: ptext2_b, + for: alice_address, + sessionStore: bob_store, + identityStore: bob_store, + context: NullContext() + ) XCTAssertEqual(ctext2_b.messageType, .whisper) let ctext2_a = try! SignalMessage(bytes: ctext2_b.serialize()) - let ptext2_a = try! signalDecrypt(message: ctext2_a, - from: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - context: NullContext()) + let ptext2_a = try! signalDecrypt( + message: ctext2_a, + from: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + context: NullContext() + ) XCTAssertEqual(ptext2_a, ptext2_b) } @@ -77,7 +85,7 @@ class SessionTests: TestCaseBase { run(initializeSessionsV3) run(initializeSessionsV4) - func run(_ initSession: InitSession) { + func run(_: InitSession) { let alice_address = try! ProtocolAddress(name: "+14151111111", deviceId: 1) let bob_address = try! ProtocolAddress(name: "+14151111112", deviceId: 1) @@ -89,25 +97,31 @@ class SessionTests: TestCaseBase { // Alice sends a message: let ptext_a: [UInt8] = [8, 6, 7, 5, 3, 0, 9] - let ctext_a = try! signalEncrypt(message: ptext_a, - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - context: NullContext()) + let ctext_a = try! signalEncrypt( + message: ptext_a, + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + context: NullContext() + ) XCTAssertEqual(ctext_a.messageType, .preKey) let ctext_b = try! PreKeySignalMessage(bytes: ctext_a.serialize()) - XCTAssertThrowsError(try signalDecryptPreKey(message: ctext_b, - from: alice_address, - sessionStore: bob_store, - identityStore: bob_store, - preKeyStore: bob_store, - signedPreKeyStore: bob_store, - kyberPreKeyStore: bob_store, - context: NullContext()), - "should fail to decrypt") { error in + XCTAssertThrowsError( + try signalDecryptPreKey( + message: ctext_b, + from: alice_address, + sessionStore: bob_store, + identityStore: bob_store, + preKeyStore: bob_store, + signedPreKeyStore: bob_store, + kyberPreKeyStore: bob_store, + context: NullContext() + ), + "should fail to decrypt" + ) { error in guard case BadStore.Error.badness = error else { XCTFail("wrong error thrown: \(error)") return @@ -133,22 +147,26 @@ class SessionTests: TestCaseBase { let prekey_id: UInt32 = 4570 let signed_prekey_id: UInt32 = 3006 - let bob_bundle = try! PreKeyBundle(registrationId: bob_store.localRegistrationId(context: NullContext()), - deviceId: 9, - prekeyId: prekey_id, - prekey: bob_pre_key.publicKey, - signedPrekeyId: signed_prekey_id, - signedPrekey: bob_signed_pre_key.publicKey, - signedPrekeySignature: bob_signed_pre_key_signature, - identity: bob_identity_key) + let bob_bundle = try! PreKeyBundle( + registrationId: bob_store.localRegistrationId(context: NullContext()), + deviceId: 9, + prekeyId: prekey_id, + prekey: bob_pre_key.publicKey, + signedPrekeyId: signed_prekey_id, + signedPrekey: bob_signed_pre_key.publicKey, + signedPrekeySignature: bob_signed_pre_key_signature, + identity: bob_identity_key + ) // Alice processes the bundle: - try! processPreKeyBundle(bob_bundle, - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - now: Date(timeIntervalSinceReferenceDate: 0), - context: NullContext()) + try! processPreKeyBundle( + bob_bundle, + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + now: Date(timeIntervalSinceReferenceDate: 0), + context: NullContext() + ) let initial_session = try! alice_store.loadSession(for: bob_address, context: NullContext())! XCTAssertTrue(initial_session.hasCurrentState(now: Date(timeIntervalSinceReferenceDate: 0))) @@ -157,12 +175,14 @@ class SessionTests: TestCaseBase { // Alice sends a message: let ptext_a: [UInt8] = [8, 6, 7, 5, 3, 0, 9] - let ctext_a = try! signalEncrypt(message: ptext_a, - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - now: Date(timeIntervalSinceReferenceDate: 0), - context: NullContext()) + let ctext_a = try! signalEncrypt( + message: ptext_a, + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + now: Date(timeIntervalSinceReferenceDate: 0), + context: NullContext() + ) XCTAssertEqual(ctext_a.messageType, .preKey) @@ -170,12 +190,14 @@ class SessionTests: TestCaseBase { XCTAssertTrue(updated_session.hasCurrentState(now: Date(timeIntervalSinceReferenceDate: 0))) XCTAssertFalse(updated_session.hasCurrentState(now: Date(timeIntervalSinceReferenceDate: 60 * 60 * 24 * 90))) - XCTAssertThrowsError(try signalEncrypt(message: ptext_a, - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - now: Date(timeIntervalSinceReferenceDate: 60 * 60 * 24 * 90), - context: NullContext())) + XCTAssertThrowsError(try signalEncrypt( + message: ptext_a, + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + now: Date(timeIntervalSinceReferenceDate: 60 * 60 * 24 * 90), + context: NullContext() + )) } func testSealedSenderSession() throws { @@ -190,57 +212,73 @@ class SessionTests: TestCaseBase { let trust_root = IdentityKeyPair.generate() let server_keys = IdentityKeyPair.generate() let server_cert = try! ServerCertificate(keyId: 1, publicKey: server_keys.publicKey, trustRoot: trust_root.privateKey) - let sender_addr = try! SealedSenderAddress(e164: "+14151111111", - uuidString: alice_address.name, - deviceId: 1) - let sender_cert = try! SenderCertificate(sender: sender_addr, - publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, - expiration: 31337, - signerCertificate: server_cert, - signerKey: server_keys.privateKey) + let sender_addr = try! SealedSenderAddress( + e164: "+14151111111", + uuidString: alice_address.name, + deviceId: 1 + ) + let sender_cert = try! SenderCertificate( + sender: sender_addr, + publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, + expiration: 31337, + signerCertificate: server_cert, + signerKey: server_keys.privateKey + ) let message = Array("2020 vision".utf8) - let ciphertext = try sealedSenderEncrypt(message: message, - for: bob_address, - from: sender_cert, - sessionStore: alice_store, - identityStore: alice_store, - context: NullContext()) + let ciphertext = try sealedSenderEncrypt( + message: message, + for: bob_address, + from: sender_cert, + sessionStore: alice_store, + identityStore: alice_store, + context: NullContext() + ) let recipient_addr = try! SealedSenderAddress(e164: nil, uuidString: bob_address.name, deviceId: 1) - let plaintext = try sealedSenderDecrypt(message: ciphertext, - from: recipient_addr, - trustRoot: trust_root.publicKey, - timestamp: 31335, - sessionStore: bob_store, - identityStore: bob_store, - preKeyStore: bob_store, - signedPreKeyStore: bob_store, - context: NullContext()) + let plaintext = try sealedSenderDecrypt( + message: ciphertext, + from: recipient_addr, + trustRoot: trust_root.publicKey, + timestamp: 31335, + sessionStore: bob_store, + identityStore: bob_store, + preKeyStore: bob_store, + signedPreKeyStore: bob_store, + context: NullContext() + ) XCTAssertEqual(plaintext.message, message) XCTAssertEqual(plaintext.sender, sender_addr) XCTAssertEqual(plaintext.sender.senderAci, alice_address.serviceId) - let innerMessage = try signalEncrypt(message: [], - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - context: NullContext()) + let innerMessage = try signalEncrypt( + message: [], + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + context: NullContext() + ) for hint in [UnidentifiedSenderMessageContent.ContentHint(rawValue: 200), .default, .resendable, .implicit] { - let content = try UnidentifiedSenderMessageContent(innerMessage, - from: sender_cert, - contentHint: hint, - groupId: []) - let ciphertext = try sealedSenderEncrypt(content, - for: bob_address, - identityStore: alice_store, - context: NullContext()) + let content = try UnidentifiedSenderMessageContent( + innerMessage, + from: sender_cert, + contentHint: hint, + groupId: [] + ) + let ciphertext = try sealedSenderEncrypt( + content, + for: bob_address, + identityStore: alice_store, + context: NullContext() + ) - let decryptedContent = try UnidentifiedSenderMessageContent(message: ciphertext, - identityStore: bob_store, - context: NullContext()) + let decryptedContent = try UnidentifiedSenderMessageContent( + message: ciphertext, + identityStore: bob_store, + context: NullContext() + ) XCTAssertEqual(decryptedContent.contentHint, hint) } } @@ -277,21 +315,27 @@ class SessionTests: TestCaseBase { let trust_root = IdentityKeyPair.generate() let server_keys = IdentityKeyPair.generate() let server_cert = try! ServerCertificate(keyId: 1, publicKey: server_keys.publicKey, trustRoot: trust_root.privateKey) - let sender_addr = try! SealedSenderAddress(e164: "+14151111111", - uuidString: alice_address.name, - deviceId: 1) - let sender_cert = try! SenderCertificate(sender: sender_addr, - publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, - expiration: 31337, - signerCertificate: server_cert, - signerKey: server_keys.privateKey) + let sender_addr = try! SealedSenderAddress( + e164: "+14151111111", + uuidString: alice_address.name, + deviceId: 1 + ) + let sender_cert = try! SenderCertificate( + sender: sender_addr, + publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, + expiration: 31337, + signerCertificate: server_cert, + signerKey: server_keys.privateKey + ) let distribution_id = UUID(uuidString: "d1d1d1d1-7000-11eb-b32a-33b8a8a487a6")! - let skdm = try! SenderKeyDistributionMessage(from: alice_address, - distributionId: distribution_id, - store: alice_store, - context: NullContext()) + let skdm = try! SenderKeyDistributionMessage( + from: alice_address, + distributionId: distribution_id, + store: alice_store, + context: NullContext() + ) let skdm_bits = skdm.serialize() @@ -303,47 +347,61 @@ class SessionTests: TestCaseBase { XCTAssertEqual(skdm.signatureKey, skdm_r.signatureKey) XCTAssertEqual(skdm.chainId, skdm_r.chainId) - try! processSenderKeyDistributionMessage(skdm_r, - from: alice_address, - store: bob_store, - context: NullContext()) + try! processSenderKeyDistributionMessage( + skdm_r, + from: alice_address, + store: bob_store, + context: NullContext() + ) - let a_message = try! groupEncrypt([1, 2, 3], - from: alice_address, - distributionId: distribution_id, - store: alice_store, - context: NullContext()) + let a_message = try! groupEncrypt( + [1, 2, 3], + from: alice_address, + distributionId: distribution_id, + store: alice_store, + context: NullContext() + ) - let a_usmc = try! UnidentifiedSenderMessageContent(a_message, - from: sender_cert, - contentHint: .default, - groupId: [42]) + let a_usmc = try! UnidentifiedSenderMessageContent( + a_message, + from: sender_cert, + contentHint: .default, + groupId: [42] + ) - let a_ctext = try! sealedSenderMultiRecipientEncrypt(a_usmc, - for: [bob_address], - identityStore: alice_store, - sessionStore: alice_store, - context: NullContext()) + let a_ctext = try! sealedSenderMultiRecipientEncrypt( + a_usmc, + for: [bob_address], + identityStore: alice_store, + sessionStore: alice_store, + context: NullContext() + ) let b_ctext = try! sealedSenderMultiRecipientMessageForSingleRecipient(a_ctext) - let b_usmc = try! UnidentifiedSenderMessageContent(message: b_ctext, - identityStore: bob_store, - context: NullContext()) + let b_usmc = try! UnidentifiedSenderMessageContent( + message: b_ctext, + identityStore: bob_store, + context: NullContext() + ) XCTAssertEqual(b_usmc.groupId, a_usmc.groupId) - let b_ptext = try! groupDecrypt(b_usmc.contents, - from: alice_address, - store: bob_store, - context: NullContext()) + let b_ptext = try! groupDecrypt( + b_usmc.contents, + from: alice_address, + store: bob_store, + context: NullContext() + ) XCTAssertEqual(b_ptext, [1, 2, 3]) - let another_skdm = try! SenderKeyDistributionMessage(from: alice_address, - distributionId: distribution_id, - store: alice_store, - context: NullContext()) + let another_skdm = try! SenderKeyDistributionMessage( + from: alice_address, + distributionId: distribution_id, + store: alice_store, + context: NullContext() + ) XCTAssertEqual(skdm.chainId, another_skdm.chainId) XCTAssertEqual(1, another_skdm.iteration) } @@ -360,39 +418,51 @@ class SessionTests: TestCaseBase { let trust_root = IdentityKeyPair.generate() let server_keys = IdentityKeyPair.generate() let server_cert = try! ServerCertificate(keyId: 1, publicKey: server_keys.publicKey, trustRoot: trust_root.privateKey) - let sender_addr = try! SealedSenderAddress(e164: "+14151111111", - uuidString: alice_address.name, - deviceId: 1) - let sender_cert = try! SenderCertificate(sender: sender_addr, - publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, - expiration: 31337, - signerCertificate: server_cert, - signerKey: server_keys.privateKey) + let sender_addr = try! SealedSenderAddress( + e164: "+14151111111", + uuidString: alice_address.name, + deviceId: 1 + ) + let sender_cert = try! SenderCertificate( + sender: sender_addr, + publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, + expiration: 31337, + signerCertificate: server_cert, + signerKey: server_keys.privateKey + ) let distribution_id = UUID(uuidString: "d1d1d1d1-7000-11eb-b32a-33b8a8a487a6")! - _ = try! SenderKeyDistributionMessage(from: alice_address, - distributionId: distribution_id, - store: alice_store, - context: NullContext()) + _ = try! SenderKeyDistributionMessage( + from: alice_address, + distributionId: distribution_id, + store: alice_store, + context: NullContext() + ) - let a_message = try! groupEncrypt([1, 2, 3], - from: alice_address, - distributionId: distribution_id, - store: alice_store, - context: NullContext()) + let a_message = try! groupEncrypt( + [1, 2, 3], + from: alice_address, + distributionId: distribution_id, + store: alice_store, + context: NullContext() + ) - let a_usmc = try! UnidentifiedSenderMessageContent(a_message, - from: sender_cert, - contentHint: .default, - groupId: [42]) + let a_usmc = try! UnidentifiedSenderMessageContent( + a_message, + from: sender_cert, + contentHint: .default, + groupId: [42] + ) do { - _ = try sealedSenderMultiRecipientEncrypt(a_usmc, - for: [bob_address], - identityStore: alice_store, - sessionStore: alice_store, - context: NullContext()) + _ = try sealedSenderMultiRecipientEncrypt( + a_usmc, + for: [bob_address], + identityStore: alice_store, + sessionStore: alice_store, + context: NullContext() + ) XCTFail("should have thrown") } catch SignalError.invalidRegistrationId(address: let address, message: _) { XCTAssertEqual(address, bob_address) @@ -414,39 +484,51 @@ class SessionTests: TestCaseBase { let trust_root = IdentityKeyPair.generate() let server_keys = IdentityKeyPair.generate() let server_cert = try! ServerCertificate(keyId: 1, publicKey: server_keys.publicKey, trustRoot: trust_root.privateKey) - let sender_addr = try! SealedSenderAddress(e164: "+14151111111", - uuidString: alice_address.name, - deviceId: 1) - let sender_cert = try! SenderCertificate(sender: sender_addr, - publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, - expiration: 31337, - signerCertificate: server_cert, - signerKey: server_keys.privateKey) + let sender_addr = try! SealedSenderAddress( + e164: "+14151111111", + uuidString: alice_address.name, + deviceId: 1 + ) + let sender_cert = try! SenderCertificate( + sender: sender_addr, + publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, + expiration: 31337, + signerCertificate: server_cert, + signerKey: server_keys.privateKey + ) let distribution_id = UUID(uuidString: "d1d1d1d1-7000-11eb-b32a-33b8a8a487a6")! - _ = try! SenderKeyDistributionMessage(from: alice_address, - distributionId: distribution_id, - store: alice_store, - context: NullContext()) + _ = try! SenderKeyDistributionMessage( + from: alice_address, + distributionId: distribution_id, + store: alice_store, + context: NullContext() + ) - let a_message = try! groupEncrypt([1, 2, 3], - from: alice_address, - distributionId: distribution_id, - store: alice_store, - context: NullContext()) + let a_message = try! groupEncrypt( + [1, 2, 3], + from: alice_address, + distributionId: distribution_id, + store: alice_store, + context: NullContext() + ) - let a_usmc = try! UnidentifiedSenderMessageContent(a_message, - from: sender_cert, - contentHint: .default, - groupId: [42]) + let a_usmc = try! UnidentifiedSenderMessageContent( + a_message, + from: sender_cert, + contentHint: .default, + groupId: [42] + ) - let sent_message = Data(try! sealedSenderMultiRecipientEncrypt(a_usmc, - for: [bob_address], - excludedRecipients: [eve_service_id, mallory_service_id], - identityStore: alice_store, - sessionStore: alice_store, - context: NullContext())) + let sent_message = Data(try! sealedSenderMultiRecipientEncrypt( + a_usmc, + for: [bob_address], + excludedRecipients: [eve_service_id, mallory_service_id], + identityStore: alice_store, + sessionStore: alice_store, + context: NullContext() + )) // Clients can't directly parse arbitrary SSv2 SentMessages, so just check that it contains // the excluded recipient service IDs followed by a device ID of 0. @@ -467,55 +549,72 @@ class SessionTests: TestCaseBase { // Notice the reverse initialization. Bob will send the first message to Alice in this example. initializeSessionsV3(alice_store: bob_store, bob_store: alice_store, bob_address: alice_address) - let bob_first_message = try signalEncrypt(message: Array("swim camp".utf8), - for: alice_address, - sessionStore: bob_store, - identityStore: bob_store, - context: NullContext()).serialize() - _ = try signalDecryptPreKey(message: PreKeySignalMessage(bytes: bob_first_message), - from: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - preKeyStore: alice_store, - signedPreKeyStore: alice_store, - kyberPreKeyStore: bob_store, - context: NullContext()) + let bob_first_message = try signalEncrypt( + message: Array("swim camp".utf8), + for: alice_address, + sessionStore: bob_store, + identityStore: bob_store, + context: NullContext() + ).serialize() + _ = try signalDecryptPreKey( + message: PreKeySignalMessage(bytes: bob_first_message), + from: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + preKeyStore: alice_store, + signedPreKeyStore: alice_store, + kyberPreKeyStore: bob_store, + context: NullContext() + ) - let bob_message = try signalEncrypt(message: Array("space camp".utf8), - for: alice_address, - sessionStore: bob_store, - identityStore: bob_store, - context: NullContext()) - let error_message = try DecryptionErrorMessage(originalMessageBytes: bob_message.serialize(), - type: bob_message.messageType, - timestamp: 408, - originalSenderDeviceId: bob_address.deviceId) + let bob_message = try signalEncrypt( + message: Array("space camp".utf8), + for: alice_address, + sessionStore: bob_store, + identityStore: bob_store, + context: NullContext() + ) + let error_message = try DecryptionErrorMessage( + originalMessageBytes: bob_message.serialize(), + type: bob_message.messageType, + timestamp: 408, + originalSenderDeviceId: bob_address.deviceId + ) let trust_root = IdentityKeyPair.generate() let server_keys = IdentityKeyPair.generate() let server_cert = try! ServerCertificate(keyId: 1, publicKey: server_keys.publicKey, trustRoot: trust_root.privateKey) - let sender_addr = try! SealedSenderAddress(e164: "+14151111111", - uuidString: alice_address.name, - deviceId: 1) - let sender_cert = try! SenderCertificate(sender: sender_addr, - publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, - expiration: 31337, - signerCertificate: server_cert, - signerKey: server_keys.privateKey) + let sender_addr = try! SealedSenderAddress( + e164: "+14151111111", + uuidString: alice_address.name, + deviceId: 1 + ) + let sender_cert = try! SenderCertificate( + sender: sender_addr, + publicKey: alice_store.identityKeyPair(context: NullContext()).publicKey, + expiration: 31337, + signerCertificate: server_cert, + signerKey: server_keys.privateKey + ) let error_message_usmc = try UnidentifiedSenderMessageContent( CiphertextMessage(PlaintextContent(error_message)), from: sender_cert, contentHint: .implicit, - groupId: []) - let ciphertext = try sealedSenderEncrypt(error_message_usmc, - for: bob_address, - identityStore: alice_store, - context: NullContext()) + groupId: [] + ) + let ciphertext = try sealedSenderEncrypt( + error_message_usmc, + for: bob_address, + identityStore: alice_store, + context: NullContext() + ) - let bob_usmc = try UnidentifiedSenderMessageContent(message: ciphertext, - identityStore: bob_store, - context: NullContext()) + let bob_usmc = try UnidentifiedSenderMessageContent( + message: ciphertext, + identityStore: bob_store, + context: NullContext() + ) XCTAssertEqual(bob_usmc.messageType, .plaintext) let bob_content = try PlaintextContent(bytes: bob_usmc.contents) let bob_error_message = try DecryptionErrorMessage.extractFromSerializedContent(bob_content.body) @@ -543,30 +642,38 @@ private func initializeSessionsV3( let prekey_id: UInt32 = 4570 let signed_prekey_id: UInt32 = 3006 - let bob_bundle = try! PreKeyBundle(registrationId: bob_store.localRegistrationId(context: NullContext()), - deviceId: 9, - prekeyId: prekey_id, - prekey: bob_pre_key.publicKey, - signedPrekeyId: signed_prekey_id, - signedPrekey: bob_signed_pre_key.publicKey, - signedPrekeySignature: bob_signed_pre_key_signature, - identity: bob_identity_key) + let bob_bundle = try! PreKeyBundle( + registrationId: bob_store.localRegistrationId(context: NullContext()), + deviceId: 9, + prekeyId: prekey_id, + prekey: bob_pre_key.publicKey, + signedPrekeyId: signed_prekey_id, + signedPrekey: bob_signed_pre_key.publicKey, + signedPrekeySignature: bob_signed_pre_key_signature, + identity: bob_identity_key + ) // Alice processes the bundle: - try! processPreKeyBundle(bob_bundle, - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - context: NullContext()) + try! processPreKeyBundle( + bob_bundle, + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + context: NullContext() + ) XCTAssertEqual(try! alice_store.loadSession(for: bob_address, context: NullContext())?.hasCurrentState, true) - XCTAssertEqual(try! alice_store.loadSession(for: bob_address, context: NullContext())?.remoteRegistrationId(), - try! bob_store.localRegistrationId(context: NullContext())) + XCTAssertEqual( + try! alice_store.loadSession(for: bob_address, context: NullContext())?.remoteRegistrationId(), + try! bob_store.localRegistrationId(context: NullContext()) + ) // Bob does the same: - try! bob_store.storePreKey(PreKeyRecord(id: prekey_id, privateKey: bob_pre_key), - id: prekey_id, - context: NullContext()) + try! bob_store.storePreKey( + PreKeyRecord(id: prekey_id, privateKey: bob_pre_key), + id: prekey_id, + context: NullContext() + ) try! bob_store.storeSignedPreKey( SignedPreKeyRecord( @@ -576,7 +683,8 @@ private func initializeSessionsV3( signature: bob_signed_pre_key_signature ), id: signed_prekey_id, - context: NullContext()) + context: NullContext() + ) } private func initializeSessionsV4( @@ -600,32 +708,40 @@ private func initializeSessionsV4( let signed_prekey_id: UInt32 = 3006 let kyber_pre_key_id: UInt32 = 8888 - let bob_bundle = try! PreKeyBundle(registrationId: bob_store.localRegistrationId(context: NullContext()), - deviceId: 9, - prekeyId: prekey_id, - prekey: bob_pre_key.publicKey, - signedPrekeyId: signed_prekey_id, - signedPrekey: bob_signed_pre_key.publicKey, - signedPrekeySignature: bob_signed_pre_key_signature, - identity: bob_identity_key, - kyberPrekeyId: kyber_pre_key_id, - kyberPrekey: bob_kyber_pre_key.publicKey, - kyberPrekeySignature: bob_kyber_pre_key_signature) + let bob_bundle = try! PreKeyBundle( + registrationId: bob_store.localRegistrationId(context: NullContext()), + deviceId: 9, + prekeyId: prekey_id, + prekey: bob_pre_key.publicKey, + signedPrekeyId: signed_prekey_id, + signedPrekey: bob_signed_pre_key.publicKey, + signedPrekeySignature: bob_signed_pre_key_signature, + identity: bob_identity_key, + kyberPrekeyId: kyber_pre_key_id, + kyberPrekey: bob_kyber_pre_key.publicKey, + kyberPrekeySignature: bob_kyber_pre_key_signature + ) // Alice processes the bundle: - try! processPreKeyBundle(bob_bundle, - for: bob_address, - sessionStore: alice_store, - identityStore: alice_store, - context: NullContext()) + try! processPreKeyBundle( + bob_bundle, + for: bob_address, + sessionStore: alice_store, + identityStore: alice_store, + context: NullContext() + ) XCTAssertEqual(try! alice_store.loadSession(for: bob_address, context: NullContext())?.hasCurrentState, true) - XCTAssertEqual(try! alice_store.loadSession(for: bob_address, context: NullContext())?.remoteRegistrationId(), - try! bob_store.localRegistrationId(context: NullContext())) + XCTAssertEqual( + try! alice_store.loadSession(for: bob_address, context: NullContext())?.remoteRegistrationId(), + try! bob_store.localRegistrationId(context: NullContext()) + ) // Bob does the same: - try! bob_store.storePreKey(PreKeyRecord(id: prekey_id, privateKey: bob_pre_key), - id: prekey_id, - context: NullContext()) + try! bob_store.storePreKey( + PreKeyRecord(id: prekey_id, privateKey: bob_pre_key), + id: prekey_id, + context: NullContext() + ) try! bob_store.storeSignedPreKey( SignedPreKeyRecord( @@ -635,7 +751,8 @@ private func initializeSessionsV4( signature: bob_signed_pre_key_signature ), id: signed_prekey_id, - context: NullContext()) + context: NullContext() + ) try! bob_store.storeKyberPreKey( KyberPreKeyRecord( id: kyber_pre_key_id, @@ -645,5 +762,5 @@ private func initializeSessionsV4( ), id: kyber_pre_key_id, context: NullContext() - ) + ) } diff --git a/swift/Tests/LibSignalClientTests/SgxTests.swift b/swift/Tests/LibSignalClientTests/SgxTests.swift index 06c4d439..df7b2e24 100644 --- a/swift/Tests/LibSignalClientTests/SgxTests.swift +++ b/swift/Tests/LibSignalClientTests/SgxTests.swift @@ -7,7 +7,6 @@ import LibSignalClient import XCTest class SgxTests: TestCaseBase { - enum ServiceType { case svr2, cds2 } @@ -40,7 +39,7 @@ class SgxTests: TestCaseBase { } func testCreateClient() { - for (serviceType, mrenclave, attestationMessage, currentDate) in testCases { + for (serviceType, mrenclave, attestationMessage, currentDate) in self.testCases { let client = try! SgxTests.build(serviceType: serviceType, mrenclave: mrenclave, attestationMessage: attestationMessage, currentDate: currentDate) let initialMessage = client.initialRequest() XCTAssertEqual(48, initialMessage.count, String(describing: serviceType)) @@ -49,48 +48,54 @@ class SgxTests: TestCaseBase { func testCreateClientFailsWithInvalidMrenclave() { let invalidMrenclave = Data(repeating: 0, count: 0) - for (serviceType, _, attestationMessage, currentDate) in testCases { + for (serviceType, _, attestationMessage, currentDate) in self.testCases { XCTAssertThrowsError( try SgxTests.build( serviceType: serviceType, mrenclave: invalidMrenclave, attestationMessage: attestationMessage, - currentDate: currentDate), String(describing: serviceType)) + currentDate: currentDate + ), String(describing: serviceType) + ) } } func testCreateClientFailsWithInvalidMessage() { let invalidMessage = Data(repeating: 0, count: 0) - for (serviceType, mrenclave, _, currentDate) in testCases { + for (serviceType, mrenclave, _, currentDate) in self.testCases { XCTAssertThrowsError( try SgxTests.build( serviceType: serviceType, mrenclave: mrenclave, attestationMessage: invalidMessage, - currentDate: currentDate), String(describing: serviceType)) + currentDate: currentDate + ), String(describing: serviceType) + ) } } func testEstablishedSendFailsPriorToEstablishment() { let plaintext: [UInt8] = [0x01, 0x02, 0x03] - for (serviceType, mrenclave, attestationMsg, currentDate) in testCases { + for (serviceType, mrenclave, attestationMsg, currentDate) in self.testCases { let client = try! SgxTests.build( serviceType: serviceType, mrenclave: mrenclave, attestationMessage: attestationMsg, - currentDate: currentDate) + currentDate: currentDate + ) XCTAssertThrowsError(try client.establishedSend(plaintext), String(describing: serviceType)) } } func testEstablishedRecvFailsPriorToEstablishment() { let receivedCiphertext: [UInt8] = [0x01, 0x02, 0x03] - for (serviceType, mrenclave, attestationMsg, currentDate) in testCases { + for (serviceType, mrenclave, attestationMsg, currentDate) in self.testCases { let client = try! SgxTests.build( serviceType: serviceType, mrenclave: mrenclave, attestationMessage: attestationMsg, - currentDate: currentDate) + currentDate: currentDate + ) XCTAssertThrowsError(try client.establishedRecv(receivedCiphertext), String(describing: serviceType)) } } diff --git a/swift/Tests/LibSignalClientTests/TestCaseBase.swift b/swift/Tests/LibSignalClientTests/TestCaseBase.swift index 47017043..5c9c9601 100644 --- a/swift/Tests/LibSignalClientTests/TestCaseBase.swift +++ b/swift/Tests/LibSignalClientTests/TestCaseBase.swift @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest import SignalFfi +import XCTest #if canImport(SignalCoreKit) import SignalCoreKit @@ -31,6 +31,6 @@ class TestCaseBase: XCTestCase { }() override class func setUp() { - precondition(loggingInitialized) + precondition(self.loggingInitialized) } } diff --git a/swift/Tests/LibSignalClientTests/TestUtils.swift b/swift/Tests/LibSignalClientTests/TestUtils.swift index ad2cd918..2c29d609 100644 --- a/swift/Tests/LibSignalClientTests/TestUtils.swift +++ b/swift/Tests/LibSignalClientTests/TestUtils.swift @@ -10,6 +10,7 @@ class BadStore: InMemorySignalProtocolStore { enum Error: Swift.Error { case badness } + override func loadPreKey(id: UInt32, context: StoreContext) throws -> PreKeyRecord { throw Error.badness } diff --git a/swift/Tests/LibSignalClientTests/UsernameTests.swift b/swift/Tests/LibSignalClientTests/UsernameTests.swift index 1cc0f292..fe8f0c0f 100644 --- a/swift/Tests/LibSignalClientTests/UsernameTests.swift +++ b/swift/Tests/LibSignalClientTests/UsernameTests.swift @@ -3,11 +3,10 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest import LibSignalClient +import XCTest class UsernameTests: TestCaseBase { - func testTheBasicFlow() throws { let candidates = try Username.candidates(from: "hel10") let username = candidates[0] @@ -48,10 +47,11 @@ class UsernameTests: TestCaseBase { let username = try Username("he110.42") XCTAssertEqual(32, username.hash.count) XCTAssertEqual([ - 0xf6, 0x3f, 0x05, 0x21, 0xeb, 0x3a, 0xdf, 0xe1, - 0xd9, 0x36, 0xf4, 0xb6, 0x26, 0xb8, 0x95, 0x58, - 0x48, 0x35, 0x07, 0xfb, 0xdb, 0x83, 0x8f, 0xc5, - 0x54, 0xaf, 0x05, 0x91, 0x11, 0xcf, 0x32, 0x2e], username.hash) + 0xF6, 0x3F, 0x05, 0x21, 0xEB, 0x3A, 0xDF, 0xE1, + 0xD9, 0x36, 0xF4, 0xB6, 0x26, 0xB8, 0x95, 0x58, + 0x48, 0x35, 0x07, 0xFB, 0xDB, 0x83, 0x8F, 0xC5, + 0x54, 0xAF, 0x05, 0x91, 0x11, 0xCF, 0x32, 0x2E, + ], username.hash) } func testInvalidHash() throws { @@ -84,10 +84,14 @@ class UsernameTests: TestCaseBase { XCTAssertEqual("jimio.01", jimio01.value) try Username.verify(proof: jimio01.generateProof(), forHash: jimio01.hash) - XCTAssertEqual("jimio.\(UInt64.max)", - try Username(nickname: "jimio", - discriminator: "\(UInt64.max)", - withValidLengthWithin: 3...32).value) + XCTAssertEqual( + "jimio.\(UInt64.max)", + try Username( + nickname: "jimio", + discriminator: "\(UInt64.max)", + withValidLengthWithin: 3...32 + ).value + ) } func testCorrectErrorsForInvalidUsernamesFromParts() throws { diff --git a/swift/Tests/LibSignalClientTests/ZKGroupTests.swift b/swift/Tests/LibSignalClientTests/ZKGroupTests.swift index a63f4526..4d62500c 100644 --- a/swift/Tests/LibSignalClientTests/ZKGroupTests.swift +++ b/swift/Tests/LibSignalClientTests/ZKGroupTests.swift @@ -3,582 +3,587 @@ // SPDX-License-Identifier: AGPL-3.0-only // -import XCTest import LibSignalClient +import XCTest private let SECONDS_PER_DAY: UInt64 = 24 * 60 * 60 class ZKGroupTests: TestCaseBase { - - let TEST_ARRAY_16: UUID = UUID(uuid: (0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f)) - - let TEST_ARRAY_16_1: UUID = UUID(uuid: (0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73)) - - let TEST_ARRAY_32: Randomness = Randomness((0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f)) - - let TEST_ARRAY_32_1: [UInt8] = [0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, - 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83] - - let TEST_ARRAY_32_2: Randomness = Randomness((0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, - 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, - 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7)) - - let TEST_ARRAY_32_3: Randomness = Randomness(( - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, - 28, 29, 30, 31, 32)) - - let TEST_ARRAY_32_4: Randomness = Randomness(( - 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, - 28, 29, 30, 31, 32, 33)) - - let TEST_ARRAY_32_5: Randomness = Randomness((0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, - 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, - 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22)) - - let authPresentationResult: [UInt8] = [ - 0x01, 0x32, 0x2f, 0x91, 0x00, 0xde, 0x07, 0x34, 0x55, 0x0a, 0x81, 0xdc, 0x81, 0x72, 0x4a, 0x81, - 0xdb, 0xd3, 0xb1, 0xb4, 0x3d, 0xbc, 0x1d, 0x55, 0x2d, 0x53, 0x45, 0x59, 0x11, 0xc2, 0x77, 0x2f, - 0x34, 0xa6, 0x35, 0x6c, 0xa1, 0x7c, 0x6d, 0x34, 0xd8, 0x58, 0x39, 0x14, 0x56, 0xaf, 0x55, 0xd0, - 0xef, 0x84, 0x1f, 0xbe, 0x1f, 0xa8, 0xc4, 0xee, 0x81, 0x0f, 0x21, 0xe0, 0xbb, 0x9f, 0x4a, 0xce, - 0x4c, 0x5c, 0x48, 0xc7, 0x2e, 0xbb, 0xeb, 0x2c, 0xcd, 0xa5, 0xf7, 0xaa, 0x49, 0xae, 0xe6, 0xbc, - 0x00, 0x51, 0xcd, 0xde, 0x16, 0x6e, 0x0f, 0x8c, 0x5f, 0x1f, 0xeb, 0xd5, 0x3a, 0x44, 0x37, 0xc5, - 0x70, 0xee, 0x1a, 0xa2, 0x23, 0xf5, 0xeb, 0x93, 0x7d, 0xb9, 0x8f, 0x34, 0xe3, 0x65, 0x3d, 0x85, - 0xec, 0x16, 0x3f, 0x39, 0x84, 0x72, 0x22, 0xa2, 0xde, 0xc4, 0x23, 0x5e, 0xa4, 0x1c, 0x47, 0xbb, - 0x62, 0x02, 0x8a, 0xae, 0x30, 0x94, 0x58, 0x57, 0xee, 0x77, 0x66, 0x30, 0x79, 0xbc, 0xc4, 0x92, - 0x3d, 0x14, 0xa4, 0x3a, 0xd4, 0xf6, 0xbc, 0x33, 0x71, 0x50, 0x46, 0xf7, 0xbd, 0xe5, 0x27, 0x15, - 0x37, 0x5c, 0xa9, 0xf8, 0x9b, 0xe0, 0xe6, 0x30, 0xd4, 0xbd, 0xaa, 0x21, 0x11, 0x56, 0xd0, 0x30, - 0x67, 0x23, 0xf5, 0x43, 0xb0, 0x6f, 0x5e, 0x99, 0x84, 0x47, 0xb9, 0x62, 0xc8, 0xe9, 0x72, 0x9b, - 0x4c, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0xd0, 0xea, 0xe8, 0xe4, 0x31, 0x1a, - 0x6a, 0xe3, 0xd2, 0x97, 0x0e, 0xf1, 0x98, 0xc3, 0x98, 0x11, 0x04, 0x62, 0xbe, 0x47, 0xdd, 0x2f, - 0x26, 0xe6, 0x55, 0x92, 0x09, 0xef, 0x6c, 0xc2, 0x00, 0x01, 0xa0, 0x5a, 0x0b, 0x31, 0x9a, 0x17, - 0x2d, 0xbe, 0xb2, 0x29, 0x3c, 0xc1, 0xe0, 0xe1, 0x91, 0xce, 0xfb, 0x23, 0xe2, 0x4c, 0xf0, 0xd6, - 0xb4, 0xb5, 0x37, 0x3a, 0x30, 0x04, 0x4b, 0xe1, 0x0c, 0xb0, 0x33, 0x67, 0x4d, 0x63, 0x1e, 0x17, - 0xdf, 0xce, 0x09, 0x39, 0x8f, 0x23, 0x4e, 0x9d, 0x62, 0xe1, 0x18, 0xa6, 0x07, 0x7c, 0xae, 0xa0, - 0xef, 0x8b, 0xf6, 0x7d, 0x7d, 0x72, 0x3d, 0xb7, 0x0f, 0xec, 0xf2, 0x09, 0x8f, 0xa0, 0x41, 0x31, - 0x7b, 0x7b, 0xe9, 0xfd, 0xbb, 0x68, 0xb0, 0xf2, 0x5f, 0x5c, 0x47, 0x9d, 0x68, 0xbd, 0x91, 0x7f, - 0xc6, 0xf1, 0x87, 0xc5, 0xbf, 0x7a, 0x58, 0x91, 0x02, 0x31, 0x92, 0x1f, 0xc4, 0x35, 0x65, 0x23, - 0x24, 0x66, 0x32, 0x5c, 0x03, 0x92, 0x12, 0x36, 0x2b, 0x6d, 0x12, 0x03, 0xcc, 0xae, 0xdf, 0x83, - 0x1d, 0xc7, 0xf9, 0x06, 0x0d, 0xca, 0xaf, 0xfa, 0x02, 0x62, 0x40, 0x42, 0x17, 0x1f, 0x5f, 0x0e, - 0x78, 0x0b, 0x9f, 0x74, 0xcf, 0xa8, 0x8a, 0x14, 0x7f, 0x3f, 0x1c, 0x08, 0x2f, 0x9c, 0xa8, 0x63, - 0x8a, 0xf1, 0x78, 0x8e, 0x78, 0x99, 0xcb, 0xae, 0x0c, 0x76, 0x5d, 0xe9, 0xdf, 0x4c, 0xfa, 0x54, - 0x87, 0xf3, 0x60, 0xe2, 0x9e, 0x99, 0x34, 0x3e, 0x91, 0x81, 0x1b, 0xae, 0xc3, 0x31, 0xc4, 0x68, - 0x09, 0x85, 0xe6, 0x08, 0xca, 0x5d, 0x40, 0x8e, 0x21, 0x72, 0x5c, 0x6a, 0xa1, 0xb6, 0x1d, 0x5a, - 0x8b, 0x48, 0xd7, 0x5f, 0x4a, 0xaa, 0x9a, 0x3c, 0xbe, 0x88, 0xd3, 0xe0, 0xf1, 0xa5, 0x43, 0x19, - 0x08, 0x1f, 0x77, 0xc7, 0x2c, 0x8f, 0x52, 0x54, 0x74, 0x40, 0xe2, 0x01, 0x00] - - let serverSignatureResult: [UInt8] = [ 0x87, 0xd3, 0x54, 0x56, 0x4d, 0x35, - 0xef, 0x91, 0xed, 0xba, 0x85, 0x1e, 0x08, 0x15, 0x61, 0x2e, 0x86, 0x4c, 0x22, - 0x7a, 0x04, 0x71, 0xd5, 0x0c, 0x27, 0x06, 0x98, 0x60, 0x44, 0x06, 0xd0, 0x03, - 0xa5, 0x54, 0x73, 0xf5, 0x76, 0xcf, 0x24, 0x1f, 0xc6, 0xb4, 0x1c, 0x6b, 0x16, - 0xe5, 0xe6, 0x3b, 0x33, 0x3c, 0x02, 0xfe, 0x4a, 0x33, 0x85, 0x80, 0x22, 0xfd, - 0xd7, 0xa4, 0xab, 0x36, 0x7b, 0x06] - - func testAuthIntegration() throws { - let aci: Aci = Aci(fromUUID: TEST_ARRAY_16) - let redemptionTime: UInt32 = 123456 - - // Generate keys (client's are per-group, server's are not) - // --- - - // SERVER - let serverSecretParams = try ServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = try serverSecretParams.getPublicParams() - let serverZkAuth = ServerZkAuthOperations(serverSecretParams: serverSecretParams) - - // CLIENT - let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) - let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) - - XCTAssertEqual((try groupSecretParams.getMasterKey()).serialize(), masterKey.serialize()) - - let groupPublicParams = try groupSecretParams.getPublicParams() - - // SERVER - // Issue credential - let authCredentialResponse = try serverZkAuth.issueAuthCredential(randomness: TEST_ARRAY_32_2, aci: aci, redemptionTime: redemptionTime) - - // CLIENT - // Receive credential - let clientZkAuthCipher = ClientZkAuthOperations(serverPublicParams: serverPublicParams) - let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) - let authCredential = try clientZkAuthCipher.receiveAuthCredential(aci: aci, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse) - - // Create and decrypt user entry - let uuidCiphertext = try clientZkGroupCipher.encrypt(aci) - let plaintext = try clientZkGroupCipher.decrypt(uuidCiphertext) - XCTAssertEqual(aci, plaintext) - - // Create presentation - let presentation = try clientZkAuthCipher.createAuthCredentialPresentation(randomness: TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, authCredential: authCredential) - - // Verify presentation - let uuidCiphertextRecv = try presentation.getUuidCiphertext() - XCTAssertEqual(uuidCiphertext.serialize(), uuidCiphertextRecv.serialize()) - XCTAssertNil(try presentation.getPniCiphertext()) - XCTAssertEqual(try presentation.getRedemptionTime(), - Date(timeIntervalSince1970: TimeInterval(redemptionTime) * TimeInterval(SECONDS_PER_DAY))) - try serverZkAuth.verifyAuthCredentialPresentation(groupPublicParams: groupPublicParams, authCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(redemptionTime) * TimeInterval(SECONDS_PER_DAY))) - - XCTAssertEqual(presentation.serialize(), authPresentationResult) - } - - func testAuthWithPniIntegration() throws { - let aci: Aci = Aci(fromUUID: TEST_ARRAY_16) - let pni: Pni = Pni(fromUUID: TEST_ARRAY_16_1) - let redemptionTime: UInt64 = 123456 * SECONDS_PER_DAY - - // Generate keys (client's are per-group, server's are not) - // --- - - // SERVER - let serverSecretParams = try ServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = try serverSecretParams.getPublicParams() - let serverZkAuth = ServerZkAuthOperations(serverSecretParams: serverSecretParams) - - // CLIENT - let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) - let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) - - XCTAssertEqual((try groupSecretParams.getMasterKey()).serialize(), masterKey.serialize()) - - let groupPublicParams = try groupSecretParams.getPublicParams() - - // SERVER - // Issue credential - let authCredentialResponse = try serverZkAuth.issueAuthCredentialWithPniAsServiceId(randomness: TEST_ARRAY_32_2, aci: aci, pni: pni, redemptionTime: redemptionTime) - - // CLIENT - // Receive credential - let clientZkAuthCipher = ClientZkAuthOperations(serverPublicParams: serverPublicParams) - let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) - let authCredential = try clientZkAuthCipher.receiveAuthCredentialWithPniAsServiceId(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse) - XCTAssertThrowsError(try clientZkAuthCipher.receiveAuthCredentialWithPniAsAci(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse)) - - // Create and decrypt user entry - let aciCiphertext = try clientZkGroupCipher.encrypt(aci) - let aciPlaintext = try clientZkGroupCipher.decrypt(aciCiphertext) - XCTAssertEqual(aci, aciPlaintext) - let pniCiphertext = try clientZkGroupCipher.encrypt(pni) - let pniPlaintext = try clientZkGroupCipher.decrypt(pniCiphertext) - XCTAssertEqual(pni, pniPlaintext) - - // Create presentation - let presentation = try clientZkAuthCipher.createAuthCredentialPresentation(randomness: TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, authCredential: authCredential) - - // Verify presentation - let uuidCiphertextRecv = try presentation.getUuidCiphertext() - XCTAssertEqual(aciCiphertext.serialize(), uuidCiphertextRecv.serialize()) - XCTAssertEqual(pniCiphertext.serialize(), try presentation.getPniCiphertext()?.serialize()) - XCTAssertEqual(try presentation.getRedemptionTime(), Date(timeIntervalSince1970: TimeInterval(redemptionTime))) - try serverZkAuth.verifyAuthCredentialPresentation(groupPublicParams: groupPublicParams, authCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(redemptionTime))) - } - - func testAuthWithPniAsAciIntegration() throws { - let aci: Aci = Aci(fromUUID: TEST_ARRAY_16) - let pni: Pni = Pni(fromUUID: TEST_ARRAY_16_1) - let redemptionTime: UInt64 = 123456 * SECONDS_PER_DAY - - // Generate keys (client's are per-group, server's are not) - // --- - - // SERVER - let serverSecretParams = try ServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = try serverSecretParams.getPublicParams() - let serverZkAuth = ServerZkAuthOperations(serverSecretParams: serverSecretParams) - - // CLIENT - let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) - let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) - - XCTAssertEqual((try groupSecretParams.getMasterKey()).serialize(), masterKey.serialize()) - - let groupPublicParams = try groupSecretParams.getPublicParams() - - // SERVER - // Issue credential - let authCredentialResponse = try serverZkAuth.issueAuthCredentialWithPniAsAci(randomness: TEST_ARRAY_32_2, aci: aci, pni: pni, redemptionTime: redemptionTime) - - // CLIENT - // Receive credential - let clientZkAuthCipher = ClientZkAuthOperations(serverPublicParams: serverPublicParams) - let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) - let authCredential = try clientZkAuthCipher.receiveAuthCredentialWithPniAsAci(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse) - XCTAssertThrowsError(try clientZkAuthCipher.receiveAuthCredentialWithPniAsServiceId(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse)) - - // Create and decrypt user entry - let aciCiphertext = try clientZkGroupCipher.encrypt(aci) - let aciPlaintext = try clientZkGroupCipher.decrypt(aciCiphertext) - XCTAssertEqual(aci, aciPlaintext) - let pniAsAci = Aci(fromUUID: pni.rawUUID) - let pniCiphertext = try clientZkGroupCipher.encrypt(pniAsAci) - let pniPlaintext = try clientZkGroupCipher.decrypt(pniCiphertext) - XCTAssertEqual(pniAsAci, pniPlaintext) - - // Create presentation - let presentation = try clientZkAuthCipher.createAuthCredentialPresentation(randomness: TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, authCredential: authCredential) - - // Verify presentation - let uuidCiphertextRecv = try presentation.getUuidCiphertext() - XCTAssertEqual(aciCiphertext.serialize(), uuidCiphertextRecv.serialize()) - XCTAssertEqual(pniCiphertext.serialize(), try presentation.getPniCiphertext()?.serialize()) - XCTAssertEqual(try presentation.getRedemptionTime(), Date(timeIntervalSince1970: TimeInterval(redemptionTime))) - try serverZkAuth.verifyAuthCredentialPresentation(groupPublicParams: groupPublicParams, authCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(redemptionTime))) - } - - func testExpiringProfileKeyIntegration() throws { - let userId: Aci = Aci(fromUUID: TEST_ARRAY_16) - // Generate keys (client's are per-group, server's are not) - // --- - - // SERVER - let serverSecretParams = try ServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = try serverSecretParams.getPublicParams() - let serverZkProfile = ServerZkProfileOperations(serverSecretParams: serverSecretParams) - - // CLIENT - let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) - let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) - - XCTAssertEqual(try groupSecretParams.getMasterKey().serialize(), masterKey.serialize()) - - let groupPublicParams = try groupSecretParams.getPublicParams() - let clientZkProfileCipher = ClientZkProfileOperations(serverPublicParams: serverPublicParams) - - let profileKey = try ProfileKey(contents: TEST_ARRAY_32_1) - let profileKeyCommitment = try profileKey.getCommitment(userId: userId) - - // Create context and request - let context = try clientZkProfileCipher.createProfileKeyCredentialRequestContext(randomness: TEST_ARRAY_32_3, userId: userId, profileKey: profileKey) - let request = try context.getRequest() - - // SERVER - let now = UInt64(Date().timeIntervalSince1970) - let startOfDay = now - (now % SECONDS_PER_DAY) - let expiration = startOfDay + 5 * SECONDS_PER_DAY - let response = try serverZkProfile.issueExpiringProfileKeyCredential(randomness: TEST_ARRAY_32_4, profileKeyCredentialRequest: request, userId: userId, profileKeyCommitment: profileKeyCommitment, expiration: expiration) - - // CLIENT - // Gets stored profile credential - let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) - let profileKeyCredential = try clientZkProfileCipher.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext: context, profileKeyCredentialResponse: response) - - // Create encrypted UID and profile key - let uuidCiphertext = try clientZkGroupCipher.encrypt(userId) - let plaintext = try clientZkGroupCipher.decrypt(uuidCiphertext) - XCTAssertEqual(plaintext, userId) - - let profileKeyCiphertext = try clientZkGroupCipher.encryptProfileKey(profileKey: profileKey, userId: userId) - let decryptedProfileKey = try clientZkGroupCipher.decryptProfileKey(profileKeyCiphertext: profileKeyCiphertext, userId: userId) - XCTAssertEqual(profileKey.serialize(), decryptedProfileKey.serialize()) - - XCTAssertEqual(Date(timeIntervalSince1970: TimeInterval(expiration)), profileKeyCredential.expirationTime) - - let presentation = try clientZkProfileCipher.createProfileKeyCredentialPresentation(randomness: TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, profileKeyCredential: profileKeyCredential) - - // Verify presentation - try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation) - try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(expiration - 5))) - XCTAssertThrowsError(try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(expiration)))) - XCTAssertThrowsError(try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(expiration + 5)))) - - let uuidCiphertextRecv = try presentation.getUuidCiphertext() - XCTAssertEqual(uuidCiphertext.serialize(), uuidCiphertextRecv.serialize()) - } - - func testServerSignatures() throws { - let serverSecretParams = try ServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = try serverSecretParams.getPublicParams() - - let message = TEST_ARRAY_32_1 - - let signature = try serverSecretParams.sign(randomness: TEST_ARRAY_32_2, message: message) - try serverPublicParams.verifySignature(message: message, notarySignature: signature) - - XCTAssertEqual(signature.serialize(), serverSignatureResult) - - var alteredMessage = message - alteredMessage[0] ^= 1 - do { - try serverPublicParams.verifySignature(message: alteredMessage, notarySignature: signature) - XCTAssert(false) - } catch SignalError.verificationFailed(_) { - // good - } - } - - func testInvalidSerialized() throws { - let ckp: [UInt8] = Array(repeating: 255, count: 289) - do { - _ = try GroupSecretParams(contents: ckp) - XCTFail("should have thrown") - } catch SignalError.invalidType(_) { - // good - } - } - - func testWrongSizeSerialized() throws { - let ckp: [UInt8] = Array(repeating: 255, count: 5) - do { - _ = try GroupSecretParams(contents: ckp) - XCTFail("should have thrown") - } catch SignalError.invalidType(_) { - // good - } - } - - func testBlobEncryption() throws { - let groupSecretParams = try GroupSecretParams.generate() - let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) - - let plaintext: [UInt8] = [0, 1, 2, 3, 4] - let ciphertext = try clientZkGroupCipher.encryptBlob(plaintext: plaintext) - let plaintext2 = try clientZkGroupCipher.decryptBlob(blobCiphertext: ciphertext) - - XCTAssertEqual(plaintext, plaintext2) - } - - func testBlobEncryptionWithRandom() throws { - let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) - let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) - let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) - - let plaintext: [UInt8] = [ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19] - - let ciphertext: [UInt8] = [ 0xdd, 0x4d, 0x03, 0x2c, 0xa9, 0xbb, 0x75, 0xa4, - 0xa7, 0x85, 0x41, 0xb9, 0x0c, 0xb4, 0xe9, 0x57, 0x43, 0xf3, 0xb0, 0xda, - 0xbf, 0xc7, 0xe1, 0x11, 0x01, 0xb0, 0x98, 0xe3, 0x4f, 0x6c, 0xf6, 0x51, - 0x39, 0x40, 0xa0, 0x4c, 0x1f, 0x20, 0xa3, 0x02, 0x69, 0x2a, 0xfd, 0xc7, - 0x08, 0x7f, 0x10, 0x19, 0x60, 0x00] - - let ciphertext257: [UInt8] = [ 0x5c, 0xb5, 0xb7, 0xbf, 0xf0, 0x6e, 0x85, 0xd9, - 0x29, 0xf3, 0x51, 0x1f, 0xd1, 0x94, 0xe6, 0x38, 0xcf, 0x32, 0xa4, 0x76, - 0x63, 0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 0xe2, 0xc4, 0xad, 0xe3, 0xde, 0xbe, 0x37, 0x92, 0xd7, 0x36, 0xc0, - 0x45, 0x7b, 0xc3, 0x52, 0xaf, 0xb8, 0xb6, 0xca, 0xa4, 0x8a, 0x5b, 0x92, - 0xc1, 0xec, 0x05, 0xba, 0x80, 0x8b, 0xa8, 0xf9, 0x4c, 0x65, 0x72, 0xeb, - 0xbf, 0x29, 0x81, 0x89, 0x12, 0x34, 0x49, 0x87, 0x57, 0x3d, 0xe4, 0x19, - 0xdb, 0xcc, 0x7f, 0x1e, 0xa0, 0xe4, 0xb2, 0xdd, 0x40, 0x77, 0xb7, 0x6b, - 0x38, 0x18, 0x19, 0x74, 0x7a, 0xc3, 0x32, 0xe4, 0x6f, 0xa2, 0x3a, 0xbf, - 0xc3, 0x33, 0x8e, 0x2f, 0x4b, 0x08, 0x1a, 0x8a, 0x53, 0xcb, 0xa0, 0x98, - 0x8e, 0xef, 0x11, 0x67, 0x64, 0xd9, 0x44, 0xf1, 0xce, 0x3f, 0x20, 0xa3, - 0x02, 0x69, 0x2a, 0xfd, 0xc7, 0x08, 0x7f, 0x10, 0x19, 0x60, 0x00 ] - - let ciphertext2 = try clientZkGroupCipher.encryptBlob(randomness: TEST_ARRAY_32_2, plaintext: plaintext) - let plaintext2 = try clientZkGroupCipher.decryptBlob(blobCiphertext: ciphertext2) - - XCTAssertEqual(plaintext, plaintext2) - XCTAssertEqual(ciphertext, ciphertext2) - - let plaintext257 = try clientZkGroupCipher.decryptBlob(blobCiphertext: ciphertext257) - XCTAssertEqual(plaintext, plaintext257) - } - - func testCreateCallLinkCredential() throws { - let userId = Aci(fromUUID: TEST_ARRAY_16) - - let serverSecretParams = GenericServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = serverSecretParams.getPublicParams() - let clientSecretParams = CallLinkSecretParams.deriveFromRootKey(TEST_ARRAY_32_1) - let clientPublicParams = clientSecretParams.getPublicParams() - - // Client - let roomId = withUnsafeBytes(of: TEST_ARRAY_32_2) { Data($0) } - let context = CreateCallLinkCredentialRequestContext.forRoomId(roomId, randomness: TEST_ARRAY_32_3) - let request = context.getRequest() - - // Server - let now = UInt64(Date().timeIntervalSince1970) - let startOfDay = now - (now % SECONDS_PER_DAY) - let response = request.issueCredential(userId: userId, timestamp: Date(timeIntervalSince1970: TimeInterval(startOfDay)), params: serverSecretParams, randomness: TEST_ARRAY_32_4) - - // Client - let credential = try context.receive(response, userId: userId, params: serverPublicParams) - let presentation = credential.present(roomId: roomId, userId: userId, serverParams: serverPublicParams, callLinkParams: clientSecretParams, randomness: TEST_ARRAY_32_5) - - // Server - try presentation.verify(roomId: roomId, serverParams: serverSecretParams, callLinkParams: clientPublicParams) - try presentation.verify(roomId: roomId, now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY)), serverParams: serverSecretParams, callLinkParams: clientPublicParams) - - XCTAssertThrowsError(try presentation.verify(roomId: roomId, now: Date(timeIntervalSince1970: TimeInterval(startOfDay + 30 * 60 * 60)), serverParams: serverSecretParams, callLinkParams: clientPublicParams)) - } - - func testCallLinkAuthCredential() throws { - let userId = Aci(fromUUID: TEST_ARRAY_16) - - let serverSecretParams = GenericServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = serverSecretParams.getPublicParams() - let clientSecretParams = CallLinkSecretParams.deriveFromRootKey(TEST_ARRAY_32_1) - let clientPublicParams = clientSecretParams.getPublicParams() - - // Server - let now = UInt64(Date().timeIntervalSince1970) - let startOfDay = now - (now % SECONDS_PER_DAY) - let redemptionTime = Date(timeIntervalSince1970: TimeInterval(startOfDay)) - let response = CallLinkAuthCredentialResponse.issueCredential(userId: userId, redemptionTime: redemptionTime, params: serverSecretParams, randomness: TEST_ARRAY_32_4) - - // Client - let credential = try response.receive(userId: userId, redemptionTime: redemptionTime, params: serverPublicParams) - let presentation = credential.present(userId: userId, redemptionTime: redemptionTime, serverParams: serverPublicParams, callLinkParams: clientSecretParams, randomness: TEST_ARRAY_32_5) - - // Server - try presentation.verify(serverParams: serverSecretParams, callLinkParams: clientPublicParams) - try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY)), serverParams: serverSecretParams, callLinkParams: clientPublicParams) - - XCTAssertThrowsError(try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + 3 * SECONDS_PER_DAY)), serverParams: serverSecretParams, callLinkParams: clientPublicParams)) - - // Client - XCTAssertEqual(userId, try clientSecretParams.decrypt(presentation.userId)) - } - - func testDeriveProfileKey() throws { - let expectedAccessKey: [UInt8] = [0x5a, 0x72, 0x3a, 0xce, 0xe5, 0x2c, 0x5e, 0xa0, 0x2b, 0x92, 0xa3, 0xa3, 0x60, 0xc0, 0x95, 0x95] - let profileKeyBytes: [UInt8] = Array(repeating: 0x02, count: 32) - - let result = try ProfileKey(contents: profileKeyBytes).deriveAccessKey() - XCTAssertEqual(expectedAccessKey, result) - } - - func testBackupAuthCredentialDeterministic() throws { - let backupKey: [UInt8] = [ - 0xf9, 0xab, 0xbb, 0xff, 0xa7, 0xd4, 0x24, 0x92, - 0x97, 0x65, 0xae, 0xcc, 0x84, 0xb6, 0x04, 0x63, - 0x3c, 0x55, 0xac, 0x1b, 0xce, 0x82, 0xe1, 0xee, - 0x06, 0xb7, 0x9b, 0xc9, 0xa5, 0x62, 0x93, 0x38] - let aci = UUID(uuidString: "e74beed0-e70f-4cfd-abbb-7e3eb333bbac")! - let serializedBackupID: [UInt8] = [0xe3, 0x92, 0x6f, 0x11, 0xdd, 0xd1, 0x43, 0xe6, 0xdd, 0x0f, 0x20, 0xbf, 0xcb, 0x08, 0x34, 0x9e] - let serializedRequestCredential = Data(base64Encoded: "AISCxQa8OsFqphsQPxqtzJk5+jndpE3SJG6bfazQB3994Aersq2yNRgcARBoedBeoEfKIXdty6X7l6+TiPFAqDvojRSO8xaZOpKJOvWSDJIGn6EeMl2jOjx+IQg8d8M0AQ==")! - let receiptLevel: UInt64 = 1 - - let context = BackupAuthCredentialRequestContext.create(backupKey: backupKey, aci: aci) - let request = context.getRequest() - let serverSecretParams = GenericServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = serverSecretParams.getPublicParams() - XCTAssertEqual(request.serialize(), Array(serializedRequestCredential)) - - let now = UInt64(Date().timeIntervalSince1970) - let startOfDay = now - (now % SECONDS_PER_DAY) - let response = request.issueCredential(timestamp: Date(timeIntervalSince1970: TimeInterval(startOfDay)), receiptLevel: receiptLevel, params: serverSecretParams, randomness: TEST_ARRAY_32_2) - let credential = try context.receive(response, params: serverPublicParams, expectedReceiptLevel: receiptLevel) - XCTAssertEqual(credential.backupID, serializedBackupID) - } - - func testBackupAuthCredential() throws { - let receiptLevel: UInt64 = 10 - - let serverSecretParams = GenericServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = serverSecretParams.getPublicParams() - - // Client - let backupKey = TEST_ARRAY_32_1 - let aci = UUID(uuidString: "e74beed0-e70f-4cfd-abbb-7e3eb333bbac")! - let context = BackupAuthCredentialRequestContext.create(backupKey: backupKey, aci: aci) - let request = context.getRequest() - - // Server - let now = UInt64(Date().timeIntervalSince1970) - let startOfDay = now - (now % SECONDS_PER_DAY) - let response = request.issueCredential(timestamp: Date(timeIntervalSince1970: TimeInterval(startOfDay)), receiptLevel: receiptLevel, params: serverSecretParams, randomness: TEST_ARRAY_32_2) - - // Client - let credential = try context.receive(response, params: serverPublicParams, expectedReceiptLevel: receiptLevel) - XCTAssertThrowsError(try context.receive(response, params: serverPublicParams, expectedReceiptLevel: receiptLevel + 1)) - - let presentation = credential.present(serverParams: serverPublicParams, randomness: TEST_ARRAY_32_3) - - // Server - try presentation.verify(serverParams: serverSecretParams) - try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY)), serverParams: serverSecretParams) - - // credential should be expired after 2 days - XCTAssertThrowsError(try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + 1 + SECONDS_PER_DAY * 2)), serverParams: serverSecretParams)) - - // future credential should be invalid - XCTAssertThrowsError(try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay - 1 - SECONDS_PER_DAY)), serverParams: serverSecretParams)) - } - - func testGroupSendCredential() { - let serverSecretParams = try! ServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = try! serverSecretParams.getPublicParams() - - let aliceAci = try! Aci.parseFrom(serviceIdString: "9d0652a3-dcc3-4d11-975f-74d61598733f") - let bobAci = try! Aci.parseFrom(serviceIdString: "6838237d-02f6-4098-b110-698253d15961") - let eveAci = try! Aci.parseFrom(serviceIdString: "3f0f4734-e331-4434-bd4f-6d8f6ea6dcc7") - let malloryAci = try! Aci.parseFrom(serviceIdString: "5d088142-6fd7-4dbd-af00-fdda1b3ce988") - - let masterKey = try! GroupMasterKey(contents: TEST_ARRAY_32_1) - let groupSecretParams = try! GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) - - let aliceCiphertext = try! ClientZkGroupCipher(groupSecretParams: groupSecretParams).encrypt(aliceAci) - let groupCiphertexts = [aliceAci, bobAci, eveAci, malloryAci].map { - try! ClientZkGroupCipher(groupSecretParams: groupSecretParams).encrypt($0) + let TEST_ARRAY_16: UUID = .init(uuid: (0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F)) + + let TEST_ARRAY_16_1: UUID = .init(uuid: (0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73)) + + let TEST_ARRAY_32: Randomness = .init(( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F + )) + + let TEST_ARRAY_32_1: [UInt8] = [ + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, + 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, + ] + + let TEST_ARRAY_32_2: Randomness = .init(( + 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, + 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7 + )) + + let TEST_ARRAY_32_3: Randomness = .init(( + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + 28, 29, 30, 31, 32 + )) + + let TEST_ARRAY_32_4: Randomness = .init(( + 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + 28, 29, 30, 31, 32, 33 + )) + + let TEST_ARRAY_32_5: Randomness = .init(( + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, + 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22 + )) + + let authPresentationResult: [UInt8] = [ + 0x01, 0x32, 0x2F, 0x91, 0x00, 0xDE, 0x07, 0x34, 0x55, 0x0A, 0x81, 0xDC, 0x81, 0x72, 0x4A, 0x81, + 0xDB, 0xD3, 0xB1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, 0x9C, 0xA8, 0x63, + 0x8A, 0xF1, 0x78, 0x8E, 0x78, 0x99, 0xCB, 0xAE, 0x0C, 0x76, 0x5D, 0xE9, 0xDF, 0x4C, 0xFA, 0x54, + 0x87, 0xF3, 0x60, 0xE2, 0x9E, 0x99, 0x34, 0x3E, 0x91, 0x81, 0x1B, 0xAE, 0xC3, 0x31, 0xC4, 0x68, + 0x09, 0x85, 0xE6, 0x08, 0xCA, 0x5D, 0x40, 0x8E, 0x21, 0x72, 0x5C, 0x6A, 0xA1, 0xB6, 0x1D, 0x5A, + 0x8B, 0x48, 0xD7, 0x5F, 0x4A, 0xAA, 0x9A, 0x3C, 0xBE, 0x88, 0xD3, 0xE0, 0xF1, 0xA5, 0x43, 0x19, + 0x08, 0x1F, 0x77, 0xC7, 0x2C, 0x8F, 0x52, 0x54, 0x74, 0x40, 0xE2, 0x01, 0x00, + ] + + let serverSignatureResult: [UInt8] = [ + 0x87, 0xD3, 0x54, 0x56, 0x4D, 0x35, 0xEF, 0x91, 0xED, 0xBA, 0x85, 0x1E, 0x08, 0x15, 0x61, 0x2E, + 0x86, 0x4C, 0x22, 0x7A, 0x04, 0x71, 0xD5, 0x0C, 0x27, 0x06, 0x98, 0x60, 0x44, 0x06, 0xD0, 0x03, + 0xA5, 0x54, 0x73, 0xF5, 0x76, 0xCF, 0x24, 0x1F, 0xC6, 0xB4, 0x1C, 0x6B, 0x16, 0xE5, 0xE6, 0x3B, + 0x33, 0x3C, 0x02, 0xFE, 0x4A, 0x33, 0x85, 0x80, 0x22, 0xFD, 0xD7, 0xA4, 0xAB, 0x36, 0x7B, 0x06, + ] + + func testAuthIntegration() throws { + let aci = Aci(fromUUID: TEST_ARRAY_16) + let redemptionTime: UInt32 = 123_456 + + // Generate keys (client's are per-group, server's are not) + // --- + + // SERVER + let serverSecretParams = try ServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = try serverSecretParams.getPublicParams() + let serverZkAuth = ServerZkAuthOperations(serverSecretParams: serverSecretParams) + + // CLIENT + let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) + let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) + + XCTAssertEqual((try groupSecretParams.getMasterKey()).serialize(), masterKey.serialize()) + + let groupPublicParams = try groupSecretParams.getPublicParams() + + // SERVER + // Issue credential + let authCredentialResponse = try serverZkAuth.issueAuthCredential(randomness: self.TEST_ARRAY_32_2, aci: aci, redemptionTime: redemptionTime) + + // CLIENT + // Receive credential + let clientZkAuthCipher = ClientZkAuthOperations(serverPublicParams: serverPublicParams) + let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) + let authCredential = try clientZkAuthCipher.receiveAuthCredential(aci: aci, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse) + + // Create and decrypt user entry + let uuidCiphertext = try clientZkGroupCipher.encrypt(aci) + let plaintext = try clientZkGroupCipher.decrypt(uuidCiphertext) + XCTAssertEqual(aci, plaintext) + + // Create presentation + let presentation = try clientZkAuthCipher.createAuthCredentialPresentation(randomness: self.TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, authCredential: authCredential) + + // Verify presentation + let uuidCiphertextRecv = try presentation.getUuidCiphertext() + XCTAssertEqual(uuidCiphertext.serialize(), uuidCiphertextRecv.serialize()) + XCTAssertNil(try presentation.getPniCiphertext()) + XCTAssertEqual( + try presentation.getRedemptionTime(), + Date(timeIntervalSince1970: TimeInterval(redemptionTime) * TimeInterval(SECONDS_PER_DAY)) + ) + try serverZkAuth.verifyAuthCredentialPresentation(groupPublicParams: groupPublicParams, authCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(redemptionTime) * TimeInterval(SECONDS_PER_DAY))) + + XCTAssertEqual(presentation.serialize(), self.authPresentationResult) } - // Server - let now = UInt64(Date().timeIntervalSince1970) - let startOfDay = now - (now % SECONDS_PER_DAY) - let response = GroupSendCredentialResponse.issueCredential(groupMembers: groupCiphertexts, requestingMember: aliceCiphertext, params: serverSecretParams, randomness: TEST_ARRAY_32_2) + func testAuthWithPniIntegration() throws { + let aci = Aci(fromUUID: TEST_ARRAY_16) + let pni = Pni(fromUUID: TEST_ARRAY_16_1) + let redemptionTime: UInt64 = 123_456 * SECONDS_PER_DAY - // Client - let credential = try! response.receive(groupMembers: [aliceAci, bobAci, eveAci, malloryAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams) - XCTAssertThrowsError(try response.receive(groupMembers: [aliceAci, bobAci, eveAci, malloryAci], localUser: bobAci, serverParams: serverPublicParams, groupParams: groupSecretParams)) - XCTAssertThrowsError(try response.receive(groupMembers: [bobAci, eveAci, malloryAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams)) - XCTAssertThrowsError(try response.receive(groupMembers: [aliceAci, eveAci, malloryAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams)) + // Generate keys (client's are per-group, server's are not) + // --- - // Try again with the alternate receive. - _ = try! response.receive(groupMembers: groupCiphertexts, localUser: aliceCiphertext, serverParams: serverPublicParams, groupParams: groupSecretParams) - XCTAssertThrowsError(try response.receive(groupMembers: groupCiphertexts, localUser: groupCiphertexts[1], serverParams: serverPublicParams, groupParams: groupSecretParams)) - XCTAssertThrowsError(try response.receive(groupMembers: Array(groupCiphertexts.dropFirst()), localUser: aliceCiphertext, serverParams: serverPublicParams, groupParams: groupSecretParams)) - XCTAssertThrowsError(try response.receive(groupMembers: Array(groupCiphertexts.dropLast()), localUser: aliceCiphertext, serverParams: serverPublicParams, groupParams: groupSecretParams)) + // SERVER + let serverSecretParams = try ServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = try serverSecretParams.getPublicParams() + let serverZkAuth = ServerZkAuthOperations(serverSecretParams: serverSecretParams) - let presentation = credential.present(serverParams: serverPublicParams, randomness: TEST_ARRAY_32_3) + // CLIENT + let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) + let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) - // Server - try! presentation.verify(groupMembers: [bobAci, eveAci, malloryAci], serverParams: serverSecretParams) - try! presentation.verify(groupMembers: [bobAci, eveAci, malloryAci], now: Date().addingTimeInterval(60 * 60), serverParams: serverSecretParams) + XCTAssertEqual((try groupSecretParams.getMasterKey()).serialize(), masterKey.serialize()) - XCTAssertThrowsError(try presentation.verify(groupMembers: [aliceAci, bobAci, eveAci, malloryAci], serverParams: serverSecretParams)) - XCTAssertThrowsError(try presentation.verify(groupMembers: [eveAci, malloryAci], serverParams: serverSecretParams)) + let groupPublicParams = try groupSecretParams.getPublicParams() - // credential should definitely be expired after 2 days - XCTAssertThrowsError(try presentation.verify(groupMembers: [bobAci, eveAci, malloryAci], now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY * 2 + 1)), serverParams: serverSecretParams)) - } + // SERVER + // Issue credential + let authCredentialResponse = try serverZkAuth.issueAuthCredentialWithPniAsServiceId(randomness: self.TEST_ARRAY_32_2, aci: aci, pni: pni, redemptionTime: redemptionTime) - func testEmptyGroupSendCredential() { - let serverSecretParams = try! ServerSecretParams.generate(randomness: TEST_ARRAY_32) - let serverPublicParams = try! serverSecretParams.getPublicParams() + // CLIENT + // Receive credential + let clientZkAuthCipher = ClientZkAuthOperations(serverPublicParams: serverPublicParams) + let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) + let authCredential = try clientZkAuthCipher.receiveAuthCredentialWithPniAsServiceId(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse) + XCTAssertThrowsError(try clientZkAuthCipher.receiveAuthCredentialWithPniAsAci(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse)) - let aliceAci = try! Aci.parseFrom(serviceIdString: "9d0652a3-dcc3-4d11-975f-74d61598733f") + // Create and decrypt user entry + let aciCiphertext = try clientZkGroupCipher.encrypt(aci) + let aciPlaintext = try clientZkGroupCipher.decrypt(aciCiphertext) + XCTAssertEqual(aci, aciPlaintext) + let pniCiphertext = try clientZkGroupCipher.encrypt(pni) + let pniPlaintext = try clientZkGroupCipher.decrypt(pniCiphertext) + XCTAssertEqual(pni, pniPlaintext) - let masterKey = try! GroupMasterKey(contents: TEST_ARRAY_32_1) - let groupSecretParams = try! GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) + // Create presentation + let presentation = try clientZkAuthCipher.createAuthCredentialPresentation(randomness: self.TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, authCredential: authCredential) - let aliceCiphertext = try! ClientZkGroupCipher(groupSecretParams: groupSecretParams).encrypt(aliceAci) + // Verify presentation + let uuidCiphertextRecv = try presentation.getUuidCiphertext() + XCTAssertEqual(aciCiphertext.serialize(), uuidCiphertextRecv.serialize()) + XCTAssertEqual(pniCiphertext.serialize(), try presentation.getPniCiphertext()?.serialize()) + XCTAssertEqual(try presentation.getRedemptionTime(), Date(timeIntervalSince1970: TimeInterval(redemptionTime))) + try serverZkAuth.verifyAuthCredentialPresentation(groupPublicParams: groupPublicParams, authCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(redemptionTime))) + } - // Server - let response = GroupSendCredentialResponse.issueCredential(groupMembers: [aliceCiphertext], requestingMember: aliceCiphertext, params: serverSecretParams, randomness: TEST_ARRAY_32_2) + func testAuthWithPniAsAciIntegration() throws { + let aci = Aci(fromUUID: TEST_ARRAY_16) + let pni = Pni(fromUUID: TEST_ARRAY_16_1) + let redemptionTime: UInt64 = 123_456 * SECONDS_PER_DAY - // Client - _ = try! response.receive(groupMembers: [aliceAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams) - } + // Generate keys (client's are per-group, server's are not) + // --- + + // SERVER + let serverSecretParams = try ServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = try serverSecretParams.getPublicParams() + let serverZkAuth = ServerZkAuthOperations(serverSecretParams: serverSecretParams) + + // CLIENT + let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) + let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) + + XCTAssertEqual((try groupSecretParams.getMasterKey()).serialize(), masterKey.serialize()) + + let groupPublicParams = try groupSecretParams.getPublicParams() + + // SERVER + // Issue credential + let authCredentialResponse = try serverZkAuth.issueAuthCredentialWithPniAsAci(randomness: self.TEST_ARRAY_32_2, aci: aci, pni: pni, redemptionTime: redemptionTime) + + // CLIENT + // Receive credential + let clientZkAuthCipher = ClientZkAuthOperations(serverPublicParams: serverPublicParams) + let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) + let authCredential = try clientZkAuthCipher.receiveAuthCredentialWithPniAsAci(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse) + XCTAssertThrowsError(try clientZkAuthCipher.receiveAuthCredentialWithPniAsServiceId(aci: aci, pni: pni, redemptionTime: redemptionTime, authCredentialResponse: authCredentialResponse)) + + // Create and decrypt user entry + let aciCiphertext = try clientZkGroupCipher.encrypt(aci) + let aciPlaintext = try clientZkGroupCipher.decrypt(aciCiphertext) + XCTAssertEqual(aci, aciPlaintext) + let pniAsAci = Aci(fromUUID: pni.rawUUID) + let pniCiphertext = try clientZkGroupCipher.encrypt(pniAsAci) + let pniPlaintext = try clientZkGroupCipher.decrypt(pniCiphertext) + XCTAssertEqual(pniAsAci, pniPlaintext) + + // Create presentation + let presentation = try clientZkAuthCipher.createAuthCredentialPresentation(randomness: self.TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, authCredential: authCredential) + + // Verify presentation + let uuidCiphertextRecv = try presentation.getUuidCiphertext() + XCTAssertEqual(aciCiphertext.serialize(), uuidCiphertextRecv.serialize()) + XCTAssertEqual(pniCiphertext.serialize(), try presentation.getPniCiphertext()?.serialize()) + XCTAssertEqual(try presentation.getRedemptionTime(), Date(timeIntervalSince1970: TimeInterval(redemptionTime))) + try serverZkAuth.verifyAuthCredentialPresentation(groupPublicParams: groupPublicParams, authCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(redemptionTime))) + } + + func testExpiringProfileKeyIntegration() throws { + let userId = Aci(fromUUID: TEST_ARRAY_16) + // Generate keys (client's are per-group, server's are not) + // --- + + // SERVER + let serverSecretParams = try ServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = try serverSecretParams.getPublicParams() + let serverZkProfile = ServerZkProfileOperations(serverSecretParams: serverSecretParams) + + // CLIENT + let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) + let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) + + XCTAssertEqual(try groupSecretParams.getMasterKey().serialize(), masterKey.serialize()) + + let groupPublicParams = try groupSecretParams.getPublicParams() + let clientZkProfileCipher = ClientZkProfileOperations(serverPublicParams: serverPublicParams) + + let profileKey = try ProfileKey(contents: TEST_ARRAY_32_1) + let profileKeyCommitment = try profileKey.getCommitment(userId: userId) + + // Create context and request + let context = try clientZkProfileCipher.createProfileKeyCredentialRequestContext(randomness: self.TEST_ARRAY_32_3, userId: userId, profileKey: profileKey) + let request = try context.getRequest() + + // SERVER + let now = UInt64(Date().timeIntervalSince1970) + let startOfDay = now - (now % SECONDS_PER_DAY) + let expiration = startOfDay + 5 * SECONDS_PER_DAY + let response = try serverZkProfile.issueExpiringProfileKeyCredential(randomness: self.TEST_ARRAY_32_4, profileKeyCredentialRequest: request, userId: userId, profileKeyCommitment: profileKeyCommitment, expiration: expiration) + + // CLIENT + // Gets stored profile credential + let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) + let profileKeyCredential = try clientZkProfileCipher.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext: context, profileKeyCredentialResponse: response) + + // Create encrypted UID and profile key + let uuidCiphertext = try clientZkGroupCipher.encrypt(userId) + let plaintext = try clientZkGroupCipher.decrypt(uuidCiphertext) + XCTAssertEqual(plaintext, userId) + + let profileKeyCiphertext = try clientZkGroupCipher.encryptProfileKey(profileKey: profileKey, userId: userId) + let decryptedProfileKey = try clientZkGroupCipher.decryptProfileKey(profileKeyCiphertext: profileKeyCiphertext, userId: userId) + XCTAssertEqual(profileKey.serialize(), decryptedProfileKey.serialize()) + + XCTAssertEqual(Date(timeIntervalSince1970: TimeInterval(expiration)), profileKeyCredential.expirationTime) + + let presentation = try clientZkProfileCipher.createProfileKeyCredentialPresentation(randomness: self.TEST_ARRAY_32_5, groupSecretParams: groupSecretParams, profileKeyCredential: profileKeyCredential) + + // Verify presentation + try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation) + try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(expiration - 5))) + XCTAssertThrowsError(try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(expiration)))) + XCTAssertThrowsError(try serverZkProfile.verifyProfileKeyCredentialPresentation(groupPublicParams: groupPublicParams, profileKeyCredentialPresentation: presentation, now: Date(timeIntervalSince1970: TimeInterval(expiration + 5)))) + + let uuidCiphertextRecv = try presentation.getUuidCiphertext() + XCTAssertEqual(uuidCiphertext.serialize(), uuidCiphertextRecv.serialize()) + } + + func testServerSignatures() throws { + let serverSecretParams = try ServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = try serverSecretParams.getPublicParams() + + let message = self.TEST_ARRAY_32_1 + + let signature = try serverSecretParams.sign(randomness: self.TEST_ARRAY_32_2, message: message) + try serverPublicParams.verifySignature(message: message, notarySignature: signature) + + XCTAssertEqual(signature.serialize(), self.serverSignatureResult) + + var alteredMessage = message + alteredMessage[0] ^= 1 + do { + try serverPublicParams.verifySignature(message: alteredMessage, notarySignature: signature) + XCTAssert(false) + } catch SignalError.verificationFailed(_) { + // good + } + } + + func testInvalidSerialized() throws { + let ckp: [UInt8] = Array(repeating: 255, count: 289) + do { + _ = try GroupSecretParams(contents: ckp) + XCTFail("should have thrown") + } catch SignalError.invalidType(_) { + // good + } + } + + func testWrongSizeSerialized() throws { + let ckp: [UInt8] = Array(repeating: 255, count: 5) + do { + _ = try GroupSecretParams(contents: ckp) + XCTFail("should have thrown") + } catch SignalError.invalidType(_) { + // good + } + } + + func testBlobEncryption() throws { + let groupSecretParams = try GroupSecretParams.generate() + let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) + + let plaintext: [UInt8] = [0, 1, 2, 3, 4] + let ciphertext = try clientZkGroupCipher.encryptBlob(plaintext: plaintext) + let plaintext2 = try clientZkGroupCipher.decryptBlob(blobCiphertext: ciphertext) + + XCTAssertEqual(plaintext, plaintext2) + } + + func testBlobEncryptionWithRandom() throws { + let masterKey = try GroupMasterKey(contents: TEST_ARRAY_32_1) + let groupSecretParams = try GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) + let clientZkGroupCipher = ClientZkGroupCipher(groupSecretParams: groupSecretParams) + + let plaintext: [UInt8] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, + ] + + let ciphertext: [UInt8] = [ + 0xDD, 0x4D, 0x03, 0x2C, 0xA9, 0xBB, 0x75, 0xA4, 0xA7, 0x85, 0x41, 0xB9, 0x0C, 0xB4, 0xE9, 0x57, + 0x43, 0xF3, 0xB0, 0xDA, 0xBF, 0xC7, 0xE1, 0x11, 0x01, 0xB0, 0x98, 0xE3, 0x4F, 0x6C, 0xF6, 0x51, + 0x39, 0x40, 0xA0, 0x4C, 0x1F, 0x20, 0xA3, 0x02, 0x69, 0x2A, 0xFD, 0xC7, 0x08, 0x7F, 0x10, 0x19, + 0x60, 0x00, + ] + + let ciphertext257: [UInt8] = [ + 0x5C, 0xB5, 0xB7, 0xBF, 0xF0, 0x6E, 0x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xD0, 0xC9, 0x47, 0xE7, 0xC9, 0x86, 0xB2, + 0xF3, 0xCE, 0x3B, 0x71, 0x61, 0xCE, 0xC7, 0x2C, 0x08, 0xE2, 0xC4, 0xAD, 0xE3, 0xDE, 0xBE, 0x37, + 0x92, 0xD7, 0x36, 0xC0, 0x45, 0x7B, 0xC3, 0x52, 0xAF, 0xB8, 0xB6, 0xCA, 0xA4, 0x8A, 0x5B, 0x92, + 0xC1, 0xEC, 0x05, 0xBA, 0x80, 0x8B, 0xA8, 0xF9, 0x4C, 0x65, 0x72, 0xEB, 0xBF, 0x29, 0x81, 0x89, + 0x12, 0x34, 0x49, 0x87, 0x57, 0x3D, 0xE4, 0x19, 0xDB, 0xCC, 0x7F, 0x1E, 0xA0, 0xE4, 0xB2, 0xDD, + 0x40, 0x77, 0xB7, 0x6B, 0x38, 0x18, 0x19, 0x74, 0x7A, 0xC3, 0x32, 0xE4, 0x6F, 0xA2, 0x3A, 0xBF, + 0xC3, 0x33, 0x8E, 0x2F, 0x4B, 0x08, 0x1A, 0x8A, 0x53, 0xCB, 0xA0, 0x98, 0x8E, 0xEF, 0x11, 0x67, + 0x64, 0xD9, 0x44, 0xF1, 0xCE, 0x3F, 0x20, 0xA3, 0x02, 0x69, 0x2A, 0xFD, 0xC7, 0x08, 0x7F, 0x10, + 0x19, 0x60, 0x00, + ] + + let ciphertext2 = try clientZkGroupCipher.encryptBlob(randomness: self.TEST_ARRAY_32_2, plaintext: plaintext) + let plaintext2 = try clientZkGroupCipher.decryptBlob(blobCiphertext: ciphertext2) + + XCTAssertEqual(plaintext, plaintext2) + XCTAssertEqual(ciphertext, ciphertext2) + + let plaintext257 = try clientZkGroupCipher.decryptBlob(blobCiphertext: ciphertext257) + XCTAssertEqual(plaintext, plaintext257) + } + + func testCreateCallLinkCredential() throws { + let userId = Aci(fromUUID: TEST_ARRAY_16) + + let serverSecretParams = GenericServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = serverSecretParams.getPublicParams() + let clientSecretParams = CallLinkSecretParams.deriveFromRootKey(self.TEST_ARRAY_32_1) + let clientPublicParams = clientSecretParams.getPublicParams() + + // Client + let roomId = withUnsafeBytes(of: TEST_ARRAY_32_2) { Data($0) } + let context = CreateCallLinkCredentialRequestContext.forRoomId(roomId, randomness: self.TEST_ARRAY_32_3) + let request = context.getRequest() + + // Server + let now = UInt64(Date().timeIntervalSince1970) + let startOfDay = now - (now % SECONDS_PER_DAY) + let response = request.issueCredential(userId: userId, timestamp: Date(timeIntervalSince1970: TimeInterval(startOfDay)), params: serverSecretParams, randomness: self.TEST_ARRAY_32_4) + + // Client + let credential = try context.receive(response, userId: userId, params: serverPublicParams) + let presentation = credential.present(roomId: roomId, userId: userId, serverParams: serverPublicParams, callLinkParams: clientSecretParams, randomness: self.TEST_ARRAY_32_5) + + // Server + try presentation.verify(roomId: roomId, serverParams: serverSecretParams, callLinkParams: clientPublicParams) + try presentation.verify(roomId: roomId, now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY)), serverParams: serverSecretParams, callLinkParams: clientPublicParams) + + XCTAssertThrowsError(try presentation.verify(roomId: roomId, now: Date(timeIntervalSince1970: TimeInterval(startOfDay + 30 * 60 * 60)), serverParams: serverSecretParams, callLinkParams: clientPublicParams)) + } + + func testCallLinkAuthCredential() throws { + let userId = Aci(fromUUID: TEST_ARRAY_16) + + let serverSecretParams = GenericServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = serverSecretParams.getPublicParams() + let clientSecretParams = CallLinkSecretParams.deriveFromRootKey(self.TEST_ARRAY_32_1) + let clientPublicParams = clientSecretParams.getPublicParams() + + // Server + let now = UInt64(Date().timeIntervalSince1970) + let startOfDay = now - (now % SECONDS_PER_DAY) + let redemptionTime = Date(timeIntervalSince1970: TimeInterval(startOfDay)) + let response = CallLinkAuthCredentialResponse.issueCredential(userId: userId, redemptionTime: redemptionTime, params: serverSecretParams, randomness: self.TEST_ARRAY_32_4) + + // Client + let credential = try response.receive(userId: userId, redemptionTime: redemptionTime, params: serverPublicParams) + let presentation = credential.present(userId: userId, redemptionTime: redemptionTime, serverParams: serverPublicParams, callLinkParams: clientSecretParams, randomness: self.TEST_ARRAY_32_5) + + // Server + try presentation.verify(serverParams: serverSecretParams, callLinkParams: clientPublicParams) + try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY)), serverParams: serverSecretParams, callLinkParams: clientPublicParams) + + XCTAssertThrowsError(try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + 3 * SECONDS_PER_DAY)), serverParams: serverSecretParams, callLinkParams: clientPublicParams)) + + // Client + XCTAssertEqual(userId, try clientSecretParams.decrypt(presentation.userId)) + } + + func testDeriveProfileKey() throws { + let expectedAccessKey: [UInt8] = [0x5A, 0x72, 0x3A, 0xCE, 0xE5, 0x2C, 0x5E, 0xA0, 0x2B, 0x92, 0xA3, 0xA3, 0x60, 0xC0, 0x95, 0x95] + let profileKeyBytes: [UInt8] = Array(repeating: 0x02, count: 32) + + let result = try ProfileKey(contents: profileKeyBytes).deriveAccessKey() + XCTAssertEqual(expectedAccessKey, result) + } + + func testBackupAuthCredentialDeterministic() throws { + let backupKey: [UInt8] = [ + 0xF9, 0xAB, 0xBB, 0xFF, 0xA7, 0xD4, 0x24, 0x92, + 0x97, 0x65, 0xAE, 0xCC, 0x84, 0xB6, 0x04, 0x63, + 0x3C, 0x55, 0xAC, 0x1B, 0xCE, 0x82, 0xE1, 0xEE, + 0x06, 0xB7, 0x9B, 0xC9, 0xA5, 0x62, 0x93, 0x38, + ] + let aci = UUID(uuidString: "e74beed0-e70f-4cfd-abbb-7e3eb333bbac")! + let serializedBackupID: [UInt8] = [0xE3, 0x92, 0x6F, 0x11, 0xDD, 0xD1, 0x43, 0xE6, 0xDD, 0x0F, 0x20, 0xBF, 0xCB, 0x08, 0x34, 0x9E] + let serializedRequestCredential = Data(base64Encoded: "AISCxQa8OsFqphsQPxqtzJk5+jndpE3SJG6bfazQB3994Aersq2yNRgcARBoedBeoEfKIXdty6X7l6+TiPFAqDvojRSO8xaZOpKJOvWSDJIGn6EeMl2jOjx+IQg8d8M0AQ==")! + let receiptLevel: UInt64 = 1 + + let context = BackupAuthCredentialRequestContext.create(backupKey: backupKey, aci: aci) + let request = context.getRequest() + let serverSecretParams = GenericServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = serverSecretParams.getPublicParams() + XCTAssertEqual(request.serialize(), Array(serializedRequestCredential)) + + let now = UInt64(Date().timeIntervalSince1970) + let startOfDay = now - (now % SECONDS_PER_DAY) + let response = request.issueCredential(timestamp: Date(timeIntervalSince1970: TimeInterval(startOfDay)), receiptLevel: receiptLevel, params: serverSecretParams, randomness: self.TEST_ARRAY_32_2) + let credential = try context.receive(response, params: serverPublicParams, expectedReceiptLevel: receiptLevel) + XCTAssertEqual(credential.backupID, serializedBackupID) + } + + func testBackupAuthCredential() throws { + let receiptLevel: UInt64 = 10 + + let serverSecretParams = GenericServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = serverSecretParams.getPublicParams() + + // Client + let backupKey = self.TEST_ARRAY_32_1 + let aci = UUID(uuidString: "e74beed0-e70f-4cfd-abbb-7e3eb333bbac")! + let context = BackupAuthCredentialRequestContext.create(backupKey: backupKey, aci: aci) + let request = context.getRequest() + + // Server + let now = UInt64(Date().timeIntervalSince1970) + let startOfDay = now - (now % SECONDS_PER_DAY) + let response = request.issueCredential(timestamp: Date(timeIntervalSince1970: TimeInterval(startOfDay)), receiptLevel: receiptLevel, params: serverSecretParams, randomness: self.TEST_ARRAY_32_2) + + // Client + let credential = try context.receive(response, params: serverPublicParams, expectedReceiptLevel: receiptLevel) + XCTAssertThrowsError(try context.receive(response, params: serverPublicParams, expectedReceiptLevel: receiptLevel + 1)) + + let presentation = credential.present(serverParams: serverPublicParams, randomness: self.TEST_ARRAY_32_3) + + // Server + try presentation.verify(serverParams: serverSecretParams) + try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY)), serverParams: serverSecretParams) + + // credential should be expired after 2 days + XCTAssertThrowsError(try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay + 1 + SECONDS_PER_DAY * 2)), serverParams: serverSecretParams)) + + // future credential should be invalid + XCTAssertThrowsError(try presentation.verify(now: Date(timeIntervalSince1970: TimeInterval(startOfDay - 1 - SECONDS_PER_DAY)), serverParams: serverSecretParams)) + } + + func testGroupSendCredential() { + let serverSecretParams = try! ServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = try! serverSecretParams.getPublicParams() + + let aliceAci = try! Aci.parseFrom(serviceIdString: "9d0652a3-dcc3-4d11-975f-74d61598733f") + let bobAci = try! Aci.parseFrom(serviceIdString: "6838237d-02f6-4098-b110-698253d15961") + let eveAci = try! Aci.parseFrom(serviceIdString: "3f0f4734-e331-4434-bd4f-6d8f6ea6dcc7") + let malloryAci = try! Aci.parseFrom(serviceIdString: "5d088142-6fd7-4dbd-af00-fdda1b3ce988") + + let masterKey = try! GroupMasterKey(contents: self.TEST_ARRAY_32_1) + let groupSecretParams = try! GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) + + let aliceCiphertext = try! ClientZkGroupCipher(groupSecretParams: groupSecretParams).encrypt(aliceAci) + let groupCiphertexts = [aliceAci, bobAci, eveAci, malloryAci].map { + try! ClientZkGroupCipher(groupSecretParams: groupSecretParams).encrypt($0) + } + + // Server + let now = UInt64(Date().timeIntervalSince1970) + let startOfDay = now - (now % SECONDS_PER_DAY) + let response = GroupSendCredentialResponse.issueCredential(groupMembers: groupCiphertexts, requestingMember: aliceCiphertext, params: serverSecretParams, randomness: self.TEST_ARRAY_32_2) + + // Client + let credential = try! response.receive(groupMembers: [aliceAci, bobAci, eveAci, malloryAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams) + XCTAssertThrowsError(try response.receive(groupMembers: [aliceAci, bobAci, eveAci, malloryAci], localUser: bobAci, serverParams: serverPublicParams, groupParams: groupSecretParams)) + XCTAssertThrowsError(try response.receive(groupMembers: [bobAci, eveAci, malloryAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams)) + XCTAssertThrowsError(try response.receive(groupMembers: [aliceAci, eveAci, malloryAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams)) + + // Try again with the alternate receive. + _ = try! response.receive(groupMembers: groupCiphertexts, localUser: aliceCiphertext, serverParams: serverPublicParams, groupParams: groupSecretParams) + XCTAssertThrowsError(try response.receive(groupMembers: groupCiphertexts, localUser: groupCiphertexts[1], serverParams: serverPublicParams, groupParams: groupSecretParams)) + XCTAssertThrowsError(try response.receive(groupMembers: Array(groupCiphertexts.dropFirst()), localUser: aliceCiphertext, serverParams: serverPublicParams, groupParams: groupSecretParams)) + XCTAssertThrowsError(try response.receive(groupMembers: Array(groupCiphertexts.dropLast()), localUser: aliceCiphertext, serverParams: serverPublicParams, groupParams: groupSecretParams)) + + let presentation = credential.present(serverParams: serverPublicParams, randomness: self.TEST_ARRAY_32_3) + + // Server + try! presentation.verify(groupMembers: [bobAci, eveAci, malloryAci], serverParams: serverSecretParams) + try! presentation.verify(groupMembers: [bobAci, eveAci, malloryAci], now: Date().addingTimeInterval(60 * 60), serverParams: serverSecretParams) + + XCTAssertThrowsError(try presentation.verify(groupMembers: [aliceAci, bobAci, eveAci, malloryAci], serverParams: serverSecretParams)) + XCTAssertThrowsError(try presentation.verify(groupMembers: [eveAci, malloryAci], serverParams: serverSecretParams)) + + // credential should definitely be expired after 2 days + XCTAssertThrowsError(try presentation.verify(groupMembers: [bobAci, eveAci, malloryAci], now: Date(timeIntervalSince1970: TimeInterval(startOfDay + SECONDS_PER_DAY * 2 + 1)), serverParams: serverSecretParams)) + } + + func testEmptyGroupSendCredential() { + let serverSecretParams = try! ServerSecretParams.generate(randomness: self.TEST_ARRAY_32) + let serverPublicParams = try! serverSecretParams.getPublicParams() + + let aliceAci = try! Aci.parseFrom(serviceIdString: "9d0652a3-dcc3-4d11-975f-74d61598733f") + + let masterKey = try! GroupMasterKey(contents: self.TEST_ARRAY_32_1) + let groupSecretParams = try! GroupSecretParams.deriveFromMasterKey(groupMasterKey: masterKey) + + let aliceCiphertext = try! ClientZkGroupCipher(groupSecretParams: groupSecretParams).encrypt(aliceAci) + + // Server + let response = GroupSendCredentialResponse.issueCredential(groupMembers: [aliceCiphertext], requestingMember: aliceCiphertext, params: serverSecretParams, randomness: self.TEST_ARRAY_32_2) + + // Client + _ = try! response.receive(groupMembers: [aliceAci], localUser: aliceAci, serverParams: serverPublicParams, groupParams: groupSecretParams) + } }