0
0
mirror of https://github.com/signalapp/libsignal.git synced 2024-09-19 19:42:19 +02:00

Enforce Swift code formatting

This commit is contained in:
moiseev-signal 2024-02-23 09:56:38 -08:00 committed by GitHub
parent 4f4d21a8ca
commit 58f43107ab
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
126 changed files with 3121 additions and 2738 deletions

View File

@ -34,3 +34,6 @@ max_line_length = 80
[*.sh] [*.sh]
indent_size = 4 indent_size = 4
[*.swift]
indent_size = 4

View File

@ -353,6 +353,10 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Check formatting
run: swiftformat --swiftversion 5 --reporter github-actions-log --lint .
working-directory: swift
- name: Run lint - name: Run lint
run: swiftlint lint --strict --reporter github-actions-logging run: swiftlint lint --strict --reporter github-actions-logging
working-directory: swift working-directory: swift

25
.swiftformat Normal file
View File

@ -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

View File

@ -12,13 +12,13 @@ let rustBuildDir = "../target/debug/"
let package = Package( let package = Package(
name: "LibSignalClient", name: "LibSignalClient",
platforms: [ platforms: [
.macOS(.v10_15), .iOS(.v13) .macOS(.v10_15), .iOS(.v13),
], ],
products: [ products: [
.library( .library(
name: "LibSignalClient", name: "LibSignalClient",
targets: ["LibSignalClient"] targets: ["LibSignalClient"]
) ),
], ],
dependencies: [ dependencies: [
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.3.0"), .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.3.0"),
@ -34,6 +34,6 @@ let package = Package(
name: "LibSignalClientTests", name: "LibSignalClientTests",
dependencies: ["LibSignalClient"], dependencies: ["LibSignalClient"],
linkerSettings: [.unsafeFlags(["-L\(rustBuildDir)"])] linkerSettings: [.unsafeFlags(["-L\(rustBuildDir)"])]
) ),
] ]
) )

View File

@ -8,9 +8,11 @@ import SignalFfi
public class ProtocolAddress: ClonableHandleOwner { public class ProtocolAddress: ClonableHandleOwner {
public convenience init(name: String, deviceId: UInt32) throws { public convenience init(name: String, deviceId: UInt32) throws {
var handle: OpaquePointer? var handle: OpaquePointer?
try checkError(signal_address_new(&handle, try checkError(signal_address_new(
&handle,
name, name,
deviceId)) deviceId
))
self.init(owned: handle!) 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) 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) return signal_address_destroy(handle)
} }
@ -47,7 +49,7 @@ public class ProtocolAddress: ClonableHandleOwner {
/// ///
/// In a future release ProtocolAddresses will *only* support ServiceIds. /// In a future release ProtocolAddresses will *only* support ServiceIds.
public var serviceId: ServiceId! { public var serviceId: ServiceId! {
return try? ServiceId.parseFrom(serviceIdString: name) return try? ServiceId.parseFrom(serviceIdString: self.name)
} }
public var deviceId: UInt32 { public var deviceId: UInt32 {
@ -63,7 +65,7 @@ public class ProtocolAddress: ClonableHandleOwner {
extension ProtocolAddress: CustomDebugStringConvertible { extension ProtocolAddress: CustomDebugStringConvertible {
public var debugDescription: String { public var debugDescription: String {
return "\(name).\(deviceId)" return "\(self.name).\(self.deviceId)"
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class Aes256Ctr32: NativeHandleOwner { public class Aes256Ctr32: NativeHandleOwner {
public static let keyLength: Int = 32 public static let keyLength: Int = 32
@ -27,27 +27,31 @@ public class Aes256Ctr32: NativeHandleOwner {
var nonceBufferWithoutCounter = SignalBorrowedBuffer(nonceBytes) var nonceBufferWithoutCounter = SignalBorrowedBuffer(nonceBytes)
nonceBufferWithoutCounter.length -= 4 nonceBufferWithoutCounter.length -= 4
var result: OpaquePointer? var result: OpaquePointer?
try checkError(signal_aes256_ctr32_new(&result, try checkError(signal_aes256_ctr32_new(
&result,
keyBuffer, keyBuffer,
nonceBufferWithoutCounter, nonceBufferWithoutCounter,
initialCounter)) initialCounter
))
return result return result
} }
} }
self.init(owned: handle!) 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) return signal_aes256_ctr32_destroy(handle)
} }
public func process(_ message: inout Data) throws { public func process(_ message: inout Data) throws {
try withNativeHandle { nativeHandle in try withNativeHandle { nativeHandle in
try message.withUnsafeMutableBytes { messageBytes in try message.withUnsafeMutableBytes { messageBytes in
try checkError(signal_aes256_ctr32_process(nativeHandle, try checkError(signal_aes256_ctr32_process(
nativeHandle,
SignalBorrowedMutableBuffer(messageBytes), SignalBorrowedMutableBuffer(messageBytes),
0, 0,
UInt32(messageBytes.count))) UInt32(messageBytes.count)
))
} }
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public struct Aes256GcmEncryptedData { public struct Aes256GcmEncryptedData {
public static let keyLength: Int = 32 public static let keyLength: Int = 32
@ -33,19 +33,18 @@ public struct Aes256GcmEncryptedData {
} }
public func concatenate() -> Data { public func concatenate() -> Data {
var result = Data(capacity: nonce.count + ciphertext.count + authenticationTag.count) var result = Data(capacity: nonce.count + self.ciphertext.count + self.authenticationTag.count)
result += nonce result += self.nonce
result += ciphertext result += self.ciphertext
result += authenticationTag result += self.authenticationTag
return result return result
} }
public static func encrypt<KeyBytes, AssociatedDataBytes>( public static func encrypt(
_ message: Data, _ message: Data,
key: KeyBytes, key: some ContiguousBytes,
associatedData: AssociatedDataBytes associatedData: some ContiguousBytes
) throws -> Self ) throws -> Self {
where KeyBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes {
var nonce = Data(count: Self.nonceLength) var nonce = Data(count: Self.nonceLength)
try nonce.withUnsafeMutableBytes { try fillRandom($0) } try nonce.withUnsafeMutableBytes { try fillRandom($0) }
@ -57,17 +56,16 @@ public struct Aes256GcmEncryptedData {
return Self(nonce: nonce, ciphertext: ciphertext, authenticationTag: tag) return Self(nonce: nonce, ciphertext: ciphertext, authenticationTag: tag)
} }
public static func encrypt<KeyBytes: ContiguousBytes>(_ message: Data, key: KeyBytes) throws -> Self { public static func encrypt(_ message: Data, key: some ContiguousBytes) throws -> Self {
return try encrypt(message, key: key, associatedData: []) 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 here specifically to avoid copying the ciphertext again if the struct is no longer used.
@inlinable @inlinable
public func decrypt<KeyBytes, AssociatedDataBytes>( public func decrypt(
key: KeyBytes, key: some ContiguousBytes,
associatedData: AssociatedDataBytes associatedData: some ContiguousBytes
) throws -> Data ) throws -> Data {
where KeyBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes {
let cipher = try Aes256GcmDecryption(key: key, nonce: self.nonce, associatedData: associatedData) let cipher = try Aes256GcmDecryption(key: key, nonce: self.nonce, associatedData: associatedData)
var plaintext = self.ciphertext var plaintext = self.ciphertext
try cipher.decrypt(&plaintext) try cipher.decrypt(&plaintext)
@ -78,26 +76,28 @@ public struct Aes256GcmEncryptedData {
} }
@inlinable @inlinable
public func decrypt<KeyBytes: ContiguousBytes>(key: KeyBytes) throws -> Data { public func decrypt(key: some ContiguousBytes) throws -> Data {
return try decrypt(key: key, associatedData: []) return try self.decrypt(key: key, associatedData: [])
} }
} }
/// Supports streamed encryption and custom nonces. Use Aes256GcmEncryptedData if you don't need either. /// Supports streamed encryption and custom nonces. Use Aes256GcmEncryptedData if you don't need either.
public class Aes256GcmEncryption: NativeHandleOwner { public class Aes256GcmEncryption: NativeHandleOwner {
public convenience init<KeyBytes, NonceBytes, AssociatedDataBytes>( public convenience init(
key: KeyBytes, key: some ContiguousBytes,
nonce: NonceBytes, nonce: some ContiguousBytes,
associatedData: AssociatedDataBytes associatedData: some ContiguousBytes
) throws where KeyBytes: ContiguousBytes, NonceBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes { ) throws {
let handle: OpaquePointer? = try key.withUnsafeBorrowedBuffer { keyBuffer in let handle: OpaquePointer? = try key.withUnsafeBorrowedBuffer { keyBuffer in
try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in
try associatedData.withUnsafeBorrowedBuffer { adBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in
var result: OpaquePointer? var result: OpaquePointer?
try checkError(signal_aes256_gcm_encryption_new(&result, try checkError(signal_aes256_gcm_encryption_new(
&result,
keyBuffer, keyBuffer,
nonceBuffer, nonceBuffer,
adBuffer)) adBuffer
))
return result return result
} }
} }
@ -105,17 +105,19 @@ public class Aes256GcmEncryption: NativeHandleOwner {
self.init(owned: handle!) 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) return signal_aes256_gcm_encryption_destroy(handle)
} }
public func encrypt(_ message: inout Data) throws { public func encrypt(_ message: inout Data) throws {
try withNativeHandle { nativeHandle in try withNativeHandle { nativeHandle in
try message.withUnsafeMutableBytes { messageBytes in try message.withUnsafeMutableBytes { messageBytes in
try checkError(signal_aes256_gcm_encryption_update(nativeHandle, try checkError(signal_aes256_gcm_encryption_update(
nativeHandle,
SignalBorrowedMutableBuffer(messageBytes), SignalBorrowedMutableBuffer(messageBytes),
0, 0,
UInt32(messageBytes.count))) UInt32(messageBytes.count)
))
} }
} }
} }
@ -131,19 +133,21 @@ public class Aes256GcmEncryption: NativeHandleOwner {
/// Supports streamed decryption. Use Aes256GcmEncryptedData if you don't need streamed decryption. /// Supports streamed decryption. Use Aes256GcmEncryptedData if you don't need streamed decryption.
public class Aes256GcmDecryption: NativeHandleOwner { public class Aes256GcmDecryption: NativeHandleOwner {
public convenience init<KeyBytes, NonceBytes, AssociatedDataBytes>( public convenience init(
key: KeyBytes, key: some ContiguousBytes,
nonce: NonceBytes, nonce: some ContiguousBytes,
associatedData: AssociatedDataBytes associatedData: some ContiguousBytes
) throws where KeyBytes: ContiguousBytes, NonceBytes: ContiguousBytes, AssociatedDataBytes: ContiguousBytes { ) throws {
let handle: OpaquePointer? = try key.withUnsafeBorrowedBuffer { keyBuffer in let handle: OpaquePointer? = try key.withUnsafeBorrowedBuffer { keyBuffer in
try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in
try associatedData.withUnsafeBorrowedBuffer { adBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in
var result: OpaquePointer? var result: OpaquePointer?
try checkError(signal_aes256_gcm_decryption_new(&result, try checkError(signal_aes256_gcm_decryption_new(
&result,
keyBuffer, keyBuffer,
nonceBuffer, nonceBuffer,
adBuffer)) adBuffer
))
return result return result
} }
} }
@ -151,28 +155,32 @@ public class Aes256GcmDecryption: NativeHandleOwner {
self.init(owned: handle!) 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) return signal_aes256_gcm_decryption_destroy(handle)
} }
public func decrypt(_ message: inout Data) throws { public func decrypt(_ message: inout Data) throws {
try withNativeHandle { nativeHandle in try withNativeHandle { nativeHandle in
try message.withUnsafeMutableBytes { messageBytes in try message.withUnsafeMutableBytes { messageBytes in
try checkError(signal_aes256_gcm_decryption_update(nativeHandle, try checkError(signal_aes256_gcm_decryption_update(
nativeHandle,
SignalBorrowedMutableBuffer(messageBytes), SignalBorrowedMutableBuffer(messageBytes),
0, 0,
UInt32(messageBytes.count))) UInt32(messageBytes.count)
))
} }
} }
} }
public func verifyTag<Bytes: ContiguousBytes>(_ tag: Bytes) throws -> Bool { public func verifyTag(_ tag: some ContiguousBytes) throws -> Bool {
return try withNativeHandle { nativeHandle in return try withNativeHandle { nativeHandle in
try tag.withUnsafeBorrowedBuffer { tagBuffer in try tag.withUnsafeBorrowedBuffer { tagBuffer in
var result = false var result = false
try checkError(signal_aes256_gcm_decryption_verify_tag(&result, try checkError(signal_aes256_gcm_decryption_verify_tag(
&result,
nativeHandle, nativeHandle,
tagBuffer)) tagBuffer
))
return result return result
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class Aes256GcmSiv: NativeHandleOwner { public class Aes256GcmSiv: NativeHandleOwner {
public convenience init<Bytes: ContiguousBytes>(key bytes: Bytes) throws { public convenience init<Bytes: ContiguousBytes>(key bytes: Bytes) throws {
@ -16,29 +16,27 @@ public class Aes256GcmSiv: NativeHandleOwner {
self.init(owned: handle!) 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) return signal_aes256_gcm_siv_destroy(handle)
} }
public func encrypt<MessageBytes, NonceBytes, AssociatedDataBytes>( public func encrypt(
_ message: MessageBytes, _ message: some ContiguousBytes,
nonce: NonceBytes, nonce: some ContiguousBytes,
associatedData: AssociatedDataBytes associatedData: some ContiguousBytes
) throws -> [UInt8] ) throws -> [UInt8] {
where MessageBytes: ContiguousBytes,
NonceBytes: ContiguousBytes,
AssociatedDataBytes: ContiguousBytes {
try withNativeHandle { nativeHandle in try withNativeHandle { nativeHandle in
try message.withUnsafeBorrowedBuffer { messageBuffer in try message.withUnsafeBorrowedBuffer { messageBuffer in
try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in
try associatedData.withUnsafeBorrowedBuffer { adBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in
try invokeFnReturningArray { try invokeFnReturningArray {
signal_aes256_gcm_siv_encrypt($0, signal_aes256_gcm_siv_encrypt(
$0,
nativeHandle, nativeHandle,
messageBuffer, messageBuffer,
nonceBuffer, nonceBuffer,
adBuffer) adBuffer
)
} }
} }
} }
@ -46,29 +44,27 @@ public class Aes256GcmSiv: NativeHandleOwner {
} }
} }
public func decrypt<MessageBytes, NonceBytes, AssociatedDataBytes> ( public func decrypt(
_ message: MessageBytes, _ message: some ContiguousBytes,
nonce: NonceBytes, nonce: some ContiguousBytes,
associatedData: AssociatedDataBytes) throws -> [UInt8] associatedData: some ContiguousBytes
where MessageBytes: ContiguousBytes, ) throws -> [UInt8] {
NonceBytes: ContiguousBytes,
AssociatedDataBytes: ContiguousBytes {
try withNativeHandle { nativeHandle in try withNativeHandle { nativeHandle in
try message.withUnsafeBorrowedBuffer { messageBuffer in try message.withUnsafeBorrowedBuffer { messageBuffer in
try nonce.withUnsafeBorrowedBuffer { nonceBuffer in try nonce.withUnsafeBorrowedBuffer { nonceBuffer in
try associatedData.withUnsafeBorrowedBuffer { adBuffer in try associatedData.withUnsafeBorrowedBuffer { adBuffer in
try invokeFnReturningArray { try invokeFnReturningArray {
signal_aes256_gcm_siv_decrypt($0, signal_aes256_gcm_siv_decrypt(
$0,
nativeHandle, nativeHandle,
messageBuffer, messageBuffer,
nonceBuffer, nonceBuffer,
adBuffer) adBuffer
)
} }
} }
} }
} }
} }
} }
} }

View File

@ -28,12 +28,14 @@ extension Int32: Completable {
extension UnsafeRawPointer: Completable { extension UnsafeRawPointer: Completable {
typealias PromiseCallback = SignalCPromiseRawPointer typealias PromiseCallback = SignalCPromiseRawPointer
} }
extension OpaquePointer: Completable { extension OpaquePointer: Completable {
// C function pointer that takes two output arguments and one input argument. // C function pointer that takes two output arguments and one input argument.
typealias PromiseCallback = (@convention(c) ( typealias PromiseCallback = (@convention(c) (
_ error: SignalFfiErrorRef?, _ error: SignalFfiErrorRef?,
_ value: UnsafePointer<OpaquePointer?>?, _ value: UnsafePointer<OpaquePointer?>?,
_ context: UnsafeRawPointer?) -> Void)? _ context: UnsafeRawPointer?
) -> Void)?
} }
extension SignalFfiCdsiLookupResponse: Completable { extension SignalFfiCdsiLookupResponse: Completable {

View File

@ -3,24 +3,28 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
/// ///
/// Cds2Client provides bindings to interact with Signal's v2 Contact Discovery Service. /// Cds2Client provides bindings to interact with Signal's v2 Contact Discovery Service.
/// ///
/// See ``SgxClient`` /// See ``SgxClient``
public class Cds2Client: SgxClient { public class Cds2Client: SgxClient {
public convenience init(
public convenience init<MrenclaveBytes, AttestationBytes>(mrenclave: MrenclaveBytes, attestationMessage: AttestationBytes, currentDate: Date) throws mrenclave: some ContiguousBytes,
where MrenclaveBytes: ContiguousBytes, AttestationBytes: ContiguousBytes { attestationMessage: some ContiguousBytes,
currentDate: Date
) throws {
let handle: OpaquePointer? = try attestationMessage.withUnsafeBorrowedBuffer { attestationMessageBuffer in let handle: OpaquePointer? = try attestationMessage.withUnsafeBorrowedBuffer { attestationMessageBuffer in
try mrenclave.withUnsafeBorrowedBuffer { mrenclaveBuffer in try mrenclave.withUnsafeBorrowedBuffer { mrenclaveBuffer in
var result: OpaquePointer? var result: OpaquePointer?
try checkError(signal_cds2_client_state_new(&result, try checkError(signal_cds2_client_state_new(
&result,
mrenclaveBuffer, mrenclaveBuffer,
attestationMessageBuffer, attestationMessageBuffer,
UInt64(currentDate.timeIntervalSince1970 * 1000))) UInt64(currentDate.timeIntervalSince1970 * 1000)
))
return result return result
} }
} }

View File

@ -27,8 +27,8 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre
private var senderKeyMap: [SenderKeyName: SenderKeyRecord] = [:] private var senderKeyMap: [SenderKeyName: SenderKeyRecord] = [:]
public init() { public init() {
privateKey = IdentityKeyPair.generate() self.privateKey = IdentityKeyPair.generate()
registrationId = UInt32.random(in: 0...0x3FFF) self.registrationId = UInt32.random(in: 0...0x3FFF)
} }
public init(identity: IdentityKeyPair, registrationId: UInt32) { public init(identity: IdentityKeyPair, registrationId: UInt32) {
@ -37,15 +37,15 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre
} }
open func identityKeyPair(context: StoreContext) throws -> IdentityKeyPair { open func identityKeyPair(context: StoreContext) throws -> IdentityKeyPair {
return privateKey return self.privateKey
} }
open func localRegistrationId(context: StoreContext) throws -> UInt32 { open func localRegistrationId(context: StoreContext) throws -> UInt32 {
return registrationId return self.registrationId
} }
open func saveIdentity(_ identity: IdentityKey, for address: ProtocolAddress, context: StoreContext) throws -> Bool { 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 return false // newly created
} else { } else {
return true return true
@ -61,7 +61,7 @@ open class InMemorySignalProtocolStore: IdentityKeyStore, PreKeyStore, SignedPre
} }
open func identity(for address: ProtocolAddress, context: StoreContext) throws -> IdentityKey? { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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? { 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] { 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 { 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 { 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? { 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)]
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public enum Direction { public enum Direction {
case sending case sending

View File

@ -3,12 +3,14 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
internal func withIdentityKeyStore<Result>(_ store: IdentityKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalIdentityKeyStore>) throws -> Result) throws -> Result { internal func withIdentityKeyStore<Result>(_ store: IdentityKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalIdentityKeyStore>) throws -> Result) throws -> Result {
func ffiShimGetIdentityKeyPair(storeCtx: UnsafeMutableRawPointer?, func ffiShimGetIdentityKeyPair(
keyp: UnsafeMutablePointer<OpaquePointer?>?) -> Int32 { storeCtx: UnsafeMutableRawPointer?,
keyp: UnsafeMutablePointer<OpaquePointer?>?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var privateKey = try store.identityKeyPair(context: context).privateKey var privateKey = try store.identityKeyPair(context: context).privateKey
@ -17,8 +19,10 @@ internal func withIdentityKeyStore<Result>(_ store: IdentityKeyStore, _ context:
} }
} }
func ffiShimGetLocalRegistrationId(storeCtx: UnsafeMutableRawPointer?, func ffiShimGetLocalRegistrationId(
idp: UnsafeMutablePointer<UInt32>?) -> Int32 { storeCtx: UnsafeMutableRawPointer?,
idp: UnsafeMutablePointer<UInt32>?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
let id = try store.localRegistrationId(context: context) let id = try store.localRegistrationId(context: context)
@ -27,9 +31,11 @@ internal func withIdentityKeyStore<Result>(_ store: IdentityKeyStore, _ context:
} }
} }
func ffiShimSaveIdentity(storeCtx: UnsafeMutableRawPointer?, func ffiShimSaveIdentity(
storeCtx: UnsafeMutableRawPointer?,
address: OpaquePointer?, address: OpaquePointer?,
public_key: OpaquePointer?) -> Int32 { public_key: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var address = ProtocolAddress(borrowing: address) var address = ProtocolAddress(borrowing: address)
@ -46,9 +52,11 @@ internal func withIdentityKeyStore<Result>(_ store: IdentityKeyStore, _ context:
} }
} }
func ffiShimGetIdentity(storeCtx: UnsafeMutableRawPointer?, func ffiShimGetIdentity(
storeCtx: UnsafeMutableRawPointer?,
public_key: UnsafeMutablePointer<OpaquePointer?>?, public_key: UnsafeMutablePointer<OpaquePointer?>?,
address: OpaquePointer?) -> Int32 { address: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var address = ProtocolAddress(borrowing: address) var address = ProtocolAddress(borrowing: address)
@ -63,10 +71,12 @@ internal func withIdentityKeyStore<Result>(_ store: IdentityKeyStore, _ context:
} }
} }
func ffiShimIsTrustedIdentity(storeCtx: UnsafeMutableRawPointer?, func ffiShimIsTrustedIdentity(
storeCtx: UnsafeMutableRawPointer?,
address: OpaquePointer?, address: OpaquePointer?,
public_key: OpaquePointer?, public_key: OpaquePointer?,
raw_direction: UInt32) -> Int32 { raw_direction: UInt32
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(IdentityKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var address = ProtocolAddress(borrowing: address) var address = ProtocolAddress(borrowing: address)
@ -96,15 +106,18 @@ internal func withIdentityKeyStore<Result>(_ store: IdentityKeyStore, _ context:
get_local_registration_id: ffiShimGetLocalRegistrationId, get_local_registration_id: ffiShimGetLocalRegistrationId,
save_identity: ffiShimSaveIdentity, save_identity: ffiShimSaveIdentity,
get_identity: ffiShimGetIdentity, get_identity: ffiShimGetIdentity,
is_trusted_identity: ffiShimIsTrustedIdentity) is_trusted_identity: ffiShimIsTrustedIdentity
)
return try body(&ffiStore) return try body(&ffiStore)
} }
} }
internal func withPreKeyStore<Result>(_ store: PreKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalPreKeyStore>) throws -> Result) throws -> Result { internal func withPreKeyStore<Result>(_ store: PreKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalPreKeyStore>) throws -> Result) throws -> Result {
func ffiShimStorePreKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimStorePreKey(
storeCtx: UnsafeMutableRawPointer?,
id: UInt32, id: UInt32,
record: OpaquePointer?) -> Int32 { record: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var record = PreKeyRecord(borrowing: record) var record = PreKeyRecord(borrowing: record)
@ -114,9 +127,11 @@ internal func withPreKeyStore<Result>(_ store: PreKeyStore, _ context: StoreCont
} }
} }
func ffiShimLoadPreKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimLoadPreKey(
storeCtx: UnsafeMutableRawPointer?,
recordp: UnsafeMutablePointer<OpaquePointer?>?, recordp: UnsafeMutablePointer<OpaquePointer?>?,
id: UInt32) -> Int32 { id: UInt32
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var record = try store.loadPreKey(id: id, context: context) var record = try store.loadPreKey(id: id, context: context)
@ -125,8 +140,10 @@ internal func withPreKeyStore<Result>(_ store: PreKeyStore, _ context: StoreCont
} }
} }
func ffiShimRemovePreKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimRemovePreKey(
id: UInt32) -> Int32 { storeCtx: UnsafeMutableRawPointer?,
id: UInt32
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(PreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
try store.removePreKey(id: id, context: context) try store.removePreKey(id: id, context: context)
@ -139,15 +156,18 @@ internal func withPreKeyStore<Result>(_ store: PreKeyStore, _ context: StoreCont
ctx: $0, ctx: $0,
load_pre_key: ffiShimLoadPreKey, load_pre_key: ffiShimLoadPreKey,
store_pre_key: ffiShimStorePreKey, store_pre_key: ffiShimStorePreKey,
remove_pre_key: ffiShimRemovePreKey) remove_pre_key: ffiShimRemovePreKey
)
return try body(&ffiStore) return try body(&ffiStore)
} }
} }
internal func withSignedPreKeyStore<Result>(_ store: SignedPreKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalSignedPreKeyStore>) throws -> Result) throws -> Result { internal func withSignedPreKeyStore<Result>(_ store: SignedPreKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalSignedPreKeyStore>) throws -> Result) throws -> Result {
func ffiShimStoreSignedPreKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimStoreSignedPreKey(
storeCtx: UnsafeMutableRawPointer?,
id: UInt32, id: UInt32,
record: OpaquePointer?) -> Int32 { record: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SignedPreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SignedPreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var record = SignedPreKeyRecord(borrowing: record) var record = SignedPreKeyRecord(borrowing: record)
@ -157,9 +177,11 @@ internal func withSignedPreKeyStore<Result>(_ store: SignedPreKeyStore, _ contex
} }
} }
func ffiShimLoadSignedPreKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimLoadSignedPreKey(
storeCtx: UnsafeMutableRawPointer?,
recordp: UnsafeMutablePointer<OpaquePointer?>?, recordp: UnsafeMutablePointer<OpaquePointer?>?,
id: UInt32) -> Int32 { id: UInt32
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SignedPreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SignedPreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var record = try store.loadSignedPreKey(id: id, context: context) var record = try store.loadSignedPreKey(id: id, context: context)
@ -172,15 +194,18 @@ internal func withSignedPreKeyStore<Result>(_ store: SignedPreKeyStore, _ contex
var ffiStore = SignalSignedPreKeyStore( var ffiStore = SignalSignedPreKeyStore(
ctx: $0, ctx: $0,
load_signed_pre_key: ffiShimLoadSignedPreKey, load_signed_pre_key: ffiShimLoadSignedPreKey,
store_signed_pre_key: ffiShimStoreSignedPreKey) store_signed_pre_key: ffiShimStoreSignedPreKey
)
return try body(&ffiStore) return try body(&ffiStore)
} }
} }
internal func withKyberPreKeyStore<Result>(_ store: KyberPreKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalKyberPreKeyStore>) throws -> Result) throws -> Result { internal func withKyberPreKeyStore<Result>(_ store: KyberPreKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalKyberPreKeyStore>) throws -> Result) throws -> Result {
func ffiShimStoreKyberPreKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimStoreKyberPreKey(
storeCtx: UnsafeMutableRawPointer?,
id: UInt32, id: UInt32,
record: OpaquePointer?) -> Int32 { record: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var record = KyberPreKeyRecord(borrowing: record) var record = KyberPreKeyRecord(borrowing: record)
@ -190,9 +215,11 @@ internal func withKyberPreKeyStore<Result>(_ store: KyberPreKeyStore, _ context:
} }
} }
func ffiShimLoadKyberPreKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimLoadKyberPreKey(
storeCtx: UnsafeMutableRawPointer?,
recordp: UnsafeMutablePointer<OpaquePointer?>?, recordp: UnsafeMutablePointer<OpaquePointer?>?,
id: UInt32) -> Int32 { id: UInt32
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var record = try store.loadKyberPreKey(id: id, context: context) var record = try store.loadKyberPreKey(id: id, context: context)
@ -201,8 +228,10 @@ internal func withKyberPreKeyStore<Result>(_ store: KyberPreKeyStore, _ context:
} }
} }
func ffiShimMarkKyberPreKeyUsed(storeCtx: UnsafeMutableRawPointer?, func ffiShimMarkKyberPreKeyUsed(
id: UInt32) -> Int32 { storeCtx: UnsafeMutableRawPointer?,
id: UInt32
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(KyberPreKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
try store.markKyberPreKeyUsed(id: id, context: context) try store.markKyberPreKeyUsed(id: id, context: context)
@ -215,15 +244,18 @@ internal func withKyberPreKeyStore<Result>(_ store: KyberPreKeyStore, _ context:
ctx: $0, ctx: $0,
load_kyber_pre_key: ffiShimLoadKyberPreKey, load_kyber_pre_key: ffiShimLoadKyberPreKey,
store_kyber_pre_key: ffiShimStoreKyberPreKey, store_kyber_pre_key: ffiShimStoreKyberPreKey,
mark_kyber_pre_key_used: ffiShimMarkKyberPreKeyUsed) mark_kyber_pre_key_used: ffiShimMarkKyberPreKeyUsed
)
return try body(&ffiStore) return try body(&ffiStore)
} }
} }
internal func withSessionStore<Result>(_ store: SessionStore, _ context: StoreContext, _ body: (UnsafePointer<SignalSessionStore>) throws -> Result) throws -> Result { internal func withSessionStore<Result>(_ store: SessionStore, _ context: StoreContext, _ body: (UnsafePointer<SignalSessionStore>) throws -> Result) throws -> Result {
func ffiShimStoreSession(storeCtx: UnsafeMutableRawPointer?, func ffiShimStoreSession(
storeCtx: UnsafeMutableRawPointer?,
address: OpaquePointer?, address: OpaquePointer?,
record: OpaquePointer?) -> Int32 { record: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SessionStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SessionStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var address = ProtocolAddress(borrowing: address) var address = ProtocolAddress(borrowing: address)
@ -235,9 +267,11 @@ internal func withSessionStore<Result>(_ store: SessionStore, _ context: StoreCo
} }
} }
func ffiShimLoadSession(storeCtx: UnsafeMutableRawPointer?, func ffiShimLoadSession(
storeCtx: UnsafeMutableRawPointer?,
recordp: UnsafeMutablePointer<OpaquePointer?>?, recordp: UnsafeMutablePointer<OpaquePointer?>?,
address: OpaquePointer?) -> Int32 { address: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SessionStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SessionStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var address = ProtocolAddress(borrowing: address) var address = ProtocolAddress(borrowing: address)
@ -255,16 +289,19 @@ internal func withSessionStore<Result>(_ store: SessionStore, _ context: StoreCo
var ffiStore = SignalSessionStore( var ffiStore = SignalSessionStore(
ctx: $0, ctx: $0,
load_session: ffiShimLoadSession, load_session: ffiShimLoadSession,
store_session: ffiShimStoreSession) store_session: ffiShimStoreSession
)
return try body(&ffiStore) return try body(&ffiStore)
} }
} }
internal func withSenderKeyStore<Result>(_ store: SenderKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalSenderKeyStore>) throws -> Result) rethrows -> Result { internal func withSenderKeyStore<Result>(_ store: SenderKeyStore, _ context: StoreContext, _ body: (UnsafePointer<SignalSenderKeyStore>) throws -> Result) rethrows -> Result {
func ffiShimStoreSenderKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimStoreSenderKey(
storeCtx: UnsafeMutableRawPointer?,
sender: OpaquePointer?, sender: OpaquePointer?,
distributionId: UnsafePointer<uuid_t>?, distributionId: UnsafePointer<uuid_t>?,
record: OpaquePointer?) -> Int32 { record: OpaquePointer?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SenderKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SenderKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var sender = ProtocolAddress(borrowing: sender) var sender = ProtocolAddress(borrowing: sender)
@ -277,10 +314,12 @@ internal func withSenderKeyStore<Result>(_ store: SenderKeyStore, _ context: Sto
} }
} }
func ffiShimLoadSenderKey(storeCtx: UnsafeMutableRawPointer?, func ffiShimLoadSenderKey(
storeCtx: UnsafeMutableRawPointer?,
recordp: UnsafeMutablePointer<OpaquePointer?>?, recordp: UnsafeMutablePointer<OpaquePointer?>?,
sender: OpaquePointer?, sender: OpaquePointer?,
distributionId: UnsafePointer<uuid_t>?) -> Int32 { distributionId: UnsafePointer<uuid_t>?
) -> Int32 {
let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SenderKeyStore, StoreContext)>.self) let storeContext = storeCtx!.assumingMemoryBound(to: ErrorHandlingContext<(SenderKeyStore, StoreContext)>.self)
return storeContext.pointee.catchCallbackErrors { store, context in return storeContext.pointee.catchCallbackErrors { store, context in
var sender = ProtocolAddress(borrowing: sender) var sender = ProtocolAddress(borrowing: sender)
@ -299,7 +338,8 @@ internal func withSenderKeyStore<Result>(_ store: SenderKeyStore, _ context: Sto
var ffiStore = SignalSenderKeyStore( var ffiStore = SignalSenderKeyStore(
ctx: $0, ctx: $0,
load_sender_key: ffiShimLoadSenderKey, load_sender_key: ffiShimLoadSenderKey,
store_sender_key: ffiShimStoreSenderKey) store_sender_key: ffiShimStoreSenderKey
)
return try body(&ffiStore) return try body(&ffiStore)
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public enum KeyFormat: UInt8, CaseIterable { public enum KeyFormat: UInt8, CaseIterable {
// PKCS#8 is the default for backward compatibility // PKCS#8 is the default for backward compatibility
@ -30,13 +30,15 @@ public struct DeviceTransferKey {
} }
public func generateCertificate(_ name: String, _ daysTilExpire: Int) -> [UInt8] { public func generateCertificate(_ name: String, _ daysTilExpire: Int) -> [UInt8] {
return privateKey.withUnsafeBorrowedBuffer { privateKeyBuffer in return self.privateKey.withUnsafeBorrowedBuffer { privateKeyBuffer in
failOnError { failOnError {
try invokeFnReturningArray { try invokeFnReturningArray {
signal_device_transfer_generate_certificate($0, signal_device_transfer_generate_certificate(
$0,
privateKeyBuffer, privateKeyBuffer,
name, name,
UInt32(daysTilExpire)) UInt32(daysTilExpire)
)
} }
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
#if canImport(SignalCoreKit) #if canImport(SignalCoreKit)
import SignalCoreKit import SignalCoreKit

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public struct DisplayableFingerprint { public struct DisplayableFingerprint {
public let formatted: String 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 /// Throws an error if `other` is not a valid fingerprint encoding, or if it uses an
/// incompatible encoding version. /// incompatible encoding version.
public func compare<Other: ContiguousBytes>(againstEncoding other: Other) throws -> Bool { public func compare<Other: ContiguousBytes>(againstEncoding other: Other) throws -> Bool {
var result: Bool = false var result = false
try encoding.withUnsafeBorrowedBuffer { encodingBuffer in try encoding.withUnsafeBorrowedBuffer { encodingBuffer in
try other.withUnsafeBorrowedBuffer { otherBuffer in try other.withUnsafeBorrowedBuffer { otherBuffer in
try checkError(signal_fingerprint_compare(&result, encodingBuffer, otherBuffer)) try checkError(signal_fingerprint_compare(&result, encodingBuffer, otherBuffer))
@ -45,21 +45,26 @@ public struct NumericFingerprintGenerator {
self.iterations = iterations self.iterations = iterations
} }
public func create<LocalBytes, RemoteBytes>(version: Int, public func create(
localIdentifier: LocalBytes, version: Int,
localIdentifier: some ContiguousBytes,
localKey: PublicKey, localKey: PublicKey,
remoteIdentifier: RemoteBytes, remoteIdentifier: some ContiguousBytes,
remoteKey: PublicKey) throws -> Fingerprint remoteKey: PublicKey
where LocalBytes: ContiguousBytes, RemoteBytes: ContiguousBytes { ) throws -> Fingerprint {
var obj: OpaquePointer? var obj: OpaquePointer?
try withNativeHandles(localKey, remoteKey) { localKeyHandle, remoteKeyHandle in try withNativeHandles(localKey, remoteKey) { localKeyHandle, remoteKeyHandle in
try localIdentifier.withUnsafeBorrowedBuffer { localBuffer in try localIdentifier.withUnsafeBorrowedBuffer { localBuffer in
try remoteIdentifier.withUnsafeBorrowedBuffer { remoteBuffer in try remoteIdentifier.withUnsafeBorrowedBuffer { remoteBuffer in
try checkError(signal_fingerprint_new(&obj, UInt32(iterations), UInt32(version), try checkError(signal_fingerprint_new(
&obj,
UInt32(self.iterations),
UInt32(version),
localBuffer, localBuffer,
localKeyHandle, localKeyHandle,
remoteBuffer, remoteBuffer,
remoteKeyHandle)) remoteKeyHandle
))
} }
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
/// The HsmCodeHashList is a wrapper around a flat UInt8 array to make it more /// The HsmCodeHashList is a wrapper around a flat UInt8 array to make it more
/// convenient to send code hashes to initialize the client. /// convenient to send code hashes to initialize the client.
@ -15,7 +15,7 @@ public struct HsmCodeHashList {
var codeHashes: [UInt8] var codeHashes: [UInt8]
public init() { public init() {
codeHashes = [] self.codeHashes = []
} }
public mutating func append(_ codeHash: [UInt8]) throws { public mutating func append(_ codeHash: [UInt8]) throws {
@ -23,11 +23,11 @@ public struct HsmCodeHashList {
fatalError("code hash length must be 32") fatalError("code hash length must be 32")
} }
codeHashes.append(contentsOf: codeHash) self.codeHashes.append(contentsOf: codeHash)
} }
func flatten() -> [UInt8] { 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. /// which decrypts and verifies it, passing the plaintext back to the client for processing.
/// ///
public class HsmEnclaveClient: NativeHandleOwner { public class HsmEnclaveClient: NativeHandleOwner {
public convenience init<Bytes: ContiguousBytes>(publicKey: Bytes, codeHashes: HsmCodeHashList) throws { public convenience init<Bytes: ContiguousBytes>(publicKey: Bytes, codeHashes: HsmCodeHashList) throws {
let codeHashBytes = codeHashes.flatten() let codeHashBytes = codeHashes.flatten()
let handle: OpaquePointer? = try publicKey.withUnsafeBorrowedBuffer { publicKeyBuffer in let handle: OpaquePointer? = try publicKey.withUnsafeBorrowedBuffer { publicKeyBuffer in
try codeHashBytes.withUnsafeBorrowedBuffer { codeHashBuffer in try codeHashBytes.withUnsafeBorrowedBuffer { codeHashBuffer in
var result: OpaquePointer? var result: OpaquePointer?
try checkError(signal_hsm_enclave_client_new(&result, try checkError(signal_hsm_enclave_client_new(
&result,
publicKeyBuffer, publicKeyBuffer,
codeHashBuffer)) codeHashBuffer
))
return result return result
} }
} }
@ -65,7 +66,7 @@ public class HsmEnclaveClient: NativeHandleOwner {
self.init(owned: handle!) 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) return signal_hsm_enclave_client_destroy(handle)
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public enum Ias { public enum Ias {
public static func verify< public static func verify<
Signature: ContiguousBytes, Signature: ContiguousBytes,
Body: ContiguousBytes, Body: ContiguousBytes,

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public struct IdentityKey: Equatable { public struct IdentityKey: Equatable {
public let publicKey: PublicKey public let publicKey: PublicKey
@ -14,22 +14,21 @@ public struct IdentityKey: Equatable {
} }
public init<Bytes: ContiguousBytes>(bytes: Bytes) throws { public init<Bytes: ContiguousBytes>(bytes: Bytes) throws {
publicKey = try PublicKey(bytes) self.publicKey = try PublicKey(bytes)
} }
public func serialize() -> [UInt8] { public func serialize() -> [UInt8] {
return publicKey.serialize() return self.publicKey.serialize()
} }
public func verifyAlternateIdentity<Bytes: ContiguousBytes>(_ other: IdentityKey, signature: Bytes) throws -> Bool { public func verifyAlternateIdentity<Bytes: ContiguousBytes>(_ other: IdentityKey, signature: Bytes) throws -> Bool {
var result: Bool = false var result = false
try withNativeHandles(publicKey, other.publicKey) { selfHandle, otherHandle in try withNativeHandles(publicKey, other.publicKey) { selfHandle, otherHandle in
try signature.withUnsafeBorrowedBuffer { signatureBuffer in try signature.withUnsafeBorrowedBuffer { signatureBuffer in
try checkError(signal_identitykey_verify_alternate_identity(&result, selfHandle, otherHandle, signatureBuffer)) try checkError(signal_identitykey_verify_alternate_identity(&result, selfHandle, otherHandle, signatureBuffer))
} }
} }
return result return result
} }
} }
@ -50,8 +49,8 @@ public struct IdentityKeyPair {
try checkError(signal_identitykeypair_deserialize(&privkeyPtr, &pubkeyPtr, $0)) try checkError(signal_identitykeypair_deserialize(&privkeyPtr, &pubkeyPtr, $0))
} }
publicKey = PublicKey(owned: pubkeyPtr!) self.publicKey = PublicKey(owned: pubkeyPtr!)
privateKey = PrivateKey(owned: privkeyPtr!) self.privateKey = PrivateKey(owned: privkeyPtr!)
} }
public init(publicKey: PublicKey, privateKey: PrivateKey) { public init(publicKey: PublicKey, privateKey: PrivateKey) {
@ -60,7 +59,7 @@ public struct IdentityKeyPair {
} }
public func serialize() -> [UInt8] { public func serialize() -> [UInt8] {
return withNativeHandles(publicKey, privateKey) { publicKey, privateKey in return withNativeHandles(self.publicKey, self.privateKey) { publicKey, privateKey in
failOnError { failOnError {
try invokeFnReturningArray { try invokeFnReturningArray {
signal_identitykeypair_serialize($0, publicKey, privateKey) signal_identitykeypair_serialize($0, publicKey, privateKey)
@ -70,11 +69,11 @@ public struct IdentityKeyPair {
} }
public var identityKey: IdentityKey { public var identityKey: IdentityKey {
return IdentityKey(publicKey: publicKey) return IdentityKey(publicKey: self.publicKey)
} }
public func signAlternateIdentity(_ other: IdentityKey) -> [UInt8] { 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 { failOnError {
try invokeFnReturningArray { try invokeFnReturningArray {
signal_identitykeypair_sign_alternate_identity($0, publicKey, privateKey, other) signal_identitykeypair_sign_alternate_identity($0, publicKey, privateKey, other)

View File

@ -23,7 +23,7 @@ public enum SizeChoice {
} }
public class IncrementalMacContext: NativeHandleOwner { public class IncrementalMacContext: NativeHandleOwner {
private var _digest: Data = Data() private var _digest: Data = .init()
public convenience init<Key: ContiguousBytes>(key: Key, chunkSize sizeChoice: SizeChoice) throws { public convenience init<Key: ContiguousBytes>(key: Key, chunkSize sizeChoice: SizeChoice) throws {
let chunkSize = try sizeChoice.sizeInBytes() let chunkSize = try sizeChoice.sizeInBytes()
@ -35,14 +35,14 @@ public class IncrementalMacContext: NativeHandleOwner {
self.init(owned: handle!) 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) return signal_incremental_mac_destroy(handle)
} }
public func update<Bytes: ContiguousBytes>(_ bytes: Bytes) throws { public func update<Bytes: ContiguousBytes>(_ bytes: Bytes) throws {
let digest = try bytes.withUnsafeBorrowedBuffer { bytesPtr in let digest = try bytes.withUnsafeBorrowedBuffer { bytesPtr in
return try invokeFnReturningArray { try invokeFnReturningArray {
return signal_incremental_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length)) signal_incremental_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length))
} }
} }
self._digest.append(contentsOf: digest) self._digest.append(contentsOf: digest)
@ -50,7 +50,7 @@ public class IncrementalMacContext: NativeHandleOwner {
public func finalize() throws -> [UInt8] { public func finalize() throws -> [UInt8] {
let digest = try invokeFnReturningArray { let digest = try invokeFnReturningArray {
return signal_incremental_mac_finalize($0, unsafeNativeHandle) signal_incremental_mac_finalize($0, unsafeNativeHandle)
} }
self._digest.append(contentsOf: digest) self._digest.append(contentsOf: digest)
return Array(self._digest) return Array(self._digest)
@ -73,14 +73,14 @@ public class ValidatingMacContext: NativeHandleOwner {
self.init(owned: handle!) 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) return signal_validating_mac_destroy(handle)
} }
public func update<Bytes: ContiguousBytes>(_ bytes: Bytes) throws -> UInt32 { public func update<Bytes: ContiguousBytes>(_ bytes: Bytes) throws -> UInt32 {
let validBytesCount = try bytes.withUnsafeBorrowedBuffer { bytesPtr in let validBytesCount = try bytes.withUnsafeBorrowedBuffer { bytesPtr in
return try invokeFnReturningInteger { try invokeFnReturningInteger {
return signal_validating_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length)) signal_validating_mac_update($0, unsafeNativeHandle, bytesPtr, 0, UInt32(bytesPtr.length))
} }
} }
if validBytesCount < 0 { if validBytesCount < 0 {
@ -91,7 +91,7 @@ public class ValidatingMacContext: NativeHandleOwner {
public func finalize() throws -> UInt32 { public func finalize() throws -> UInt32 {
let validBytesCount = try invokeFnReturningInteger { let validBytesCount = try invokeFnReturningInteger {
return signal_validating_mac_finalize($0, unsafeNativeHandle) signal_validating_mac_finalize($0, unsafeNativeHandle)
} }
if validBytesCount < 0 { if validBytesCount < 0 {
throw SignalError.verificationFailed("Bad incremental MAC (finalize)") throw SignalError.verificationFailed("Bad incremental MAC (finalize)")

View File

@ -56,16 +56,16 @@ public class SignalInputStreamAdapter<Inner>: SignalInputStream where Inner: Col
} }
public func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int { public func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int {
let amount = min(buffer.count, inner.count) let amount = min(buffer.count, self.inner.count)
buffer.copyBytes(from: inner.prefix(amount)) buffer.copyBytes(from: self.inner.prefix(amount))
inner = inner.dropFirst(amount) self.inner = self.inner.dropFirst(amount)
return amount return amount
} }
public func skip(by amount: UInt64) throws { public func skip(by amount: UInt64) throws {
if amount > UInt64(inner.count) { if amount > UInt64(self.inner.count) {
throw SignalInputStreamError.unexpectedEof throw SignalInputStreamError.unexpectedEof
} }
inner = inner.dropFirst(Int(amount)) self.inner = self.inner.dropFirst(Int(amount))
} }
} }

View File

@ -7,10 +7,12 @@ import Foundation
import SignalFfi import SignalFfi
internal func withInputStream<Result>(_ stream: SignalInputStream, _ body: (UnsafePointer<SignalFfi.SignalInputStream>) throws -> Result) throws -> Result { internal func withInputStream<Result>(_ stream: SignalInputStream, _ body: (UnsafePointer<SignalFfi.SignalInputStream>) throws -> Result) throws -> Result {
func ffiShimRead(stream_ctx: UnsafeMutableRawPointer?, func ffiShimRead(
stream_ctx: UnsafeMutableRawPointer?,
pBuf: UnsafeMutablePointer<UInt8>?, pBuf: UnsafeMutablePointer<UInt8>?,
bufLen: Int, bufLen: Int,
pAmountRead: UnsafeMutablePointer<Int>?) -> Int32 { pAmountRead: UnsafeMutablePointer<Int>?
) -> Int32 {
let streamContext = stream_ctx!.assumingMemoryBound(to: ErrorHandlingContext<SignalInputStream>.self) let streamContext = stream_ctx!.assumingMemoryBound(to: ErrorHandlingContext<SignalInputStream>.self)
return streamContext.pointee.catchCallbackErrors { stream in return streamContext.pointee.catchCallbackErrors { stream in
let buf = UnsafeMutableRawBufferPointer(start: pBuf, count: bufLen) let buf = UnsafeMutableRawBufferPointer(start: pBuf, count: bufLen)
@ -32,7 +34,8 @@ internal func withInputStream<Result>(_ stream: SignalInputStream, _ body: (Unsa
var ffiStream = SignalFfi.SignalInputStream( var ffiStream = SignalFfi.SignalInputStream(
ctx: $0, ctx: $0,
read: ffiShimRead as SignalRead, read: ffiShimRead as SignalRead,
skip: ffiShimSkip as SignalSkip) skip: ffiShimSkip as SignalSkip
)
return try body(&ffiStream) return try body(&ffiStream)
} }
} }

View File

@ -3,24 +3,27 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public func hkdf<InputBytes, SaltBytes, InfoBytes>(outputLength: Int, public func hkdf(
inputKeyMaterial: InputBytes, outputLength: Int,
salt: SaltBytes, inputKeyMaterial: some ContiguousBytes,
info: InfoBytes) throws -> [UInt8] salt: some ContiguousBytes,
where InputBytes: ContiguousBytes, SaltBytes: ContiguousBytes, InfoBytes: ContiguousBytes { info: some ContiguousBytes
) throws -> [UInt8] {
var output = Array(repeating: UInt8(0x00), count: outputLength) var output = Array(repeating: UInt8(0x00), count: outputLength)
try output.withUnsafeMutableBytes { outputBuffer in try output.withUnsafeMutableBytes { outputBuffer in
try inputKeyMaterial.withUnsafeBorrowedBuffer { inputBuffer in try inputKeyMaterial.withUnsafeBorrowedBuffer { inputBuffer in
try salt.withUnsafeBorrowedBuffer { saltBuffer in try salt.withUnsafeBorrowedBuffer { saltBuffer in
try info.withUnsafeBorrowedBuffer { infoBuffer in try info.withUnsafeBorrowedBuffer { infoBuffer in
try checkError(signal_hkdf_derive(.init(outputBuffer), try checkError(signal_hkdf_derive(
.init(outputBuffer),
inputBuffer, inputBuffer,
infoBuffer, infoBuffer,
saltBuffer)) saltBuffer
))
} }
} }
} }
@ -30,15 +33,18 @@ where InputBytes: ContiguousBytes, SaltBytes: ContiguousBytes, InfoBytes: Contig
} }
@available(*, deprecated, message: "Remove the 'version' parameter for standard HKDF behavior") @available(*, deprecated, message: "Remove the 'version' parameter for standard HKDF behavior")
public func hkdf<InputBytes, SaltBytes, InfoBytes>(outputLength: Int, public func hkdf(
outputLength: Int,
version: UInt32, version: UInt32,
inputKeyMaterial: InputBytes, inputKeyMaterial: some ContiguousBytes,
salt: SaltBytes, salt: some ContiguousBytes,
info: InfoBytes) throws -> [UInt8] info: some ContiguousBytes
where InputBytes: ContiguousBytes, SaltBytes: ContiguousBytes, InfoBytes: ContiguousBytes { ) throws -> [UInt8] {
precondition(version == 3, "HKDF versions other than 3 are no longer supported") precondition(version == 3, "HKDF versions other than 3 are no longer supported")
return try hkdf(outputLength: outputLength, return try hkdf(
outputLength: outputLength,
inputKeyMaterial: inputKeyMaterial, inputKeyMaterial: inputKeyMaterial,
salt: salt, salt: salt,
info: info) info: info
)
} }

View File

@ -3,11 +3,10 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class KEMKeyPair: ClonableHandleOwner { public class KEMKeyPair: ClonableHandleOwner {
public static func generate() -> KEMKeyPair { public static func generate() -> KEMKeyPair {
return failOnError { return failOnError {
try invokeFnReturningNativeHandle { 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) 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) return signal_kyber_key_pair_destroy(handle)
} }
@ -55,11 +54,11 @@ public class KEMPublicKey: ClonableHandleOwner {
self.init(owned: handle!) 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) 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) return signal_kyber_public_key_destroy(handle)
} }
@ -96,11 +95,11 @@ public class KEMSecretKey: ClonableHandleOwner {
self.init(owned: handle!) 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) 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) return signal_kyber_secret_key_destroy(handle)
} }

View File

@ -74,11 +74,11 @@ public func sanitizeWebp(input: SignalInputStream, length ignored: UInt64) throw
} }
public class SanitizedMetadata: ClonableHandleOwner { 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) 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) return signal_sanitized_metadata_destroy(handle)
} }

View File

@ -23,10 +23,9 @@ public class MessageBackupKey: NativeHandleOwner {
super.init(owned: handle) super.init(owned: handle)
} }
internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? {
signal_message_backup_key_destroy(handle) signal_message_backup_key_destroy(handle)
} }
} }
/// Validates a message backup file. /// Validates a message backup file.
@ -93,7 +92,7 @@ private class ValidationOutcome: NativeHandleOwner {
} }
} }
internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? {
signal_message_backup_validation_outcome_destroy(handle) signal_message_backup_validation_outcome_destroy(handle)
} }
} }

View File

@ -16,7 +16,7 @@ public class NativeHandleOwner {
/// You should probably use `withNativeHandle(_:)` /// You should probably use `withNativeHandle(_:)`
/// unless you can't use block scoping to keep the owner (`self`) alive. /// unless you can't use block scoping to keep the owner (`self`) alive.
internal var unsafeNativeHandle: OpaquePointer? { internal var unsafeNativeHandle: OpaquePointer? {
switch handle { switch self.handle {
case nil: case nil:
return nil return nil
case .borrowed(let handle)?: 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) self.handle = .owned(handle)
} }
@ -34,7 +34,7 @@ public class NativeHandleOwner {
self.handle = handle.map { .borrowed($0) } 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") fatalError("must be implemented by subclasses")
} }
@ -61,7 +61,7 @@ public class NativeHandleOwner {
} }
@available(*, unavailable, message: "use the method form instead") @available(*, unavailable, message: "use the method form instead")
internal func withNativeHandle<Result>(_ a: NativeHandleOwner, _ callback: (OpaquePointer?) throws -> Result) rethrows -> Result { internal func withNativeHandle<Result>(_: NativeHandleOwner, _: (OpaquePointer?) throws -> Result) rethrows -> Result {
fatalError() fatalError()
} }
@ -96,11 +96,11 @@ internal func withNativeHandles<Result>(_ a: NativeHandleOwner, _ b: NativeHandl
} }
public class ClonableHandleOwner: NativeHandleOwner { public class ClonableHandleOwner: NativeHandleOwner {
required internal init(owned handle: OpaquePointer) { internal required init(owned handle: OpaquePointer) {
super.init(owned: handle) super.init(owned: handle)
} }
internal override init(borrowing handle: OpaquePointer?) { override internal init(borrowing handle: OpaquePointer?) {
super.init(borrowing: handle) super.init(borrowing: handle)
} }

View File

@ -91,15 +91,15 @@ public class Net {
) async throws -> CdsiLookup { ) async throws -> CdsiLookup {
let timeoutMs = durationToMillis(timeout) let timeoutMs = durationToMillis(timeout)
let handle: OpaquePointer = try await invokeAsyncFunction { promise, context in let handle: OpaquePointer = try await invokeAsyncFunction { promise, context in
asyncContext.withNativeHandle { asyncContext in self.asyncContext.withNativeHandle { asyncContext in
connectionManager.withNativeHandle { connectionManager in self.connectionManager.withNativeHandle { connectionManager in
request.withNativeHandle { request in request.withNativeHandle { request in
signal_cdsi_lookup_new(promise, context, asyncContext, connectionManager, auth.username, auth.password, request, timeoutMs) 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 private var asyncContext: TokioAsyncContext
@ -150,7 +150,8 @@ public class CdsiLookupRequest: NativeHandleOwner {
prevE164s: [String], prevE164s: [String],
acisAndAccessKeys: [AciAndAccessKey], acisAndAccessKeys: [AciAndAccessKey],
token: Data?, token: Data?,
returnAcisWithoutUaks: Bool) throws { returnAcisWithoutUaks: Bool
) throws {
self.init() self.init()
try self.withNativeHandle { handle in try self.withNativeHandle { handle in
for e164 in e164s { 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) 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. /// Returned by ``Net/cdsiLookup(auth:request:timeout:)`` when a request is successfully initiated.
public class CdsiLookup { public class CdsiLookup {
class NativeCdsiLookup: NativeHandleOwner { class NativeCdsiLookup: NativeHandleOwner {
internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? { override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? {
signal_cdsi_lookup_destroy(handle) signal_cdsi_lookup_destroy(handle)
} }
} }
@ -212,7 +213,7 @@ public class CdsiLookup {
/// numbers. /// numbers.
public var token: Data { public var token: Data {
failOnError { failOnError {
try native.withNativeHandle { handle in try self.native.withNativeHandle { handle in
try invokeFnReturningData { try invokeFnReturningData {
signal_cdsi_lookup_token($0, handle) signal_cdsi_lookup_token($0, handle)
} }
@ -232,8 +233,8 @@ public class CdsiLookup {
/// `SignalError.networkProtocolError` for a CDSI or attested connection protocol issue. /// `SignalError.networkProtocolError` for a CDSI or attested connection protocol issue.
public func complete() async throws -> CdsiLookupResponse { public func complete() async throws -> CdsiLookupResponse {
let response: SignalFfiCdsiLookupResponse = try await invokeAsyncFunction { promise, context in let response: SignalFfiCdsiLookupResponse = try await invokeAsyncFunction { promise, context in
asyncContext.withNativeHandle { asyncContext in self.asyncContext.withNativeHandle { asyncContext in
native.withNativeHandle { handle in self.native.withNativeHandle { handle in
signal_cdsi_lookup_complete(promise, context, asyncContext, handle) signal_cdsi_lookup_complete(promise, context, asyncContext, handle)
} }
} }
@ -336,7 +337,7 @@ internal class TokioAsyncContext: NativeHandleOwner {
self.init(owned: handle!) 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) signal_tokio_async_context_destroy(handle)
} }
} }
@ -348,7 +349,7 @@ internal class ConnectionManager: NativeHandleOwner {
self.init(owned: handle!) 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) signal_connection_manager_destroy(handle)
} }
} }

View File

@ -48,7 +48,7 @@ public func verifyLocalPin<Bytes: ContiguousBytes>(_ pin: Bytes, againstEncodedH
/// A hash of the pin that can be used to interact with a Secure Value Recovery service. /// A hash of the pin that can be used to interact with a Secure Value Recovery service.
public class PinHash: NativeHandleOwner { 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) return signal_pin_hash_destroy(handle)
} }
@ -83,7 +83,6 @@ public class PinHash: NativeHandleOwner {
/// - parameter salt: A 32 byte salt /// - parameter salt: A 32 byte salt
/// - returns: A `PinHash` /// - returns: A `PinHash`
public convenience init<PinBytes: ContiguousBytes, SaltBytes: ContiguousBytes>(normalizedPin: PinBytes, salt: SaltBytes) throws { public convenience init<PinBytes: ContiguousBytes, SaltBytes: ContiguousBytes>(normalizedPin: PinBytes, salt: SaltBytes) throws {
var result: OpaquePointer? var result: OpaquePointer?
try normalizedPin.withUnsafeBorrowedBuffer { pinBytes in try normalizedPin.withUnsafeBorrowedBuffer { pinBytes in
try salt.withUnsafeBytes { saltBytes in try salt.withUnsafeBytes { saltBytes in
@ -114,5 +113,4 @@ public class PinHash: NativeHandleOwner {
} }
self.init(owned: result!) self.init(owned: result!)
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class PrivateKey: ClonableHandleOwner { public class PrivateKey: ClonableHandleOwner {
public convenience init<Bytes: ContiguousBytes>(_ bytes: Bytes) throws { public convenience init<Bytes: ContiguousBytes>(_ 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) 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) return signal_privatekey_destroy(handle)
} }
@ -73,5 +73,4 @@ public class PrivateKey: ClonableHandleOwner {
} }
} }
} }
} }

View File

@ -3,15 +3,17 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public func signalEncrypt<Bytes: ContiguousBytes>(message: Bytes, public func signalEncrypt<Bytes: ContiguousBytes>(
message: Bytes,
for address: ProtocolAddress, for address: ProtocolAddress,
sessionStore: SessionStore, sessionStore: SessionStore,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
now: Date = Date(), now: Date = Date(),
context: StoreContext) throws -> CiphertextMessage { context: StoreContext
) throws -> CiphertextMessage {
return try address.withNativeHandle { addressHandle in return try address.withNativeHandle { addressHandle in
try message.withUnsafeBorrowedBuffer { messageBuffer in try message.withUnsafeBorrowedBuffer { messageBuffer in
try withSessionStore(sessionStore, context) { ffiSessionStore in try withSessionStore(sessionStore, context) { ffiSessionStore in
@ -25,11 +27,13 @@ public func signalEncrypt<Bytes: ContiguousBytes>(message: Bytes,
} }
} }
public func signalDecrypt(message: SignalMessage, public func signalDecrypt(
message: SignalMessage,
from address: ProtocolAddress, from address: ProtocolAddress,
sessionStore: SessionStore, sessionStore: SessionStore,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
context: StoreContext) throws -> [UInt8] { context: StoreContext
) throws -> [UInt8] {
return try withNativeHandles(message, address) { messageHandle, addressHandle in return try withNativeHandles(message, address) { messageHandle, addressHandle in
try withSessionStore(sessionStore, context) { ffiSessionStore in try withSessionStore(sessionStore, context) { ffiSessionStore in
try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in
@ -41,14 +45,16 @@ public func signalDecrypt(message: SignalMessage,
} }
} }
public func signalDecryptPreKey(message: PreKeySignalMessage, public func signalDecryptPreKey(
message: PreKeySignalMessage,
from address: ProtocolAddress, from address: ProtocolAddress,
sessionStore: SessionStore, sessionStore: SessionStore,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
preKeyStore: PreKeyStore, preKeyStore: PreKeyStore,
signedPreKeyStore: SignedPreKeyStore, signedPreKeyStore: SignedPreKeyStore,
kyberPreKeyStore: KyberPreKeyStore, kyberPreKeyStore: KyberPreKeyStore,
context: StoreContext) throws -> [UInt8] { context: StoreContext
) throws -> [UInt8] {
return try withNativeHandles(message, address) { messageHandle, addressHandle in return try withNativeHandles(message, address) { messageHandle, addressHandle in
try withSessionStore(sessionStore, context) { ffiSessionStore in try withSessionStore(sessionStore, context) { ffiSessionStore in
try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in
@ -66,12 +72,14 @@ public func signalDecryptPreKey(message: PreKeySignalMessage,
} }
} }
public func processPreKeyBundle(_ bundle: PreKeyBundle, public func processPreKeyBundle(
_ bundle: PreKeyBundle,
for address: ProtocolAddress, for address: ProtocolAddress,
sessionStore: SessionStore, sessionStore: SessionStore,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
now: Date = Date(), now: Date = Date(),
context: StoreContext) throws { context: StoreContext
) throws {
return try withNativeHandles(bundle, address) { bundleHandle, addressHandle in return try withNativeHandles(bundle, address) { bundleHandle, addressHandle in
try withSessionStore(sessionStore, context) { ffiSessionStore in try withSessionStore(sessionStore, context) { ffiSessionStore in
try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in
@ -81,11 +89,13 @@ public func processPreKeyBundle(_ bundle: PreKeyBundle,
} }
} }
public func groupEncrypt<Bytes: ContiguousBytes>(_ message: Bytes, public func groupEncrypt<Bytes: ContiguousBytes>(
_ message: Bytes,
from sender: ProtocolAddress, from sender: ProtocolAddress,
distributionId: UUID, distributionId: UUID,
store: SenderKeyStore, store: SenderKeyStore,
context: StoreContext) throws -> CiphertextMessage { context: StoreContext
) throws -> CiphertextMessage {
return try sender.withNativeHandle { senderHandle in return try sender.withNativeHandle { senderHandle in
try message.withUnsafeBorrowedBuffer { messageBuffer in try message.withUnsafeBorrowedBuffer { messageBuffer in
try withUnsafePointer(to: distributionId.uuid) { distributionId in try withUnsafePointer(to: distributionId.uuid) { distributionId in
@ -99,10 +109,12 @@ public func groupEncrypt<Bytes: ContiguousBytes>(_ message: Bytes,
} }
} }
public func groupDecrypt<Bytes: ContiguousBytes>(_ message: Bytes, public func groupDecrypt<Bytes: ContiguousBytes>(
_ message: Bytes,
from sender: ProtocolAddress, from sender: ProtocolAddress,
store: SenderKeyStore, store: SenderKeyStore,
context: StoreContext) throws -> [UInt8] { context: StoreContext
) throws -> [UInt8] {
return try sender.withNativeHandle { senderHandle in return try sender.withNativeHandle { senderHandle in
try message.withUnsafeBorrowedBuffer { messageBuffer in try message.withUnsafeBorrowedBuffer { messageBuffer in
try withSenderKeyStore(store, context) { ffiStore in try withSenderKeyStore(store, context) { ffiStore in
@ -114,15 +126,19 @@ public func groupDecrypt<Bytes: ContiguousBytes>(_ message: Bytes,
} }
} }
public func processSenderKeyDistributionMessage(_ message: SenderKeyDistributionMessage, public func processSenderKeyDistributionMessage(
_ message: SenderKeyDistributionMessage,
from sender: ProtocolAddress, from sender: ProtocolAddress,
store: SenderKeyStore, store: SenderKeyStore,
context: StoreContext) throws { context: StoreContext
) throws {
return try withNativeHandles(sender, message) { senderHandle, messageHandle in return try withNativeHandles(sender, message) { senderHandle, messageHandle in
try withSenderKeyStore(store, context) { try withSenderKeyStore(store, context) {
try checkError(signal_process_sender_key_distribution_message(senderHandle, try checkError(signal_process_sender_key_distribution_message(
senderHandle,
messageHandle, messageHandle,
$0)) $0
))
} }
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class PublicKey: ClonableHandleOwner { public class PublicKey: ClonableHandleOwner {
public convenience init<Bytes: ContiguousBytes>(_ bytes: Bytes) throws { public convenience init<Bytes: ContiguousBytes>(_ bytes: Bytes) throws {
@ -16,11 +16,11 @@ public class PublicKey: ClonableHandleOwner {
self.init(owned: handle!) 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) 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) return signal_publickey_clone(&newHandle, currentHandle)
} }
@ -44,9 +44,8 @@ public class PublicKey: ClonableHandleOwner {
} }
} }
public func verifySignature<MessageBytes, SignatureBytes>(message: MessageBytes, signature: SignatureBytes) throws -> Bool public func verifySignature(message: some ContiguousBytes, signature: some ContiguousBytes) throws -> Bool {
where MessageBytes: ContiguousBytes, SignatureBytes: ContiguousBytes { var result = false
var result: Bool = false
try withNativeHandle { nativeHandle in try withNativeHandle { nativeHandle in
try message.withUnsafeBorrowedBuffer { messageBuffer in try message.withUnsafeBorrowedBuffer { messageBuffer in
try signature.withUnsafeBorrowedBuffer { signatureBuffer in try signature.withUnsafeBorrowedBuffer { signatureBuffer in

View File

@ -3,26 +3,32 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
@inlinable @inlinable
public func sealedSenderEncrypt<Bytes: ContiguousBytes>(message: Bytes, public func sealedSenderEncrypt<Bytes: ContiguousBytes>(
message: Bytes,
for address: ProtocolAddress, for address: ProtocolAddress,
from senderCert: SenderCertificate, from senderCert: SenderCertificate,
sessionStore: SessionStore, sessionStore: SessionStore,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
context: StoreContext) throws -> [UInt8] { context: StoreContext
let ciphertextMessage = try signalEncrypt(message: message, ) throws -> [UInt8] {
let ciphertextMessage = try signalEncrypt(
message: message,
for: address, for: address,
sessionStore: sessionStore, sessionStore: sessionStore,
identityStore: identityStore, identityStore: identityStore,
context: context) context: context
)
let usmc = try UnidentifiedSenderMessageContent(ciphertextMessage, let usmc = try UnidentifiedSenderMessageContent(
ciphertextMessage,
from: senderCert, from: senderCert,
contentHint: .default, contentHint: .default,
groupId: []) groupId: []
)
return try sealedSenderEncrypt(usmc, for: address, identityStore: identityStore, context: context) return try sealedSenderEncrypt(usmc, for: address, identityStore: identityStore, context: context)
} }
@ -41,17 +47,21 @@ public class UnidentifiedSenderMessageContent: NativeHandleOwner {
public static var `default`: Self { public static var `default`: Self {
return Self(SignalContentHintDefault) return Self(SignalContentHintDefault)
} }
public static var resendable: Self { public static var resendable: Self {
return Self(SignalContentHintResendable) return Self(SignalContentHintResendable)
} }
public static var implicit: Self { public static var implicit: Self {
return Self(SignalContentHintImplicit) return Self(SignalContentHintImplicit)
} }
} }
public convenience init<Bytes: ContiguousBytes>(message sealedSenderMessage: Bytes, public convenience init<Bytes: ContiguousBytes>(
message sealedSenderMessage: Bytes,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
context: StoreContext) throws { context: StoreContext
) throws {
var result: OpaquePointer? var result: OpaquePointer?
try sealedSenderMessage.withUnsafeBorrowedBuffer { messageBuffer in try sealedSenderMessage.withUnsafeBorrowedBuffer { messageBuffer in
try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in
@ -59,31 +69,36 @@ public class UnidentifiedSenderMessageContent: NativeHandleOwner {
signal_sealed_session_cipher_decrypt_to_usmc( signal_sealed_session_cipher_decrypt_to_usmc(
&result, &result,
messageBuffer, messageBuffer,
ffiIdentityStore)) ffiIdentityStore
))
} }
} }
self.init(owned: result!) self.init(owned: result!)
} }
public convenience init<GroupIdBytes: ContiguousBytes>(_ message: CiphertextMessage, public convenience init<GroupIdBytes: ContiguousBytes>(
_ message: CiphertextMessage,
from sender: SenderCertificate, from sender: SenderCertificate,
contentHint: ContentHint, contentHint: ContentHint,
groupId: GroupIdBytes) throws { groupId: GroupIdBytes
) throws {
var result: OpaquePointer? var result: OpaquePointer?
try withNativeHandles(message, sender) { messageHandle, senderHandle in try withNativeHandles(message, sender) { messageHandle, senderHandle in
try groupId.withUnsafeBorrowedBuffer { groupIdBuffer in try groupId.withUnsafeBorrowedBuffer { groupIdBuffer in
try checkError( try checkError(
signal_unidentified_sender_message_content_new(&result, signal_unidentified_sender_message_content_new(
&result,
messageHandle, messageHandle,
senderHandle, senderHandle,
contentHint.rawValue, contentHint.rawValue,
groupIdBuffer)) groupIdBuffer
))
} }
} }
self.init(owned: result!) 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) return signal_unidentified_sender_message_content_destroy(handle)
} }
@ -144,28 +159,34 @@ public class UnidentifiedSenderMessageContent: NativeHandleOwner {
} }
} }
public func sealedSenderEncrypt(_ content: UnidentifiedSenderMessageContent, public func sealedSenderEncrypt(
_ content: UnidentifiedSenderMessageContent,
for recipient: ProtocolAddress, for recipient: ProtocolAddress,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
context: StoreContext) throws -> [UInt8] { context: StoreContext
) throws -> [UInt8] {
return try withNativeHandles(recipient, content) { recipientHandle, contentHandle in return try withNativeHandles(recipient, content) { recipientHandle, contentHandle in
try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in
try invokeFnReturningArray { try invokeFnReturningArray {
signal_sealed_session_cipher_encrypt($0, signal_sealed_session_cipher_encrypt(
$0,
recipientHandle, recipientHandle,
contentHandle, contentHandle,
ffiIdentityStore) ffiIdentityStore
)
} }
} }
} }
} }
public func sealedSenderMultiRecipientEncrypt(_ content: UnidentifiedSenderMessageContent, public func sealedSenderMultiRecipientEncrypt(
_ content: UnidentifiedSenderMessageContent,
for recipients: [ProtocolAddress], for recipients: [ProtocolAddress],
excludedRecipients: [ServiceId] = [], excludedRecipients: [ServiceId] = [],
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
sessionStore: SessionStore, sessionStore: SessionStore,
context: StoreContext) throws -> [UInt8] { context: StoreContext
) throws -> [UInt8] {
let sessions = try sessionStore.loadExistingSessions(for: recipients, context: context) let sessions = try sessionStore.loadExistingSessions(for: recipients, context: context)
// Use withExtendedLifetime instead of withNativeHandle for the arrays of wrapper objects, // Use withExtendedLifetime instead of withNativeHandle for the arrays of wrapper objects,
// which aren't compatible with withNativeHandle's simple lexical scoping. // 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 recipientHandles = recipients.map { $0.unsafeNativeHandle }
let sessionHandles = sessions.map { $0.unsafeNativeHandle } let sessionHandles = sessions.map { $0.unsafeNativeHandle }
return try content.withNativeHandle { contentHandle in 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) let recipientHandlesBuffer = SignalBorrowedSliceOfProtocolAddress(base: recipientHandles.baseAddress, length: recipientHandles.count)
return try sessionHandles.withUnsafeBufferPointer { sessionHandles in return try sessionHandles.withUnsafeBufferPointer { sessionHandles in
let sessionHandlesBuffer = SignalBorrowedSliceOfSessionRecord(base: sessionHandles.baseAddress, length: sessionHandles.count) let sessionHandlesBuffer = SignalBorrowedSliceOfSessionRecord(base: sessionHandles.baseAddress, length: sessionHandles.count)
return try ServiceId.concatenatedFixedWidthBinary(excludedRecipients).withUnsafeBorrowedBuffer { excludedRecipientsBuffer in return try ServiceId.concatenatedFixedWidthBinary(excludedRecipients).withUnsafeBorrowedBuffer { excludedRecipientsBuffer in
return try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in try withIdentityKeyStore(identityStore, context) { ffiIdentityStore in
try invokeFnReturningArray { try invokeFnReturningArray {
signal_sealed_sender_multi_recipient_encrypt($0, signal_sealed_sender_multi_recipient_encrypt(
$0,
recipientHandlesBuffer, recipientHandlesBuffer,
sessionHandlesBuffer, sessionHandlesBuffer,
excludedRecipientsBuffer, excludedRecipientsBuffer,
contentHandle, contentHandle,
ffiIdentityStore) ffiIdentityStore
)
} }
} }
} }
@ -225,7 +248,7 @@ public struct SealedSenderAddress: Hashable {
/// ///
/// In a future release SealedSenderAddress will *only* support ACIs. /// In a future release SealedSenderAddress will *only* support ACIs.
public var senderAci: Aci! { public var senderAci: Aci! {
return try? Aci.parseFrom(serviceIdString: uuidString) return try? Aci.parseFrom(serviceIdString: self.uuidString)
} }
} }
@ -234,7 +257,8 @@ public struct SealedSenderResult {
public var sender: SealedSenderAddress public var sender: SealedSenderAddress
} }
public func sealedSenderDecrypt<Bytes: ContiguousBytes>(message: Bytes, public func sealedSenderDecrypt<Bytes: ContiguousBytes>(
message: Bytes,
from localAddress: SealedSenderAddress, from localAddress: SealedSenderAddress,
trustRoot: PublicKey, trustRoot: PublicKey,
timestamp: UInt64, timestamp: UInt64,
@ -242,7 +266,8 @@ public func sealedSenderDecrypt<Bytes: ContiguousBytes>(message: Bytes,
identityStore: IdentityKeyStore, identityStore: IdentityKeyStore,
preKeyStore: PreKeyStore, preKeyStore: PreKeyStore,
signedPreKeyStore: SignedPreKeyStore, signedPreKeyStore: SignedPreKeyStore,
context: StoreContext) throws -> SealedSenderResult { context: StoreContext
) throws -> SealedSenderResult {
var senderE164: UnsafePointer<CChar>? var senderE164: UnsafePointer<CChar>?
var senderUUID: UnsafePointer<CChar>? var senderUUID: UnsafePointer<CChar>?
var senderDeviceId: UInt32 = 0 var senderDeviceId: UInt32 = 0
@ -268,7 +293,8 @@ public func sealedSenderDecrypt<Bytes: ContiguousBytes>(message: Bytes,
ffiSessionStore, ffiSessionStore,
ffiIdentityStore, ffiIdentityStore,
ffiPreKeyStore, ffiPreKeyStore,
ffiSignedPreKeyStore) ffiSignedPreKeyStore
)
} }
} }
} }
@ -282,8 +308,12 @@ public func sealedSenderDecrypt<Bytes: ContiguousBytes>(message: Bytes,
signal_free_string(senderUUID) signal_free_string(senderUUID)
} }
return SealedSenderResult(message: plaintext, return SealedSenderResult(
sender: try SealedSenderAddress(e164: senderE164.map(String.init(cString:)), message: plaintext,
sender: try SealedSenderAddress(
e164: senderE164.map(String.init(cString:)),
uuidString: String(cString: senderUUID!), uuidString: String(cString: senderUUID!),
deviceId: senderDeviceId)) deviceId: senderDeviceId
)
)
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class ServerCertificate: NativeHandleOwner { public class ServerCertificate: NativeHandleOwner {
public convenience init<Bytes: ContiguousBytes>(_ bytes: Bytes) throws { public convenience init<Bytes: ContiguousBytes>(_ bytes: Bytes) throws {
@ -25,7 +25,7 @@ public class ServerCertificate: NativeHandleOwner {
self.init(owned: result!) 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) 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 { public convenience init(sender: SealedSenderAddress, publicKey: PublicKey, expiration: UInt64, signerCertificate: ServerCertificate, signerKey: PrivateKey) throws {
var result: OpaquePointer? var result: OpaquePointer?
try withNativeHandles(publicKey, signerCertificate, signerKey) { publicKeyHandle, signerCertificateHandle, signerKeyHandle in try withNativeHandles(publicKey, signerCertificate, signerKey) { publicKeyHandle, signerCertificateHandle, signerKeyHandle in
try checkError(signal_sender_certificate_new(&result, try checkError(signal_sender_certificate_new(
&result,
sender.uuidString, sender.uuidString,
sender.e164, sender.e164,
sender.deviceId, sender.deviceId,
publicKeyHandle, publicKeyHandle,
expiration, expiration,
signerCertificateHandle, signerCertificateHandle,
signerKeyHandle)) signerKeyHandle
))
} }
self.init(owned: result!) 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) return signal_sender_certificate_destroy(handle)
} }
@ -184,7 +186,7 @@ public class SenderCertificate: NativeHandleOwner {
/// ///
/// In a future release SenderCertificate will *only* support ACIs. /// In a future release SenderCertificate will *only* support ACIs.
public var senderAci: Aci! { public var senderAci: Aci! {
return try? Aci.parseFrom(serviceIdString: senderUuid) return try? Aci.parseFrom(serviceIdString: self.senderUuid)
} }
public var senderE164: String? { public var senderE164: String? {
@ -214,7 +216,7 @@ public class SenderCertificate: NativeHandleOwner {
} }
public func validate(trustRoot: PublicKey, time: UInt64) throws -> Bool { public func validate(trustRoot: PublicKey, time: UInt64) throws -> Bool {
var result: Bool = false var result = false
try withNativeHandles(self, trustRoot) { certificateHandle, trustRootHandle in try withNativeHandles(self, trustRoot) { certificateHandle, trustRootHandle in
try checkError(signal_sender_certificate_validate(&result, certificateHandle, trustRootHandle, time)) try checkError(signal_sender_certificate_validate(&result, certificateHandle, trustRootHandle, time))
} }

View File

@ -43,7 +43,7 @@ public enum ServiceIdError: Error {
} }
public class ServiceId { 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) { fileprivate init(fromFixedWidthBinary storage: ServiceIdStorage) {
self.storage = storage self.storage = storage
@ -187,7 +187,7 @@ public class Aci: ServiceId {
super.init(.aci, uuid) super.init(.aci, uuid)
} }
internal override init(fromFixedWidthBinary bytes: ServiceIdStorage) { override internal init(fromFixedWidthBinary bytes: ServiceIdStorage) {
super.init(fromFixedWidthBinary: bytes) super.init(fromFixedWidthBinary: bytes)
} }
} }
@ -197,7 +197,7 @@ public class Pni: ServiceId {
super.init(.pni, uuid) super.init(.pni, uuid)
} }
internal override init(fromFixedWidthBinary bytes: ServiceIdStorage) { override internal init(fromFixedWidthBinary bytes: ServiceIdStorage) {
super.init(fromFixedWidthBinary: bytes) super.init(fromFixedWidthBinary: bytes)
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
/// ///
/// SgxClient provides bindings to interact with a Signal SGX service /// 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. /// which decrypts and verifies it, passing the plaintext back to the client for processing.
/// ///
public class SgxClient: NativeHandleOwner { public class SgxClient: NativeHandleOwner {
override internal class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? {
internal override class func destroyNativeHandle(_ handle: OpaquePointer) -> SignalFfiErrorRef? {
return signal_sgx_client_state_destroy(handle) return signal_sgx_client_state_destroy(handle)
} }

View File

@ -11,15 +11,20 @@ import SignalFfi
/// ///
/// See ``SgxClient`` /// See ``SgxClient``
public class Svr2Client: SgxClient { public class Svr2Client: SgxClient {
public convenience init<MrenclaveBytes, AttestationBytes>(mrenclave: MrenclaveBytes, attestationMessage: AttestationBytes, currentDate: Date) throws public convenience init(
where MrenclaveBytes: ContiguousBytes, AttestationBytes: ContiguousBytes { mrenclave: some ContiguousBytes,
attestationMessage: some ContiguousBytes,
currentDate: Date
) throws {
let handle: OpaquePointer? = try attestationMessage.withUnsafeBorrowedBuffer { attestationMessageBuffer in let handle: OpaquePointer? = try attestationMessage.withUnsafeBorrowedBuffer { attestationMessageBuffer in
try mrenclave.withUnsafeBorrowedBuffer { mrenclaveBuffer in try mrenclave.withUnsafeBorrowedBuffer { mrenclaveBuffer in
var result: OpaquePointer? var result: OpaquePointer?
try checkError(signal_svr2_client_new(&result, try checkError(signal_svr2_client_new(
&result,
mrenclaveBuffer, mrenclaveBuffer,
attestationMessageBuffer, attestationMessageBuffer,
UInt64(currentDate.timeIntervalSince1970 * 1000))) UInt64(currentDate.timeIntervalSince1970 * 1000)
))
return result return result
} }
} }

View File

@ -62,7 +62,7 @@ public struct Username {
public func createLink(previousEntropy: [UInt8]? = nil) throws -> ([UInt8], [UInt8]) { public func createLink(previousEntropy: [UInt8]? = nil) throws -> ([UInt8], [UInt8]) {
let bytes = failOnError { let bytes = failOnError {
return try self.value.withCString { usernamePtr in try self.value.withCString { usernamePtr in
try (previousEntropy ?? []).withUnsafeBorrowedBuffer { entropyPtr in try (previousEntropy ?? []).withUnsafeBorrowedBuffer { entropyPtr in
try invokeFnReturningArray { try invokeFnReturningArray {
signal_username_link_create($0, usernamePtr, entropyPtr) signal_username_link_create($0, usernamePtr, entropyPtr)
@ -98,7 +98,7 @@ public struct Username {
extension Username: CustomStringConvertible { extension Username: CustomStringConvertible {
public var description: String { public var description: String {
return value return self.value
} }
} }

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
#if canImport(Security) #if canImport(Security)
import Security import Security
@ -114,7 +114,7 @@ internal func invokeFnReturningInteger<Result: FixedWidthInteger>(fn: (UnsafeMut
} }
internal func invokeFnReturningBool(fn: (UnsafeMutablePointer<Bool>?) -> SignalFfiErrorRef?) throws -> Bool { internal func invokeFnReturningBool(fn: (UnsafeMutablePointer<Bool>?) -> SignalFfiErrorRef?) throws -> Bool {
var output: Bool = false var output = false
try checkError(fn(&output)) try checkError(fn(&output))
return output return output
} }

View File

@ -19,18 +19,21 @@ public class CiphertextMessage: NativeHandleOwner {
public static var whisper: Self { public static var whisper: Self {
return Self(SignalCiphertextMessageTypeWhisper) return Self(SignalCiphertextMessageTypeWhisper)
} }
public static var preKey: Self { public static var preKey: Self {
return Self(SignalCiphertextMessageTypePreKey) return Self(SignalCiphertextMessageTypePreKey)
} }
public static var senderKey: Self { public static var senderKey: Self {
return Self(SignalCiphertextMessageTypeSenderKey) return Self(SignalCiphertextMessageTypeSenderKey)
} }
public static var plaintext: Self { public static var plaintext: Self {
return Self(SignalCiphertextMessageTypePlaintext) 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) return signal_ciphertext_message_destroy(handle)
} }

View File

@ -3,11 +3,11 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class PlaintextContent: NativeHandleOwner { 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) return signal_plaintext_content_destroy(handle)
} }
@ -49,7 +49,7 @@ public class PlaintextContent: NativeHandleOwner {
} }
public class DecryptionErrorMessage: 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) return signal_decryption_error_message_destroy(handle)
} }

View File

@ -3,11 +3,11 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class PreKeySignalMessage: NativeHandleOwner { 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) 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 return nil
} else { } else {
return id return id

View File

@ -3,26 +3,30 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class SenderKeyDistributionMessage: NativeHandleOwner { 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) return signal_sender_key_distribution_message_destroy(handle)
} }
public convenience init(from sender: ProtocolAddress, public convenience init(
from sender: ProtocolAddress,
distributionId: UUID, distributionId: UUID,
store: SenderKeyStore, store: SenderKeyStore,
context: StoreContext) throws { context: StoreContext
) throws {
var result: OpaquePointer? var result: OpaquePointer?
try sender.withNativeHandle { senderHandle in try sender.withNativeHandle { senderHandle in
try withUnsafePointer(to: distributionId.uuid) { distributionId in try withUnsafePointer(to: distributionId.uuid) { distributionId in
try withSenderKeyStore(store, context) { try withSenderKeyStore(store, context) {
try checkError(signal_sender_key_distribution_message_create(&result, try checkError(signal_sender_key_distribution_message_create(
&result,
senderHandle, senderHandle,
distributionId, distributionId,
$0)) $0
))
} }
} }
} }

View File

@ -3,11 +3,11 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class SenderKeyMessage: NativeHandleOwner { 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) return signal_sender_key_message_destroy(handle)
} }
@ -70,7 +70,7 @@ public class SenderKeyMessage: NativeHandleOwner {
} }
public func verifySignature(against key: PublicKey) throws -> Bool { public func verifySignature(against key: PublicKey) throws -> Bool {
var result: Bool = false var result = false
try withNativeHandles(self, key) { messageHandle, keyHandle in try withNativeHandles(self, key) { messageHandle, keyHandle in
try checkError(signal_sender_key_message_verify_signature(&result, messageHandle, keyHandle)) try checkError(signal_sender_key_message_verify_signature(&result, messageHandle, keyHandle))
} }

View File

@ -3,11 +3,11 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class SignalMessage: NativeHandleOwner { 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) return signal_message_destroy(handle)
} }
@ -69,17 +69,21 @@ public class SignalMessage: NativeHandleOwner {
} }
} }
public func verifyMac<Bytes: ContiguousBytes>(sender: PublicKey, public func verifyMac<Bytes: ContiguousBytes>(
sender: PublicKey,
receiver: PublicKey, receiver: PublicKey,
macKey: Bytes) throws -> Bool { macKey: Bytes
) throws -> Bool {
return try withNativeHandles(self, sender, receiver) { messageHandle, senderHandle, receiverHandle in return try withNativeHandles(self, sender, receiver) { messageHandle, senderHandle, receiverHandle in
try macKey.withUnsafeBorrowedBuffer { try macKey.withUnsafeBorrowedBuffer {
var result: Bool = false var result: Bool = false
try checkError(signal_message_verify_mac(&result, try checkError(signal_message_verify_mac(
&result,
messageHandle, messageHandle,
senderHandle, senderHandle,
receiverHandle, receiverHandle,
$0)) $0
))
return result return result
} }
} }

View File

@ -3,15 +3,15 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class KyberPreKeyRecord: ClonableHandleOwner { 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) 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) return signal_kyber_pre_key_record_clone(&newHandle, currentHandle)
} }

View File

@ -3,28 +3,31 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class PreKeyBundle: NativeHandleOwner { 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) return signal_pre_key_bundle_destroy(handle)
} }
// with a prekey // with a prekey
public convenience init<Bytes: ContiguousBytes>(registrationId: UInt32, public convenience init<Bytes: ContiguousBytes>(
registrationId: UInt32,
deviceId: UInt32, deviceId: UInt32,
prekeyId: UInt32, prekeyId: UInt32,
prekey: PublicKey, prekey: PublicKey,
signedPrekeyId: UInt32, signedPrekeyId: UInt32,
signedPrekey: PublicKey, signedPrekey: PublicKey,
signedPrekeySignature: Bytes, signedPrekeySignature: Bytes,
identity identityKey: IdentityKey) throws { identity identityKey: IdentityKey
) throws {
var result: OpaquePointer? var result: OpaquePointer?
try withNativeHandles(prekey, signedPrekey, identityKey.publicKey) { prekeyHandle, signedPrekeyHandle, identityKeyHandle in try withNativeHandles(prekey, signedPrekey, identityKey.publicKey) { prekeyHandle, signedPrekeyHandle, identityKeyHandle in
try signedPrekeySignature.withUnsafeBorrowedBuffer { signedSignatureBuffer in try signedPrekeySignature.withUnsafeBorrowedBuffer { signedSignatureBuffer in
try [].withUnsafeBorrowedBuffer { kyberSignatureBuffer in try [].withUnsafeBorrowedBuffer { kyberSignatureBuffer in
try checkError(signal_pre_key_bundle_new(&result, try checkError(signal_pre_key_bundle_new(
&result,
registrationId, registrationId,
deviceId, deviceId,
prekeyId, prekeyId,
@ -35,7 +38,8 @@ public class PreKeyBundle: NativeHandleOwner {
identityKeyHandle, identityKeyHandle,
~0, ~0,
nil, nil,
kyberSignatureBuffer)) kyberSignatureBuffer
))
} }
} }
} }
@ -43,17 +47,20 @@ public class PreKeyBundle: NativeHandleOwner {
} }
// without a prekey // without a prekey
public convenience init<Bytes: ContiguousBytes>(registrationId: UInt32, public convenience init<Bytes: ContiguousBytes>(
registrationId: UInt32,
deviceId: UInt32, deviceId: UInt32,
signedPrekeyId: UInt32, signedPrekeyId: UInt32,
signedPrekey: PublicKey, signedPrekey: PublicKey,
signedPrekeySignature: Bytes, signedPrekeySignature: Bytes,
identity identityKey: IdentityKey) throws { identity identityKey: IdentityKey
) throws {
var result: OpaquePointer? var result: OpaquePointer?
try withNativeHandles(signedPrekey, identityKey.publicKey) { signedPrekeyHandle, identityKeyHandle in try withNativeHandles(signedPrekey, identityKey.publicKey) { signedPrekeyHandle, identityKeyHandle in
try signedPrekeySignature.withUnsafeBorrowedBuffer { signedSignatureBuffer in try signedPrekeySignature.withUnsafeBorrowedBuffer { signedSignatureBuffer in
try [].withUnsafeBorrowedBuffer { kyberSignatureBuffer in try [].withUnsafeBorrowedBuffer { kyberSignatureBuffer in
try checkError(signal_pre_key_bundle_new(&result, try checkError(signal_pre_key_bundle_new(
&result,
registrationId, registrationId,
deviceId, deviceId,
~0, ~0,
@ -64,7 +71,8 @@ public class PreKeyBundle: NativeHandleOwner {
identityKeyHandle, identityKeyHandle,
~0, ~0,
nil, nil,
kyberSignatureBuffer)) kyberSignatureBuffer
))
} }
} }
} }
@ -92,7 +100,8 @@ public class PreKeyBundle: NativeHandleOwner {
try withNativeHandles(prekey, signedPrekey, identityKey.publicKey, kyberPrekey) { prekeyHandle, signedPrekeyHandle, identityKeyHandle, kyberKeyHandle in try withNativeHandles(prekey, signedPrekey, identityKey.publicKey, kyberPrekey) { prekeyHandle, signedPrekeyHandle, identityKeyHandle, kyberKeyHandle in
try signedPrekeySignature.withUnsafeBorrowedBuffer { ecSignatureBuffer in try signedPrekeySignature.withUnsafeBorrowedBuffer { ecSignatureBuffer in
try kyberPrekeySignature.withUnsafeBorrowedBuffer { kyberSignatureBuffer in try kyberPrekeySignature.withUnsafeBorrowedBuffer { kyberSignatureBuffer in
try checkError(signal_pre_key_bundle_new(&result, try checkError(signal_pre_key_bundle_new(
&result,
registrationId, registrationId,
deviceId, deviceId,
prekeyId, prekeyId,
@ -103,7 +112,8 @@ public class PreKeyBundle: NativeHandleOwner {
identityKeyHandle, identityKeyHandle,
kyberPrekeyId, kyberPrekeyId,
kyberKeyHandle, kyberKeyHandle,
kyberSignatureBuffer)) kyberSignatureBuffer
))
} }
} }
} }
@ -129,7 +139,8 @@ public class PreKeyBundle: NativeHandleOwner {
try withNativeHandles(signedPrekey, identityKey.publicKey, kyberPrekey) { signedPrekeyHandle, identityKeyHandle, kyberKeyHandle in try withNativeHandles(signedPrekey, identityKey.publicKey, kyberPrekey) { signedPrekeyHandle, identityKeyHandle, kyberKeyHandle in
try signedPrekeySignature.withUnsafeBorrowedBuffer { ecSignatureBuffer in try signedPrekeySignature.withUnsafeBorrowedBuffer { ecSignatureBuffer in
try kyberPrekeySignature.withUnsafeBorrowedBuffer { kyberSignatureBuffer in try kyberPrekeySignature.withUnsafeBorrowedBuffer { kyberSignatureBuffer in
try checkError(signal_pre_key_bundle_new(&result, try checkError(signal_pre_key_bundle_new(
&result,
registrationId, registrationId,
deviceId, deviceId,
~0, ~0,
@ -140,7 +151,8 @@ public class PreKeyBundle: NativeHandleOwner {
identityKeyHandle, identityKeyHandle,
kyberPrekeyId, kyberPrekeyId,
kyberKeyHandle, kyberKeyHandle,
kyberSignatureBuffer)) kyberSignatureBuffer
))
} }
} }
} }

View File

@ -3,15 +3,15 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class PreKeyRecord: ClonableHandleOwner { 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) 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) return signal_pre_key_record_clone(&newHandle, currentHandle)
} }
@ -24,9 +24,11 @@ public class PreKeyRecord: ClonableHandleOwner {
self.init(owned: handle!) self.init(owned: handle!)
} }
public convenience init(id: UInt32, public convenience init(
id: UInt32,
publicKey: PublicKey, publicKey: PublicKey,
privateKey: PrivateKey) throws { privateKey: PrivateKey
) throws {
var handle: OpaquePointer? var handle: OpaquePointer?
try withNativeHandles(publicKey, privateKey) { publicKeyHandle, privateKeyHandle in try withNativeHandles(publicKey, privateKey) { publicKeyHandle, privateKeyHandle in
try checkError(signal_pre_key_record_new(&handle, id, publicKeyHandle, privateKeyHandle)) try checkError(signal_pre_key_record_new(&handle, id, publicKeyHandle, privateKeyHandle))

View File

@ -3,15 +3,15 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class SenderKeyRecord: ClonableHandleOwner { 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) 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) return signal_sender_key_record_clone(&newHandle, currentHandle)
} }

View File

@ -3,15 +3,15 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class SessionRecord: ClonableHandleOwner { 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) 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) return signal_session_record_clone(&newHandle, currentHandle)
} }
@ -61,7 +61,7 @@ public class SessionRecord: ClonableHandleOwner {
} }
public func currentRatchetKeyMatches(_ key: PublicKey) throws -> Bool { public func currentRatchetKeyMatches(_ key: PublicKey) throws -> Bool {
var result: Bool = false var result = false
try withNativeHandles(self, key) { sessionHandle, keyHandle in try withNativeHandles(self, key) { sessionHandle, keyHandle in
try checkError(signal_session_record_current_ratchet_key_matches(&result, sessionHandle, keyHandle)) try checkError(signal_session_record_current_ratchet_key_matches(&result, sessionHandle, keyHandle))
} }

View File

@ -3,15 +3,15 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import SignalFfi
import Foundation import Foundation
import SignalFfi
public class SignedPreKeyRecord: ClonableHandleOwner { 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) 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) return signal_signed_pre_key_record_clone(&newHandle, currentHandle)
} }
@ -24,17 +24,24 @@ public class SignedPreKeyRecord: ClonableHandleOwner {
self.init(owned: handle!) self.init(owned: handle!)
} }
public convenience init<Bytes: ContiguousBytes>(id: UInt32, public convenience init<Bytes: ContiguousBytes>(
id: UInt32,
timestamp: UInt64, timestamp: UInt64,
privateKey: PrivateKey, privateKey: PrivateKey,
signature: Bytes) throws { signature: Bytes
) throws {
let publicKey = privateKey.publicKey let publicKey = privateKey.publicKey
var result: OpaquePointer? var result: OpaquePointer?
try withNativeHandles(publicKey, privateKey) { publicKeyHandle, privateKeyHandle in try withNativeHandles(publicKey, privateKey) { publicKeyHandle, privateKeyHandle in
try signature.withUnsafeBorrowedBuffer { try signature.withUnsafeBorrowedBuffer {
try checkError(signal_signed_pre_key_record_new(&result, id, timestamp, try checkError(signal_signed_pre_key_record_new(
publicKeyHandle, privateKeyHandle, &result,
$0)) id,
timestamp,
publicKeyHandle,
privateKeyHandle,
$0
))
} }
} }
self.init(owned: result!) self.init(owned: result!)

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class AuthCredentialPresentation: ByteArray { public class AuthCredentialPresentation: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_auth_credential_presentation_check_valid_contents) try super.init(contents, checkValid: signal_auth_credential_presentation_check_valid_contents)
} }
@ -36,5 +35,4 @@ public class AuthCredentialPresentation: ByteArray {
} }
return Date(timeIntervalSince1970: TimeInterval(secondsSinceEpoch)) return Date(timeIntervalSince1970: TimeInterval(secondsSinceEpoch))
} }
} }

View File

@ -7,14 +7,13 @@ import Foundation
import SignalFfi import SignalFfi
public class BackupAuthCredential: ByteArray { public class BackupAuthCredential: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_backup_auth_credential_check_valid_contents) try super.init(contents, checkValid: signal_backup_auth_credential_check_valid_contents)
} }
public func present(serverParams: GenericServerPublicParams) -> BackupAuthCredentialPresentation { public func present(serverParams: GenericServerPublicParams) -> BackupAuthCredentialPresentation {
return failOnError { return failOnError {
present(serverParams: serverParams, randomness: try .generate()) self.present(serverParams: serverParams, randomness: try .generate())
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class BackupAuthCredentialPresentation: ByteArray { public class BackupAuthCredentialPresentation: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_backup_auth_credential_presentation_check_valid_contents) try super.init(contents, checkValid: signal_backup_auth_credential_presentation_check_valid_contents)
} }

View File

@ -13,7 +13,7 @@ public class BackupAuthCredentialRequest: ByteArray {
public func issueCredential(timestamp: Date, receiptLevel: UInt64, params: GenericServerSecretParams) -> BackupAuthCredentialResponse { public func issueCredential(timestamp: Date, receiptLevel: UInt64, params: GenericServerSecretParams) -> BackupAuthCredentialResponse {
return failOnError { return failOnError {
issueCredential(timestamp: timestamp, receiptLevel: receiptLevel, params: params, randomness: try .generate()) self.issueCredential(timestamp: timestamp, receiptLevel: receiptLevel, params: params, randomness: try .generate())
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class BackupAuthCredentialRequestContext: ByteArray { public class BackupAuthCredentialRequestContext: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_backup_auth_credential_request_context_check_valid_contents) try super.init(contents, checkValid: signal_backup_auth_credential_request_context_check_valid_contents)
} }
@ -47,5 +46,4 @@ public class BackupAuthCredentialRequestContext: ByteArray {
} }
} }
} }
} }

View File

@ -10,8 +10,8 @@ public class ByteArray {
private let contents: [UInt8] private let contents: [UInt8]
init(_ newContents: [UInt8], checkValid: (SignalBorrowedBuffer) -> SignalFfiErrorRef?) throws { init(_ newContents: [UInt8], checkValid: (SignalBorrowedBuffer) -> SignalFfiErrorRef?) throws {
contents = newContents self.contents = newContents
try withUnsafeBorrowedBuffer { buffer in try self.withUnsafeBorrowedBuffer { buffer in
try checkError(checkValid(buffer)) try checkError(checkValid(buffer))
} }
} }
@ -20,7 +20,7 @@ public class ByteArray {
if newContents.count != expectedLength { if newContents.count != expectedLength {
throw SignalError.invalidType("\(type(of: self)) uses \(expectedLength) bytes, but tried to deserialize from an array of \(newContents.count) bytes") 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 { required init(contents: [UInt8]) throws {
@ -28,7 +28,7 @@ public class ByteArray {
} }
public func serialize() -> [UInt8] { public func serialize() -> [UInt8] {
return contents return self.contents
} }
/// Passes a pointer to the serialized contents to `callback`. /// Passes a pointer to the serialized contents to `callback`.
@ -45,7 +45,7 @@ public class ByteArray {
func withUnsafePointerToSerialized<Serialized, Result>(_ callback: (UnsafePointer<Serialized>) throws -> Result) throws -> Result { func withUnsafePointerToSerialized<Serialized, Result>(_ callback: (UnsafePointer<Serialized>) throws -> Result) throws -> Result {
precondition(MemoryLayout<Serialized>.alignment == 1, "not a fixed-sized array (tuple) of UInt8") precondition(MemoryLayout<Serialized>.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<Serialized>.size let expectedSize = MemoryLayout<Serialized>.size
guard expectedSize == buffer.count else { 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") 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. /// Used for types that don't have a fixed-length representation.
func withUnsafeBorrowedBuffer<Result>(_ callback: (SignalBorrowedBuffer) throws -> Result) throws -> Result { func withUnsafeBorrowedBuffer<Result>(_ callback: (SignalBorrowedBuffer) throws -> Result) throws -> Result {
return try contents.withUnsafeBorrowedBuffer(callback) return try self.contents.withUnsafeBorrowedBuffer(callback)
} }
} }

View File

@ -7,14 +7,13 @@ import Foundation
import SignalFfi import SignalFfi
public class CallLinkAuthCredential: ByteArray { public class CallLinkAuthCredential: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_call_link_auth_credential_check_valid_contents) 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 { public func present(userId: Aci, redemptionTime: Date, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams) -> CallLinkAuthCredentialPresentation {
return failOnError { return failOnError {
present(userId: userId, redemptionTime: redemptionTime, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate()) self.present(userId: userId, redemptionTime: redemptionTime, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate())
} }
} }
@ -35,5 +34,4 @@ public class CallLinkAuthCredential: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class CallLinkAuthCredentialPresentation: ByteArray { public class CallLinkAuthCredentialPresentation: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_call_link_auth_credential_presentation_check_valid_contents) try super.init(contents, checkValid: signal_call_link_auth_credential_presentation_check_valid_contents)
} }

View File

@ -13,7 +13,7 @@ public class CallLinkAuthCredentialResponse: ByteArray {
public static func issueCredential(userId: Aci, redemptionTime: Date, params: GenericServerSecretParams) -> CallLinkAuthCredentialResponse { public static func issueCredential(userId: Aci, redemptionTime: Date, params: GenericServerSecretParams) -> CallLinkAuthCredentialResponse {
return failOnError { return failOnError {
issueCredential(userId: userId, redemptionTime: redemptionTime, params: params, randomness: try .generate()) self.issueCredential(userId: userId, redemptionTime: redemptionTime, params: params, randomness: try .generate())
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class CallLinkSecretParams: ByteArray { public class CallLinkSecretParams: ByteArray {
public static func deriveFromRootKey<RootKey: ContiguousBytes>(_ rootKey: RootKey) -> CallLinkSecretParams { public static func deriveFromRootKey<RootKey: ContiguousBytes>(_ rootKey: RootKey) -> CallLinkSecretParams {
return failOnError { return failOnError {
try rootKey.withUnsafeBorrowedBuffer { rootKey in try rootKey.withUnsafeBorrowedBuffer { rootKey in
@ -41,5 +40,4 @@ public class CallLinkSecretParams: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ClientZkAuthOperations { public class ClientZkAuthOperations {
let serverPublicParams: ServerPublicParams let serverPublicParams: ServerPublicParams
public init(serverPublicParams: ServerPublicParams) { public init(serverPublicParams: ServerPublicParams) {
@ -15,7 +14,7 @@ public class ClientZkAuthOperations {
} }
public func receiveAuthCredential(aci: Aci, redemptionTime: UInt32, authCredentialResponse: AuthCredentialResponse) throws -> AuthCredential { public func receiveAuthCredential(aci: Aci, redemptionTime: UInt32, authCredentialResponse: AuthCredentialResponse) throws -> AuthCredential {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try aci.withPointerToFixedWidthBinary { uuid in try aci.withPointerToFixedWidthBinary { uuid in
try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -30,7 +29,7 @@ public class ClientZkAuthOperations {
/// ///
/// - parameter redemptionTime: This is provided by the server as an integer, and should be passed through directly. /// - 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 { public func receiveAuthCredentialWithPniAsServiceId(aci: Aci, pni: Pni, redemptionTime: UInt64, authCredentialResponse: AuthCredentialWithPniResponse) throws -> AuthCredentialWithPni {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try aci.withPointerToFixedWidthBinary { aci in try aci.withPointerToFixedWidthBinary { aci in
try pni.withPointerToFixedWidthBinary { pni in try pni.withPointerToFixedWidthBinary { pni in
try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in
@ -50,7 +49,7 @@ public class ClientZkAuthOperations {
/// ///
/// - parameter redemptionTime: This is provided by the server as an integer, and should be passed through directly. /// - 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 { public func receiveAuthCredentialWithPniAsAci(aci: Aci, pni: Pni, redemptionTime: UInt64, authCredentialResponse: AuthCredentialWithPniResponse) throws -> AuthCredentialWithPni {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try aci.withPointerToFixedWidthBinary { aci in try aci.withPointerToFixedWidthBinary { aci in
try pni.withPointerToFixedWidthBinary { pni in try pni.withPointerToFixedWidthBinary { pni in
try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in try authCredentialResponse.withUnsafePointerToSerialized { authCredentialResponse in
@ -64,11 +63,11 @@ public class ClientZkAuthOperations {
} }
public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation { public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation {
return try createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential) return try self.createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential)
} }
public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation { public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredential) throws -> AuthCredentialPresentation {
return try serverPublicParams.withUnsafePointerToSerialized { contents in return try self.serverPublicParams.withUnsafePointerToSerialized { contents in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try authCredential.withUnsafePointerToSerialized { authCredential in try authCredential.withUnsafePointerToSerialized { authCredential in
@ -82,11 +81,11 @@ public class ClientZkAuthOperations {
} }
public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation { public func createAuthCredentialPresentation(groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation {
return try createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential) return try self.createAuthCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, authCredential: authCredential)
} }
public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation { public func createAuthCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, authCredential: AuthCredentialWithPni) throws -> AuthCredentialPresentation {
return try serverPublicParams.withUnsafePointerToSerialized { contents in return try self.serverPublicParams.withUnsafePointerToSerialized { contents in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try authCredential.withUnsafePointerToSerialized { authCredential in try authCredential.withUnsafePointerToSerialized { authCredential in
@ -98,5 +97,4 @@ public class ClientZkAuthOperations {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ClientZkGroupCipher { public class ClientZkGroupCipher {
let groupSecretParams: GroupSecretParams let groupSecretParams: GroupSecretParams
public init(groupSecretParams: GroupSecretParams) { public init(groupSecretParams: GroupSecretParams) {
@ -15,7 +14,7 @@ public class ClientZkGroupCipher {
} }
public func encrypt(_ serviceId: ServiceId) throws -> UuidCiphertext { public func encrypt(_ serviceId: ServiceId) throws -> UuidCiphertext {
return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try serviceId.withPointerToFixedWidthBinary { serviceId in try serviceId.withPointerToFixedWidthBinary { serviceId in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
signal_group_secret_params_encrypt_service_id($0, groupSecretParams, serviceId) signal_group_secret_params_encrypt_service_id($0, groupSecretParams, serviceId)
@ -25,7 +24,7 @@ public class ClientZkGroupCipher {
} }
public func decrypt(_ uuidCiphertext: UuidCiphertext) throws -> ServiceId { public func decrypt(_ uuidCiphertext: UuidCiphertext) throws -> ServiceId {
return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try uuidCiphertext.withUnsafePointerToSerialized { uuidCiphertext in try uuidCiphertext.withUnsafePointerToSerialized { uuidCiphertext in
try invokeFnReturningServiceId { try invokeFnReturningServiceId {
signal_group_secret_params_decrypt_service_id($0, groupSecretParams, uuidCiphertext) signal_group_secret_params_decrypt_service_id($0, groupSecretParams, uuidCiphertext)
@ -35,7 +34,7 @@ public class ClientZkGroupCipher {
} }
public func encryptProfileKey(profileKey: ProfileKey, userId: Aci) throws -> ProfileKeyCiphertext { public func encryptProfileKey(profileKey: ProfileKey, userId: Aci) throws -> ProfileKeyCiphertext {
return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try profileKey.withUnsafePointerToSerialized { profileKey in try profileKey.withUnsafePointerToSerialized { profileKey in
try userId.withPointerToFixedWidthBinary { userId in try userId.withPointerToFixedWidthBinary { userId in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -47,7 +46,7 @@ public class ClientZkGroupCipher {
} }
public func decryptProfileKey(profileKeyCiphertext: ProfileKeyCiphertext, userId: Aci) throws -> ProfileKey { public func decryptProfileKey(profileKeyCiphertext: ProfileKeyCiphertext, userId: Aci) throws -> ProfileKey {
return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try profileKeyCiphertext.withUnsafePointerToSerialized { profileKeyCiphertext in try profileKeyCiphertext.withUnsafePointerToSerialized { profileKeyCiphertext in
try userId.withPointerToFixedWidthBinary { userId in try userId.withPointerToFixedWidthBinary { userId in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -59,11 +58,11 @@ public class ClientZkGroupCipher {
} }
public func encryptBlob(plaintext: [UInt8]) throws -> [UInt8] { public func encryptBlob(plaintext: [UInt8]) throws -> [UInt8] {
return try encryptBlob(randomness: Randomness.generate(), plaintext: plaintext) return try self.encryptBlob(randomness: Randomness.generate(), plaintext: plaintext)
} }
public func encryptBlob(randomness: Randomness, plaintext: [UInt8]) throws -> [UInt8] { public func encryptBlob(randomness: Randomness, plaintext: [UInt8]) throws -> [UInt8] {
return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try plaintext.withUnsafeBorrowedBuffer { plaintext in try plaintext.withUnsafeBorrowedBuffer { plaintext in
try invokeFnReturningArray { try invokeFnReturningArray {
@ -75,7 +74,7 @@ public class ClientZkGroupCipher {
} }
public func decryptBlob(blobCiphertext: [UInt8]) throws -> [UInt8] { public func decryptBlob(blobCiphertext: [UInt8]) throws -> [UInt8] {
return try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in return try self.groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try blobCiphertext.withUnsafeBorrowedBuffer { blobCiphertext in try blobCiphertext.withUnsafeBorrowedBuffer { blobCiphertext in
try invokeFnReturningArray { try invokeFnReturningArray {
signal_group_secret_params_decrypt_blob_with_padding($0, groupSecretParams, blobCiphertext) signal_group_secret_params_decrypt_blob_with_padding($0, groupSecretParams, blobCiphertext)
@ -83,5 +82,4 @@ public class ClientZkGroupCipher {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ClientZkProfileOperations { public class ClientZkProfileOperations {
let serverPublicParams: ServerPublicParams let serverPublicParams: ServerPublicParams
public init(serverPublicParams: ServerPublicParams) { public init(serverPublicParams: ServerPublicParams) {
@ -15,11 +14,11 @@ public class ClientZkProfileOperations {
} }
public func createProfileKeyCredentialRequestContext(userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext { public func createProfileKeyCredentialRequestContext(userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext {
return try createProfileKeyCredentialRequestContext(randomness: Randomness.generate(), userId: userId, profileKey: profileKey) return try self.createProfileKeyCredentialRequestContext(randomness: Randomness.generate(), userId: userId, profileKey: profileKey)
} }
public func createProfileKeyCredentialRequestContext(randomness: Randomness, userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext { public func createProfileKeyCredentialRequestContext(randomness: Randomness, userId: Aci, profileKey: ProfileKey) throws -> ProfileKeyCredentialRequestContext {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try userId.withPointerToFixedWidthBinary { userId in try userId.withPointerToFixedWidthBinary { userId in
try profileKey.withUnsafePointerToSerialized { profileKey in try profileKey.withUnsafePointerToSerialized { profileKey in
@ -37,7 +36,7 @@ public class ClientZkProfileOperations {
profileKeyCredentialResponse: ExpiringProfileKeyCredentialResponse, profileKeyCredentialResponse: ExpiringProfileKeyCredentialResponse,
now: Date = Date() now: Date = Date()
) throws -> ExpiringProfileKeyCredential { ) throws -> ExpiringProfileKeyCredential {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try profileKeyCredentialRequestContext.withUnsafePointerToSerialized { requestContext in try profileKeyCredentialRequestContext.withUnsafePointerToSerialized { requestContext in
try profileKeyCredentialResponse.withUnsafePointerToSerialized { response in try profileKeyCredentialResponse.withUnsafePointerToSerialized { response in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -49,11 +48,11 @@ public class ClientZkProfileOperations {
} }
public func createProfileKeyCredentialPresentation(groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation { public func createProfileKeyCredentialPresentation(groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation {
return try createProfileKeyCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, profileKeyCredential: profileKeyCredential) return try self.createProfileKeyCredentialPresentation(randomness: Randomness.generate(), groupSecretParams: groupSecretParams, profileKeyCredential: profileKeyCredential)
} }
public func createProfileKeyCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation { public func createProfileKeyCredentialPresentation(randomness: Randomness, groupSecretParams: GroupSecretParams, profileKeyCredential: ExpiringProfileKeyCredential) throws -> ProfileKeyCredentialPresentation {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in try groupSecretParams.withUnsafePointerToSerialized { groupSecretParams in
try profileKeyCredential.withUnsafePointerToSerialized { profileKeyCredential in try profileKeyCredential.withUnsafePointerToSerialized { profileKeyCredential in
@ -65,5 +64,4 @@ public class ClientZkProfileOperations {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ClientZkReceiptOperations { public class ClientZkReceiptOperations {
let serverPublicParams: ServerPublicParams let serverPublicParams: ServerPublicParams
public init(serverPublicParams: ServerPublicParams) { public init(serverPublicParams: ServerPublicParams) {
@ -15,11 +14,11 @@ public class ClientZkReceiptOperations {
} }
public func createReceiptCredentialRequestContext(receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext { public func createReceiptCredentialRequestContext(receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext {
return try createReceiptCredentialRequestContext(randomness: Randomness.generate(), receiptSerial: receiptSerial) return try self.createReceiptCredentialRequestContext(randomness: Randomness.generate(), receiptSerial: receiptSerial)
} }
public func createReceiptCredentialRequestContext(randomness: Randomness, receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext { public func createReceiptCredentialRequestContext(randomness: Randomness, receiptSerial: ReceiptSerial) throws -> ReceiptCredentialRequestContext {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try receiptSerial.withUnsafePointerToSerialized { receiptSerial in try receiptSerial.withUnsafePointerToSerialized { receiptSerial in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -31,7 +30,7 @@ public class ClientZkReceiptOperations {
} }
public func receiveReceiptCredential(receiptCredentialRequestContext: ReceiptCredentialRequestContext, receiptCredentialResponse: ReceiptCredentialResponse) throws -> ReceiptCredential { public func receiveReceiptCredential(receiptCredentialRequestContext: ReceiptCredentialRequestContext, receiptCredentialResponse: ReceiptCredentialResponse) throws -> ReceiptCredential {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try receiptCredentialRequestContext.withUnsafePointerToSerialized { requestContext in try receiptCredentialRequestContext.withUnsafePointerToSerialized { requestContext in
try receiptCredentialResponse.withUnsafePointerToSerialized { response in try receiptCredentialResponse.withUnsafePointerToSerialized { response in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -43,11 +42,11 @@ public class ClientZkReceiptOperations {
} }
public func createReceiptCredentialPresentation(receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation { public func createReceiptCredentialPresentation(receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation {
return try createReceiptCredentialPresentation(randomness: Randomness.generate(), receiptCredential: receiptCredential) return try self.createReceiptCredentialPresentation(randomness: Randomness.generate(), receiptCredential: receiptCredential)
} }
public func createReceiptCredentialPresentation(randomness: Randomness, receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation { public func createReceiptCredentialPresentation(randomness: Randomness, receiptCredential: ReceiptCredential) throws -> ReceiptCredentialPresentation {
return try serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in return try self.serverPublicParams.withUnsafePointerToSerialized { serverPublicParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try receiptCredential.withUnsafePointerToSerialized { receiptCredential in try receiptCredential.withUnsafePointerToSerialized { receiptCredential in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -57,5 +56,4 @@ public class ClientZkReceiptOperations {
} }
} }
} }
} }

View File

@ -7,14 +7,13 @@ import Foundation
import SignalFfi import SignalFfi
public class CreateCallLinkCredential: ByteArray { public class CreateCallLinkCredential: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_create_call_link_credential_check_valid_contents) try super.init(contents, checkValid: signal_create_call_link_credential_check_valid_contents)
} }
public func present<RoomId: ContiguousBytes>(roomId: RoomId, userId: Aci, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams) -> CreateCallLinkCredentialPresentation { public func present<RoomId: ContiguousBytes>(roomId: RoomId, userId: Aci, serverParams: GenericServerPublicParams, callLinkParams: CallLinkSecretParams) -> CreateCallLinkCredentialPresentation {
return failOnError { return failOnError {
present(roomId: roomId, userId: userId, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate()) self.present(roomId: roomId, userId: userId, serverParams: serverParams, callLinkParams: callLinkParams, randomness: try .generate())
} }
} }
@ -37,5 +36,4 @@ public class CreateCallLinkCredential: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class CreateCallLinkCredentialPresentation: ByteArray { public class CreateCallLinkCredentialPresentation: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_create_call_link_credential_presentation_check_valid_contents) try super.init(contents, checkValid: signal_create_call_link_credential_presentation_check_valid_contents)
} }
@ -23,5 +22,4 @@ public class CreateCallLinkCredentialPresentation: ByteArray {
} }
} }
} }
} }

View File

@ -13,7 +13,7 @@ public class CreateCallLinkCredentialRequest: ByteArray {
public func issueCredential(userId: Aci, timestamp: Date, params: GenericServerSecretParams) -> CreateCallLinkCredentialResponse { public func issueCredential(userId: Aci, timestamp: Date, params: GenericServerSecretParams) -> CreateCallLinkCredentialResponse {
return failOnError { return failOnError {
issueCredential(userId: userId, timestamp: timestamp, params: params, randomness: try .generate()) self.issueCredential(userId: userId, timestamp: timestamp, params: params, randomness: try .generate())
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class CreateCallLinkCredentialRequestContext: ByteArray { public class CreateCallLinkCredentialRequestContext: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_create_call_link_credential_request_context_check_valid_contents) try super.init(contents, checkValid: signal_create_call_link_credential_request_context_check_valid_contents)
} }
@ -53,5 +52,4 @@ public class CreateCallLinkCredentialRequestContext: ByteArray {
} }
} }
} }
} }

View File

@ -7,10 +7,9 @@ import Foundation
import SignalFfi import SignalFfi
public class GenericServerSecretParams: ByteArray { public class GenericServerSecretParams: ByteArray {
public static func generate() -> Self { public static func generate() -> Self {
return failOnError { return failOnError {
generate(randomness: try .generate()) self.generate(randomness: try .generate())
} }
} }
@ -37,5 +36,4 @@ public class GenericServerSecretParams: ByteArray {
} }
} }
} }
} }

View File

@ -4,11 +4,9 @@
// //
public class GroupIdentifier: ByteArray { public class GroupIdentifier: ByteArray {
public static let SIZE: Int = 32 public static let SIZE: Int = 32
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(newContents: contents, expectedLength: GroupIdentifier.SIZE) try super.init(newContents: contents, expectedLength: GroupIdentifier.SIZE)
} }
} }

View File

@ -4,11 +4,9 @@
// //
public class GroupMasterKey: ByteArray { public class GroupMasterKey: ByteArray {
public static let SIZE: Int = 32 public static let SIZE: Int = 32
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(newContents: contents, expectedLength: GroupMasterKey.SIZE) try super.init(newContents: contents, expectedLength: GroupMasterKey.SIZE)
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class GroupPublicParams: ByteArray { public class GroupPublicParams: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_group_public_params_check_valid_contents) try super.init(contents, checkValid: signal_group_public_params_check_valid_contents)
} }
@ -19,5 +18,4 @@ public class GroupPublicParams: ByteArray {
} }
} }
} }
} }

View File

@ -7,9 +7,8 @@ import Foundation
import SignalFfi import SignalFfi
public class GroupSecretParams: ByteArray { public class GroupSecretParams: ByteArray {
public static func generate() throws -> GroupSecretParams { public static func generate() throws -> GroupSecretParams {
return try generate(randomness: Randomness.generate()) return try self.generate(randomness: Randomness.generate())
} }
public static func generate(randomness: Randomness) throws -> GroupSecretParams { public static func generate(randomness: Randomness) throws -> GroupSecretParams {
@ -47,5 +46,4 @@ public class GroupSecretParams: ByteArray {
} }
} }
} }
} }

View File

@ -16,7 +16,6 @@ import SignalFfi
* - SeeAlso: ``GroupSendCredentialResponse``, ``GroupSendCredentialPresentation`` * - SeeAlso: ``GroupSendCredentialResponse``, ``GroupSendCredentialPresentation``
*/ */
public class GroupSendCredential: ByteArray { public class GroupSendCredential: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_group_send_credential_check_valid_contents) try super.init(contents, checkValid: signal_group_send_credential_check_valid_contents)
} }
@ -26,7 +25,7 @@ public class GroupSendCredential: ByteArray {
*/ */
public func present(serverParams: ServerPublicParams) -> GroupSendCredentialPresentation { public func present(serverParams: ServerPublicParams) -> GroupSendCredentialPresentation {
return failOnError { return failOnError {
present(serverParams: serverParams, randomness: try .generate()) self.present(serverParams: serverParams, randomness: try .generate())
} }
} }

View File

@ -16,7 +16,6 @@ import SignalFfi
* - SeeAlso: ``GroupSendCredentialResponse``, ``GroupSendCredential`` * - SeeAlso: ``GroupSendCredentialResponse``, ``GroupSendCredential``
*/ */
public class GroupSendCredentialPresentation: ByteArray { public class GroupSendCredentialPresentation: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_group_send_credential_presentation_check_valid_contents) try super.init(contents, checkValid: signal_group_send_credential_presentation_check_valid_contents)
} }

View File

@ -37,7 +37,7 @@ public class GroupSendCredentialResponse: ByteArray {
*/ */
public static func issueCredential(groupMembers: [UuidCiphertext], requestingMember: UuidCiphertext, expiration: Date = GroupSendCredentialResponse.defaultExpiration(), params: ServerSecretParams) -> GroupSendCredentialResponse { public static func issueCredential(groupMembers: [UuidCiphertext], requestingMember: UuidCiphertext, expiration: Date = GroupSendCredentialResponse.defaultExpiration(), params: ServerSecretParams) -> GroupSendCredentialResponse {
return failOnError { return failOnError {
issueCredential(groupMembers: groupMembers, requestingMember: requestingMember, expiration: expiration, params: params, randomness: try .generate()) self.issueCredential(groupMembers: groupMembers, requestingMember: requestingMember, expiration: expiration, params: params, randomness: try .generate())
} }
} }
@ -53,7 +53,7 @@ public class GroupSendCredentialResponse: ByteArray {
let concatenated = groupMembers.flatMap { $0.serialize() } let concatenated = groupMembers.flatMap { $0.serialize() }
return failOnError { return failOnError {
return try concatenated.withUnsafeBorrowedBuffer { concatenated in try concatenated.withUnsafeBorrowedBuffer { concatenated in
try requestingMember.withUnsafePointerToSerialized { requestingMember in try requestingMember.withUnsafePointerToSerialized { requestingMember in
try params.withUnsafePointerToSerialized { params in try params.withUnsafePointerToSerialized { params in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
@ -64,7 +64,8 @@ public class GroupSendCredentialResponse: ByteArray {
requestingMember, requestingMember,
UInt64(expiration.timeIntervalSince1970), UInt64(expiration.timeIntervalSince1970),
params, params,
randomness) randomness
)
} }
} }
} }

View File

@ -4,11 +4,9 @@
// //
public class NotarySignature: ByteArray { public class NotarySignature: ByteArray {
public static let SIZE: Int = 64 public static let SIZE: Int = 64
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(newContents: contents, expectedLength: NotarySignature.SIZE) try super.init(newContents: contents, expectedLength: NotarySignature.SIZE)
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ProfileKey: ByteArray { public class ProfileKey: ByteArray {
public static let SIZE: Int = 32 public static let SIZE: Int = 32
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
@ -43,5 +42,4 @@ public class ProfileKey: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ProfileKeyCredentialPresentation: ByteArray { public class ProfileKeyCredentialPresentation: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_profile_key_credential_presentation_check_valid_contents) try super.init(contents, checkValid: signal_profile_key_credential_presentation_check_valid_contents)
} }
@ -27,5 +26,4 @@ public class ProfileKeyCredentialPresentation: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ProfileKeyCredentialRequestContext: ByteArray { public class ProfileKeyCredentialRequestContext: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_profile_key_credential_request_context_check_valid_contents) try super.init(contents, checkValid: signal_profile_key_credential_request_context_check_valid_contents)
} }
@ -19,5 +18,4 @@ public class ProfileKeyCredentialRequestContext: ByteArray {
} }
} }
} }
} }

View File

@ -4,11 +4,9 @@
// //
public class ProfileKeyVersion: ByteArray { public class ProfileKeyVersion: ByteArray {
public static let SIZE: Int = 64 public static let SIZE: Int = 64
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(newContents: contents, expectedLength: ProfileKeyVersion.SIZE) try super.init(newContents: contents, expectedLength: ProfileKeyVersion.SIZE)
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ReceiptCredential: ByteArray { public class ReceiptCredential: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_receipt_credential_check_valid_contents) try super.init(contents, checkValid: signal_receipt_credential_check_valid_contents)
} }
@ -27,5 +26,4 @@ public class ReceiptCredential: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ReceiptCredentialPresentation: ByteArray { public class ReceiptCredentialPresentation: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_receipt_credential_presentation_check_valid_contents) try super.init(contents, checkValid: signal_receipt_credential_presentation_check_valid_contents)
} }
@ -35,5 +34,4 @@ public class ReceiptCredentialPresentation: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ReceiptCredentialRequestContext: ByteArray { public class ReceiptCredentialRequestContext: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_receipt_credential_request_context_check_valid_contents) try super.init(contents, checkValid: signal_receipt_credential_request_context_check_valid_contents)
} }
@ -19,5 +18,4 @@ public class ReceiptCredentialRequestContext: ByteArray {
} }
} }
} }
} }

View File

@ -4,11 +4,9 @@
// //
public class ReceiptSerial: ByteArray { public class ReceiptSerial: ByteArray {
public static let SIZE: Int = 16 public static let SIZE: Int = 16
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(newContents: contents, expectedLength: ReceiptSerial.SIZE) try super.init(newContents: contents, expectedLength: ReceiptSerial.SIZE)
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ServerPublicParams: ByteArray { public class ServerPublicParams: ByteArray {
public required init(contents: [UInt8]) throws { public required init(contents: [UInt8]) throws {
try super.init(contents, checkValid: signal_server_public_params_check_valid_contents) try super.init(contents, checkValid: signal_server_public_params_check_valid_contents)
} }
@ -21,5 +20,4 @@ public class ServerPublicParams: ByteArray {
} }
} }
} }
} }

View File

@ -7,9 +7,8 @@ import Foundation
import SignalFfi import SignalFfi
public class ServerSecretParams: ByteArray { public class ServerSecretParams: ByteArray {
public static func generate() throws -> ServerSecretParams { public static func generate() throws -> ServerSecretParams {
return try generate(randomness: Randomness.generate()) return try self.generate(randomness: Randomness.generate())
} }
public static func generate(randomness: Randomness) throws -> ServerSecretParams { public static func generate(randomness: Randomness) throws -> ServerSecretParams {
@ -33,7 +32,7 @@ public class ServerSecretParams: ByteArray {
} }
public func sign(message: [UInt8]) throws -> NotarySignature { public func sign(message: [UInt8]) throws -> NotarySignature {
return try sign(randomness: Randomness.generate(), message: message) return try self.sign(randomness: Randomness.generate(), message: message)
} }
public func sign(randomness: Randomness, message: [UInt8]) throws -> NotarySignature { public func sign(randomness: Randomness, message: [UInt8]) throws -> NotarySignature {
@ -47,5 +46,4 @@ public class ServerSecretParams: ByteArray {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ServerZkAuthOperations { public class ServerZkAuthOperations {
let serverSecretParams: ServerSecretParams let serverSecretParams: ServerSecretParams
public init(serverSecretParams: ServerSecretParams) { public init(serverSecretParams: ServerSecretParams) {
@ -15,11 +14,11 @@ public class ServerZkAuthOperations {
} }
public func issueAuthCredential(aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse { public func issueAuthCredential(aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse {
return try issueAuthCredential(randomness: Randomness.generate(), aci: aci, redemptionTime: redemptionTime) return try self.issueAuthCredential(randomness: Randomness.generate(), aci: aci, redemptionTime: redemptionTime)
} }
public func issueAuthCredential(randomness: Randomness, aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse { public func issueAuthCredential(randomness: Randomness, aci: Aci, redemptionTime: UInt32) throws -> AuthCredentialResponse {
return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try aci.withPointerToFixedWidthBinary { aci in try aci.withPointerToFixedWidthBinary { aci in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -31,11 +30,11 @@ public class ServerZkAuthOperations {
} }
public func issueAuthCredentialWithPniAsServiceId(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { public func issueAuthCredentialWithPniAsServiceId(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse {
return try issueAuthCredentialWithPniAsServiceId(randomness: Randomness.generate(), aci: aci, pni: pni, redemptionTime: redemptionTime) return try self.issueAuthCredentialWithPniAsServiceId(randomness: Randomness.generate(), aci: aci, pni: pni, redemptionTime: redemptionTime)
} }
public func issueAuthCredentialWithPniAsServiceId(randomness: Randomness, aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { public func issueAuthCredentialWithPniAsServiceId(randomness: Randomness, aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse {
return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try aci.withPointerToFixedWidthBinary { aci in try aci.withPointerToFixedWidthBinary { aci in
try pni.withPointerToFixedWidthBinary { pni in try pni.withPointerToFixedWidthBinary { pni in
@ -49,11 +48,11 @@ public class ServerZkAuthOperations {
} }
public func issueAuthCredentialWithPniAsAci(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse { public func issueAuthCredentialWithPniAsAci(aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse {
return try issueAuthCredentialWithPniAsAci(randomness: Randomness.generate(), aci: aci, pni: pni, redemptionTime: redemptionTime) 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 { public func issueAuthCredentialWithPniAsAci(randomness: Randomness, aci: Aci, pni: Pni, redemptionTime: UInt64) throws -> AuthCredentialWithPniResponse {
return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try aci.withPointerToFixedWidthBinary { aci in try aci.withPointerToFixedWidthBinary { aci in
try pni.withPointerToFixedWidthBinary { pni in try pni.withPointerToFixedWidthBinary { pni in
@ -67,7 +66,7 @@ public class ServerZkAuthOperations {
} }
public func verifyAuthCredentialPresentation(groupPublicParams: GroupPublicParams, authCredentialPresentation: AuthCredentialPresentation, now: Date = Date()) throws { public func verifyAuthCredentialPresentation(groupPublicParams: GroupPublicParams, authCredentialPresentation: AuthCredentialPresentation, now: Date = Date()) throws {
try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in
try authCredentialPresentation.withUnsafeBorrowedBuffer { authCredentialPresentation in try authCredentialPresentation.withUnsafeBorrowedBuffer { authCredentialPresentation in
try checkError(signal_server_secret_params_verify_auth_credential_presentation(serverSecretParams, groupPublicParams, authCredentialPresentation, UInt64(now.timeIntervalSince1970))) try checkError(signal_server_secret_params_verify_auth_credential_presentation(serverSecretParams, groupPublicParams, authCredentialPresentation, UInt64(now.timeIntervalSince1970)))
@ -75,5 +74,4 @@ public class ServerZkAuthOperations {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ServerZkProfileOperations { public class ServerZkProfileOperations {
let serverSecretParams: ServerSecretParams let serverSecretParams: ServerSecretParams
public init(serverSecretParams: ServerSecretParams) { public init(serverSecretParams: ServerSecretParams) {
@ -15,11 +14,11 @@ public class ServerZkProfileOperations {
} }
public func issueExpiringProfileKeyCredential(profileKeyCredentialRequest: ProfileKeyCredentialRequest, userId: Aci, profileKeyCommitment: ProfileKeyCommitment, expiration: UInt64) throws -> ExpiringProfileKeyCredentialResponse { 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) return try self.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 { public func issueExpiringProfileKeyCredential(randomness: Randomness, profileKeyCredentialRequest: ProfileKeyCredentialRequest, userId: Aci, profileKeyCommitment: ProfileKeyCommitment, expiration: UInt64) throws -> ExpiringProfileKeyCredentialResponse {
return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try profileKeyCredentialRequest.withUnsafePointerToSerialized { request in try profileKeyCredentialRequest.withUnsafePointerToSerialized { request in
try userId.withPointerToFixedWidthBinary { userId in try userId.withPointerToFixedWidthBinary { userId in
@ -39,7 +38,7 @@ public class ServerZkProfileOperations {
profileKeyCredentialPresentation: ProfileKeyCredentialPresentation, profileKeyCredentialPresentation: ProfileKeyCredentialPresentation,
now: Date = Date() now: Date = Date()
) throws { ) throws {
try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in try groupPublicParams.withUnsafePointerToSerialized { groupPublicParams in
try profileKeyCredentialPresentation.withUnsafeBorrowedBuffer { presentation in try profileKeyCredentialPresentation.withUnsafeBorrowedBuffer { presentation in
try checkError(signal_server_secret_params_verify_profile_key_credential_presentation(serverSecretParams, groupPublicParams, presentation, UInt64(now.timeIntervalSince1970))) try checkError(signal_server_secret_params_verify_profile_key_credential_presentation(serverSecretParams, groupPublicParams, presentation, UInt64(now.timeIntervalSince1970)))
@ -47,5 +46,4 @@ public class ServerZkProfileOperations {
} }
} }
} }
} }

View File

@ -7,7 +7,6 @@ import Foundation
import SignalFfi import SignalFfi
public class ServerZkReceiptOperations { public class ServerZkReceiptOperations {
let serverSecretParams: ServerSecretParams let serverSecretParams: ServerSecretParams
public init(serverSecretParams: ServerSecretParams) { public init(serverSecretParams: ServerSecretParams) {
@ -15,11 +14,11 @@ public class ServerZkReceiptOperations {
} }
public func issueReceiptCredential(receiptCredentialRequest: ReceiptCredentialRequest, receiptExpirationTime: UInt64, receiptLevel: UInt64) throws -> ReceiptCredentialResponse { public func issueReceiptCredential(receiptCredentialRequest: ReceiptCredentialRequest, receiptExpirationTime: UInt64, receiptLevel: UInt64) throws -> ReceiptCredentialResponse {
return try issueReceiptCredential(randomness: Randomness.generate(), receiptCredentialRequest: receiptCredentialRequest, receiptExpirationTime: receiptExpirationTime, receiptLevel: receiptLevel) 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 { public func issueReceiptCredential(randomness: Randomness, receiptCredentialRequest: ReceiptCredentialRequest, receiptExpirationTime: UInt64, receiptLevel: UInt64) throws -> ReceiptCredentialResponse {
return try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in return try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try randomness.withUnsafePointerToBytes { randomness in try randomness.withUnsafePointerToBytes { randomness in
try receiptCredentialRequest.withUnsafePointerToSerialized { receiptCredentialRequest in try receiptCredentialRequest.withUnsafePointerToSerialized { receiptCredentialRequest in
try invokeFnReturningSerialized { try invokeFnReturningSerialized {
@ -31,11 +30,10 @@ public class ServerZkReceiptOperations {
} }
public func verifyReceiptCredentialPresentation(receiptCredentialPresentation: ReceiptCredentialPresentation) throws { public func verifyReceiptCredentialPresentation(receiptCredentialPresentation: ReceiptCredentialPresentation) throws {
try serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in try self.serverSecretParams.withUnsafePointerToSerialized { serverSecretParams in
try receiptCredentialPresentation.withUnsafePointerToSerialized { receiptCredentialPresentation in try receiptCredentialPresentation.withUnsafePointerToSerialized { receiptCredentialPresentation in
try checkError(signal_server_secret_params_verify_receipt_credential_presentation(serverSecretParams, receiptCredentialPresentation)) try checkError(signal_server_secret_params_verify_receipt_credential_presentation(serverSecretParams, receiptCredentialPresentation))
} }
} }
} }
} }

View File

@ -6,9 +6,9 @@
// These testing endpoints aren't generated in device builds, to save on code size. // These testing endpoints aren't generated in device builds, to save on code size.
#if !os(iOS) || targetEnvironment(simulator) #if !os(iOS) || targetEnvironment(simulator)
import XCTest
@testable import LibSignalClient @testable import LibSignalClient
import SignalFfi import SignalFfi
import XCTest
final class AsyncTests: XCTestCase { final class AsyncTests: XCTestCase {
func testSuccess() async throws { func testSuccess() async throws {
@ -39,7 +39,8 @@ final class AsyncTests: XCTestCase {
XCTAssertEqual( XCTAssertEqual(
try invokeFnReturningInteger { result in try invokeFnReturningInteger { result in
signal_testing_testing_handle_type_get_value(result, handle) signal_testing_testing_handle_type_get_value(result, handle)
}, value) }, value
)
} }
do { do {
@ -52,7 +53,8 @@ final class AsyncTests: XCTestCase {
XCTAssertEqual( XCTAssertEqual(
try invokeFnReturningString { result in try invokeFnReturningString { result in
signal_testing_other_testing_handle_type_get_value(result, otherHandle) signal_testing_other_testing_handle_type_get_value(result, otherHandle)
}, value) }, value
)
} }
} }
} }

View File

@ -6,9 +6,9 @@
// These testing endpoints aren't generated in device builds, to save on code size. // These testing endpoints aren't generated in device builds, to save on code size.
#if !os(iOS) || targetEnvironment(simulator) #if !os(iOS) || targetEnvironment(simulator)
import XCTest
@testable import LibSignalClient @testable import LibSignalClient
import SignalFfi import SignalFfi
import XCTest
private func fakeAsyncRuntime() -> OpaquePointer! { private func fakeAsyncRuntime() -> OpaquePointer! {
OpaquePointer(bitPattern: -1) OpaquePointer(bitPattern: -1)

View File

@ -3,8 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import XCTest
@testable import LibSignalClient @testable import LibSignalClient
import XCTest
private struct FakeHandle { private struct FakeHandle {
// We're using the tuple to guarantee in-memory layout for this test. // We're using the tuple to guarantee in-memory layout for this test.

File diff suppressed because one or more lines are too long

View File

@ -3,11 +3,10 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import XCTest
import LibSignalClient import LibSignalClient
import XCTest
class HsmEnclaveTests: TestCaseBase { class HsmEnclaveTests: TestCaseBase {
func testCreateClient() { func testCreateClient() {
let validKey = IdentityKeyPair.generate().publicKey let validKey = IdentityKeyPair.generate().publicKey
var hashes = HsmCodeHashList() var hashes = HsmCodeHashList()

View File

@ -3,11 +3,10 @@
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
// //
import XCTest
import LibSignalClient import LibSignalClient
import XCTest
class IasTests: TestCaseBase { class IasTests: TestCaseBase {
func testSignatureValidation() throws { func testSignatureValidation() throws {
let signatureData = Data(base64Encoded: goodSignature)! let signatureData = Data(base64Encoded: goodSignature)!
let messageData = Data(base64Encoded: goodMessage)! let messageData = Data(base64Encoded: goodMessage)!

View File

@ -4,8 +4,8 @@
// //
import Foundation import Foundation
import XCTest
import LibSignalClient import LibSignalClient
import XCTest
class IncrementalMacTests: TestCaseBase { class IncrementalMacTests: TestCaseBase {
private let TEST_KEY = Data(base64Encoded: "qDSBRX7+zGmtE0LiHZwCl/cd679ckwS0wbLkM8Gnj5g=")! private let TEST_KEY = Data(base64Encoded: "qDSBRX7+zGmtE0LiHZwCl/cd679ckwS0wbLkM8Gnj5g=")!
@ -15,24 +15,24 @@ class IncrementalMacTests: TestCaseBase {
func testIncrementalDigestCreation() throws { func testIncrementalDigestCreation() throws {
let mac = try IncrementalMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE) 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) try mac.update(d)
} }
let digest = try mac.finalize() let digest = try mac.finalize()
XCTAssertEqual(TEST_DIGEST, digest) XCTAssertEqual(self.TEST_DIGEST, digest)
} }
func testIncrementalValidationSuccess() throws { func testIncrementalValidationSuccess() throws {
let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST) let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST)
for d in TEST_INPUT { for d in self.TEST_INPUT {
_ = try mac.update(d) _ = try mac.update(d)
} }
_ = try mac.finalize() _ = try mac.finalize()
} }
func testNoBytesCanBeConsumedWithoutValidation() throws { func testNoBytesCanBeConsumedWithoutValidation() throws {
var corruptInput = TEST_INPUT var corruptInput = self.TEST_INPUT
corruptInput[0][1] ^= 0xff corruptInput[0][1] ^= 0xFF
let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST) let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST)
XCTAssertEqual(0, try mac.update(corruptInput[0])) XCTAssertEqual(0, try mac.update(corruptInput[0]))
@ -46,8 +46,8 @@ class IncrementalMacTests: TestCaseBase {
} }
func testIncrementalValidationFailureInFinalize() throws { func testIncrementalValidationFailureInFinalize() throws {
var corruptInput = TEST_INPUT var corruptInput = self.TEST_INPUT
corruptInput[2][0] ^= 0xff corruptInput[2][0] ^= 0xFF
let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST) let mac = try ValidatingMacContext(key: TEST_KEY, chunkSize: CHUNK_SIZE, expectingDigest: TEST_DIGEST)
XCTAssertEqual(0, try mac.update(corruptInput[0])) XCTAssertEqual(0, try mac.update(corruptInput[0]))

View File

@ -25,30 +25,30 @@ public class ThrowsAfterInputStream: SignalInputStream {
} }
public func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int { public func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int {
if readBeforeThrow == 0 { if self.readBeforeThrow == 0 {
throw TestIoError() throw TestIoError()
} }
var target = buffer var target = buffer
if buffer.count > readBeforeThrow { if buffer.count > self.readBeforeThrow {
target = UnsafeMutableRawBufferPointer(rebasing: buffer[..<Int(readBeforeThrow)]) target = UnsafeMutableRawBufferPointer(rebasing: buffer[..<Int(self.readBeforeThrow)])
} }
let read = try inner.read(into: target) let read = try inner.read(into: target)
if read > 0 { if read > 0 {
readBeforeThrow -= UInt64(read) self.readBeforeThrow -= UInt64(read)
} }
return read return read
} }
public func skip(by amount: UInt64) throws { public func skip(by amount: UInt64) throws {
if readBeforeThrow < amount { if self.readBeforeThrow < amount {
readBeforeThrow = 0 self.readBeforeThrow = 0
throw TestIoError() throw TestIoError()
} }
try inner.skip(by: amount) try self.inner.skip(by: amount)
readBeforeThrow -= amount self.readBeforeThrow -= amount
} }
private var inner: SignalInputStream private var inner: SignalInputStream

View File

@ -5,8 +5,8 @@
#if SIGNAL_MEDIA_SUPPORTED #if SIGNAL_MEDIA_SUPPORTED
import XCTest
@testable import LibSignalClient @testable import LibSignalClient
import XCTest
class Mp4SanitizerTests: TestCaseBase { class Mp4SanitizerTests: TestCaseBase {
func testEmptyMp4() { func testEmptyMp4() {
@ -129,7 +129,7 @@ private func webp() -> [UInt8] {
webp.append(contentsOf: "VP8L") // chunk type webp.append(contentsOf: "VP8L") // chunk type
webp.append(contentsOf: [8, 0, 0, 0]) // chunk size 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 return webp
} }

Some files were not shown because too many files have changed in this diff Show More