From ae90d57db366583682e3926124590d95b358a195 Mon Sep 17 00:00:00 2001 From: Fabian Boemer Date: Thu, 5 Sep 2024 09:44:13 -0700 Subject: [PATCH] Add ApplicationProtobuf --- Package.swift | 18 + .../ApplicationProtobuf.md | 12 + .../ApplicationProtobuf/ConversionError.swift | 49 + .../ApplicationProtobuf/PirConversion.swift | 349 +++++++ .../PirConversionApi.swift | 76 ++ .../ApplicationProtobuf/PnnsConversion.swift | 337 +++++++ .../PnnsConversionApi.swift | 52 + .../ApplicationProtobuf/generated/README.md | 15 + ...morphic_encryption_api_pir_v1_pir.pb.swift | 832 +++++++++++++++ ...rphic_encryption_api_pnns_v1_pnns.pb.swift | 366 +++++++ ...cryption_api_shared_v1_api_shared.pb.swift | 276 +++++ ...homomorphic_encryption_api_v1_api.pb.swift | 953 ++++++++++++++++++ ...homomorphic_encryption_pir_v1_pir.pb.swift | 713 +++++++++++++ ...c_encryption_pir_v1_pir_algorithm.pb.swift | 84 ++ ...ic_encryption_pir_v1_pir_database.pb.swift | 136 +++ ...momorphic_encryption_pnns_v1_pnns.pb.swift | 204 ++++ ...yption_pnns_v1_pnns_client_config.pb.swift | 155 +++ ..._encryption_pnns_v1_pnns_database.pb.swift | 144 +++ ...tion_pnns_v1_pnns_distance_metric.pb.swift | 74 ++ ...ption_pnns_v1_pnns_matrix_packing.pb.swift | 375 +++++++ ...n_pnns_v1_pnns_processed_database.pb.swift | 121 +++ ...yption_pnns_v1_pnns_server_config.pb.swift | 149 +++ .../protobuf_module_mappings.txtpb | 4 + .../ConversionError.swift | 6 +- .../generated/README.md | 2 +- .../ConversionError.swift | 8 +- .../generated/README.md | 2 +- .../generated/README.md | 2 +- .../PirConversionTests.swift | 118 +++ .../PnnsConversionTests.swift | 266 +++++ Utilities/generate-protobuf-files.sh | 25 +- 31 files changed, 5910 insertions(+), 13 deletions(-) create mode 100644 Sources/ApplicationProtobuf/ApplicationProtobuf.docc/ApplicationProtobuf.md create mode 100644 Sources/ApplicationProtobuf/ConversionError.swift create mode 100644 Sources/ApplicationProtobuf/PirConversion.swift create mode 100644 Sources/ApplicationProtobuf/PirConversionApi.swift create mode 100644 Sources/ApplicationProtobuf/PnnsConversion.swift create mode 100644 Sources/ApplicationProtobuf/PnnsConversionApi.swift create mode 100644 Sources/ApplicationProtobuf/generated/README.md create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pir_v1_pir.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pnns_v1_pnns.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_shared_v1_api_shared.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_v1_api.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_algorithm.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_database.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_client_config.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_database.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_distance_metric.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_matrix_packing.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_processed_database.pb.swift create mode 100644 Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_server_config.pb.swift create mode 100644 Sources/ApplicationProtobuf/protobuf_module_mappings.txtpb create mode 100644 Tests/ApplicationProtobufTests/PirConversionTests.swift create mode 100644 Tests/ApplicationProtobufTests/PnnsConversionTests.swift diff --git a/Package.swift b/Package.swift index 1197605c..95b81efe 100644 --- a/Package.swift +++ b/Package.swift @@ -55,6 +55,7 @@ let package = Package( .library( name: "PrivateNearestNeighborSearchProtobuf", targets: ["PrivateNearestNeighborSearchProtobuf"]), + .library(name: "ApplicationProtobuf", targets: ["ApplicationProtobuf"]), .library(name: "_TestUtilities", targets: ["_TestUtilities"]), .executable(name: "PIRGenerateDatabase", targets: ["PIRGenerateDatabase"]), .executable(name: "PIRProcessDatabase", targets: ["PIRProcessDatabase"]), @@ -132,6 +133,14 @@ let package = Package( .product(name: "SwiftProtobuf", package: "swift-protobuf")], exclude: ["generated/README.md", "protobuf_module_mappings.txtpb"], swiftSettings: librarySettings), + .target( + name: "ApplicationProtobuf", + dependencies: ["HomomorphicEncryptionProtobuf", + "PrivateInformationRetrieval", + "PrivateNearestNeighborSearch", + .product(name: "SwiftProtobuf", package: "swift-protobuf")], + exclude: ["generated/README.md", "protobuf_module_mappings.txtpb"], + swiftSettings: librarySettings), .target( name: "_TestUtilities", dependencies: [ @@ -238,6 +247,15 @@ let package = Package( "PrivateNearestNeighborSearch", "PrivateNearestNeighborSearchProtobuf", ], swiftSettings: executableSettings), + .testTarget( + name: "ApplicationProtobufTests", + dependencies: [ + "ApplicationProtobuf", + "PrivateNearestNeighborSearch", + "PrivateInformationRetrieval", + "_TestUtilities", + .product(name: "SwiftProtobuf", package: "swift-protobuf"), + ], swiftSettings: executableSettings), ]) // MARK: - Benchmarks diff --git a/Sources/ApplicationProtobuf/ApplicationProtobuf.docc/ApplicationProtobuf.md b/Sources/ApplicationProtobuf/ApplicationProtobuf.docc/ApplicationProtobuf.md new file mode 100644 index 00000000..5d63ab47 --- /dev/null +++ b/Sources/ApplicationProtobuf/ApplicationProtobuf.docc/ApplicationProtobuf.md @@ -0,0 +1,12 @@ +# ``ApplicationProtobuf`` + +Protocol buffer support for HE applications, including `PrivateInformationRetrieval` and `PrivateNearestNeighborSearch` + +## Overview +`ApplicationProtobuf` contains supports for using [PrivateInformationRetrieval](https://swiftpackageindex.com/apple/swift-homomorphic-encryption/main/documentation/privateinformationretrieval) and [PrivateNearestNeighborSearch](https://swiftpackageindex.com/apple/swift-homomorphic-encryption/main/documentation/privatenearestneighborsearch) with [protocol buffers](https://protobuf.dev/), commonly referred to as `protobuf`. +This module contains: +* the generated Swift code to use the protobuf types. +* conversion between protobuf types and [PrivateInformationRetrieval](https://swiftpackageindex.com/apple/swift-homomorphic-encryption/main/documentation/privateinformationretrieval) runtime types. +* conversion between protobuf types and [PrivateNearestNeighborSearch](https://swiftpackageindex.com/apple/swift-homomorphic-encryption/main/documentation/privatenearestneighborsearch) runtime types. + +The protobuf schemas are defined at [https://github.com/apple/swift-homomorphic-encryption-protobuf](https://github.com/apple/swift-homomorphic-encryption-protobuf). diff --git a/Sources/ApplicationProtobuf/ConversionError.swift b/Sources/ApplicationProtobuf/ConversionError.swift new file mode 100644 index 00000000..247dc8fd --- /dev/null +++ b/Sources/ApplicationProtobuf/ConversionError.swift @@ -0,0 +1,49 @@ +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +/// Error type when converting between protobuf and native objects. +public enum ConversionError: Error { + case unrecognizedEnumValue(enum: any Enum.Type, value: Int) + case unsetField(field: String, message: any Message.Type) + case unsetOneof(oneof: any Message.Type, field: String) + case unspecifiedEnumValue(enum: any Enum.Type) +} + +extension ConversionError { + static func unsetOneof(oneof: any Message.Type, field: AnyKeyPath) -> Self { + .unsetOneof(oneof: oneof, field: String(reflecting: field)) + } + + static func unsetField(_ field: AnyKeyPath, in message: any Message.Type) -> Self { + .unsetField(field: String(reflecting: field), message: message) + } +} + +extension ConversionError: LocalizedError { + public var errorDescription: String? { + switch self { + case let .unrecognizedEnumValue(enum: enumeration, value): + "Unrecognized value \(value) in enum \(enumeration)" + case let .unsetField(field, message): + "Unset field \(field) in message \(message)" + case let .unsetOneof(oneof, field): + "Unset oneof in message \(oneof) for field \(field)" + case let .unspecifiedEnumValue(enum: enumeration): + "Unspecified value for enum \(enumeration)" + } + } +} diff --git a/Sources/ApplicationProtobuf/PirConversion.swift b/Sources/ApplicationProtobuf/PirConversion.swift new file mode 100644 index 00000000..86c3277f --- /dev/null +++ b/Sources/ApplicationProtobuf/PirConversion.swift @@ -0,0 +1,349 @@ +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import _CryptoExtras +import Crypto +import Foundation +import HomomorphicEncryption +import PrivateInformationRetrieval +import SwiftProtobuf + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices { + /// Converts the protobuf object to a native type. + /// - Parameter context: Context to associate with the native type. + /// - Returns: The converted native type. + /// - Throws: Error upon invalid protobuf object. + public func native(context: Context) throws -> Query { + let ciphertexts: [Scheme.CanonicalCiphertext] = try ciphertexts.map { ciphertext in + let serializedCiphertext: SerializedCiphertext = try ciphertext.native() + return try Ciphertext( + deserialize: serializedCiphertext, + context: context) + } + return Query(ciphertexts: ciphertexts, indicesCount: Int(numPirCalls)) + } +} + +extension Query { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices { + try Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices.with { encryptedIndices in + encryptedIndices.ciphertexts = try ciphertexts.map { ciphertext in + try ciphertext.serialize().proto() + } + encryptedIndices.numPirCalls = UInt64(indicesCount) + } + } +} + +extension ProcessedDatabaseWithParameters { + /// Converts the native processed database with parameters into protobuf object that contains only the parameters. + /// - Parameter context: The context that was used to create processed database. + /// - Returns: The PIR parameters protobuf object. + /// - Throws: Error when the parameters cannot be represented as a protobuf object. + public func proto(context: Context) throws -> Apple_SwiftHomomorphicEncryption_Pir_V1_PirParameters { + let encryptionParameters = context.encryptionParameters + return try Apple_SwiftHomomorphicEncryption_Pir_V1_PirParameters.with { params in + params.encryptionParameters = try encryptionParameters.proto(scheme: Scheme.self) + params.numEntries = UInt64(pirParameter.entryCount) + params.entrySize = UInt64(pirParameter.entrySizeInBytes) + params.dimensions = pirParameter.dimensions.map(UInt64.init) + if let keywordPirParameter { + params.keywordPirParams = keywordPirParameter.proto() + } + params.algorithm = algorithm.proto() + params.batchSize = UInt64(pirParameter.batchSize) + params.evaluationKeyConfig = try evaluationKeyConfig + .proto(encryptionParameters: encryptionParameters, scheme: Scheme.self) + params.keyCompressionStrategy = .unspecified + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error when the parameters cannot be represented as a protobuf object. + public func native() throws -> KeywordPirParameter { + let symmetricPirClientConfig = hasSymmetricPirClientConfig ? try symmetricPirClientConfig.native() : nil + return KeywordPirParameter( + hashFunctionCount: Int(numHashFunctions), + shardingFunction: shardingFunction.native(), + symmetricPirClientConfig: symmetricPirClientConfig) + } +} + +extension KeywordPirParameter { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters { + Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters.with { params in + params.numHashFunctions = UInt64(hashFunctionCount) + params.shardingFunction = shardingFunction.proto() + if let symmetricPirClientConfig { + params.symmetricPirClientConfig = symmetricPirClientConfig.proto() + } + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() -> ShardingFunction { + switch function { + case .sha256: + .sha256 + case let .doubleMod(doubleMod): + .doubleMod(otherShardCount: Int(doubleMod.otherShardCount)) + case .none: + .sha256 + } + } +} + +extension ShardingFunction { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction { + Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction.with { shardingFunction in + shardingFunction.function = switch self.function { + case .sha256: + .sha256(Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256()) + case let .doubleMod(otherShardCount: otherShardCount): + .doubleMod(Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod.with { doubleMod in + doubleMod.otherShardCount = UInt32(otherShardCount) + }) + } + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() throws -> SymmetricPirClientConfig { + switch configType { + case .unspecified: + throw ConversionError + .unspecifiedEnumValue(enum: Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirConfigType.self) + case .oprfP384AesGcm192Nonce96Tag128: + return SymmetricPirClientConfig( + serverPublicKey: [UInt8](serverPublicKey), + configType: .OPRF_P384_AES_GCM_192_NONCE_96_TAG_128) + case let .UNRECOGNIZED(value): + throw ConversionError.unrecognizedEnumValue( + enum: Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirConfigType.self, + value: value) + } + } +} + +extension SymmetricPirClientConfig { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig { + Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig.with { config in + config.serverPublicKey = Data(serverPublicKey) + switch configType { + case .OPRF_P384_AES_GCM_192_NONCE_96_TAG_128: + config.configType = .oprfP384AesGcm192Nonce96Tag128 + } + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PirParameters { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() -> IndexPirParameter { + IndexPirParameter( + entryCount: Int(numEntries), + entrySizeInBytes: Int(entrySize), + dimensions: dimensions.map(Int.init), + batchSize: Int(batchSize), + evaluationKeyConfig: evaluationKeyConfig.native()) + } + + /// Converts the protobuf object into a native type. + /// - Parameter database: The database to use. + /// - Returns: A database with parameters. + /// - Throws: Error when the protobuf object cannot be represented. + public func native(database: ProcessedDatabase) throws + -> ProcessedDatabaseWithParameters + { + try ProcessedDatabaseWithParameters( + database: database, + algorithm: algorithm.native(), + evaluationKeyConfig: evaluationKeyConfig.native(), + pirParameter: native(), + keywordPirParameter: hasKeywordPirParams ? keywordPirParams.native() : nil) + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() throws -> PirAlgorithm { + switch self { + case .aclsPir: PirAlgorithm.aclsPir + case .mulPir: PirAlgorithm.mulPir + case let .UNRECOGNIZED(value): + throw ConversionError.unrecognizedEnumValue(enum: Self.self, value: value) + } + } +} + +extension PirAlgorithm { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm { + switch self { + case .aclsPir: Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm.aclsPir + case .mulPir: Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm.mulPir + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() throws -> PirKeyCompressionStrategy { + switch self { + case .unspecified: PirKeyCompressionStrategy.noCompression + case .hybridCompression: PirKeyCompressionStrategy.hybridCompression + case .maximumCompression: PirKeyCompressionStrategy.maxCompression + case let .UNRECOGNIZED(value): + throw ConversionError.unrecognizedEnumValue(enum: Self.self, value: value) + } + } +} + +extension PirKeyCompressionStrategy { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy { + switch self { + case .noCompression: Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy.unspecified + case .hybridCompression: Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy.hybridCompression + case .maxCompression: Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy.maximumCompression + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() -> KeywordValuePair { + KeywordValuePair(keyword: Array(keyword), value: Array(value)) + } +} + +extension KeywordValuePair { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow { + Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow.with { row in + row.keyword = Data(keyword) + row.value = Data(value) + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() -> [KeywordValuePair] { + rows.map { row in row.native() } + } +} + +extension [KeywordValuePair] { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase { + Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase.with { database in + database.rows = self.map { $0.proto() } + } + } +} + +extension [KeywordValuePair.Keyword: KeywordValuePair.Value] { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase { + Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase.with { database in + database.rows = self.map { row in KeywordValuePair(keyword: row.key, value: row.value).proto() } + } + } +} + +extension Query { + package func size() throws -> Int { + try proto().serializedData().count + } +} + +extension Response { + package func size() throws -> Int { + try proto().serializedData().count + } +} + +extension EvaluationKey { + package func size() throws -> Int { + try serialize().proto().serializedData().count + } +} + +extension OprfQuery { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest { + Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest.with { request in + request.queryElement = oprfRepresentation + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error when the protobuf object cannot be represented. + public func native() throws -> OprfQuery { + try OprfQuery(oprfRepresentation: queryElement) + } +} + +extension OprfResponse { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse { + Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse.with { response in + response.evaluatedElement = evaluatedElement.oprfRepresentation + response.proof = proof.rawRepresentation + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error when the protobuf object cannot be represented. + public func native() throws -> OprfResponse { + try OprfResponse(rawRepresentation: evaluatedElement + proof) + } +} diff --git a/Sources/ApplicationProtobuf/PirConversionApi.swift b/Sources/ApplicationProtobuf/PirConversionApi.swift new file mode 100644 index 00000000..f9b00b8a --- /dev/null +++ b/Sources/ApplicationProtobuf/PirConversionApi.swift @@ -0,0 +1,76 @@ +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import HomomorphicEncryption +import HomomorphicEncryptionProtobuf +import PrivateInformationRetrieval + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse { + /// Converts the protobuf object to a native type. + /// - Parameter context: Context to associate with the native type. + /// - Returns: The converted native type. + /// - Throws: Error upon invalid protobuf object. + public func native(context: Context) throws -> Response { + let ciphertexts: [[Scheme.CoeffCiphertext]] = try replies.map { reply in + let serializedCiphertexts: [SerializedCiphertext] = try reply.native() + return try serializedCiphertexts.map { serialized in + try Scheme.CoeffCiphertext(deserialize: serialized, context: context, moduliCount: 1) + } + } + return Response(ciphertexts: ciphertexts) + } +} + +extension Response { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse { + try Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse.with { pirResponse in + pirResponse.replies = try ciphertexts.map { reply in + try reply.map { try $0.serialize(forDecryption: true) }.proto() + } + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig { + /// Converts the protobuf object to a native type. + /// - Parameters: + /// - batchSize: Number of queries in a batch. + /// - evaluationKeyConfig: Evaluation key configuration + /// - Returns: The converted native type. + public func native(batchSize: Int, evaluationKeyConfig: EvaluationKeyConfig) -> IndexPirParameter { + IndexPirParameter( + entryCount: Int(numEntries), + entrySizeInBytes: Int(entrySize), + dimensions: dimensions.map(Int.init), + batchSize: batchSize, + evaluationKeyConfig: evaluationKeyConfig) + } +} + +extension IndexPirParameter { + /// Converts the native object into a protobuf object. + /// - Parameter shardID: Optional identifier to associate with the shard + /// - Returns: The converted protobuf object. + public func proto(shardID: String = "") -> Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig { + Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig.with { shardConfig in + shardConfig.numEntries = UInt64(entryCount) + shardConfig.entrySize = UInt64(entrySizeInBytes) + shardConfig.dimensions = dimensions.map(UInt64.init) + shardConfig.shardID = shardID + } + } +} diff --git a/Sources/ApplicationProtobuf/PnnsConversion.swift b/Sources/ApplicationProtobuf/PnnsConversion.swift new file mode 100644 index 00000000..aaebf4c8 --- /dev/null +++ b/Sources/ApplicationProtobuf/PnnsConversion.swift @@ -0,0 +1,337 @@ +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation + +import HomomorphicEncryption +import PrivateNearestNeighborSearch + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon unsupported object. + public func native() throws -> DistanceMetric { + switch self { + case .cosineSimilarity: + .cosineSimilarity + case let .UNRECOGNIZED(value): + throw ConversionError.unrecognizedEnumValue(enum: Self.self, value: value) + } + } +} + +extension DistanceMetric { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric { + switch self { + case .cosineSimilarity: + Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric.cosineSimilarity + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon unsupported object. + public func native() -> BabyStepGiantStep { + BabyStepGiantStep( + vectorDimension: Int(vectorDimension), + babyStep: Int(babyStep), + giantStep: Int(giantStep)) + } +} + +extension BabyStepGiantStep { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep { + Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep.with { babyStepGiantStep in + babyStepGiantStep.vectorDimension = UInt32(vectorDimension) + babyStepGiantStep.babyStep = UInt32(babyStep) + babyStepGiantStep.giantStep = UInt32(giantStep) + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon unsupported object. + public func native() throws -> MatrixPacking { + guard let matrixPackingType else { + throw ConversionError.unsetOneof(oneof: Self.self, field: \Self.matrixPackingType) + } + switch matrixPackingType { + case .denseColumn: + return MatrixPacking.denseColumn + case .denseRow: + return MatrixPacking.denseRow + case let .diagonal(diagonal): + guard diagonal.hasBabyStepGiantStep else { + throw ConversionError.unsetField(\Self.diagonal.babyStepGiantStep, in: Self.self) + } + let bsgs = diagonal.babyStepGiantStep.native() + return MatrixPacking.diagonal(babyStepGiantStep: bsgs) + } + } +} + +extension MatrixPacking { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking { + Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking.with { packing in + switch self { + case .denseColumn: + let protoDenseColumn = Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn() + packing.matrixPackingType = .denseColumn(protoDenseColumn) + case .denseRow: + let protoDenseRow = Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow() + packing.matrixPackingType = .denseRow(protoDenseRow) + case let .diagonal(babyStepGiantStep): + let diagonal = Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal.with { diagonalPacking in + diagonalPacking.babyStepGiantStep = babyStepGiantStep.proto() + } + packing.matrixPackingType = .diagonal(diagonal) + } + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon unsupported object. + public func native() throws -> ClientConfig { + guard hasEncryptionParameters else { + throw ConversionError.unsetField(\Self.encryptionParameters, in: Self.self) + } + return try ClientConfig( + encryptionParameters: encryptionParameters.native(), + scalingFactor: Int(scalingFactor), + queryPacking: queryPacking.native(), + vectorDimension: Int(vectorDimension), + evaluationKeyConfig: EvaluationKeyConfig(galoisElements: galoisElements.map { Int($0) }), + distanceMetric: distanceMetric.native(), + extraPlaintextModuli: extraPlaintextModuli.map { Scheme.Scalar($0) }) + } +} + +extension ClientConfig { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig { + try Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig.with { config in + config.encryptionParameters = try encryptionParameters[0].proto(scheme: Scheme.self) + config.scalingFactor = UInt64(scalingFactor) + config.queryPacking = try queryPacking.proto() + config.vectorDimension = UInt32(vectorDimension) + config.galoisElements = evaluationKeyConfig.galoisElements.map { UInt32($0) } + config.distanceMetric = distanceMetric.proto() + config.extraPlaintextModuli = extraPlaintextModuli.map { UInt64($0) } + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon unsupported object. + public func native() throws -> ServerConfig { + guard hasClientConfig else { + throw ConversionError.unsetField(\Self.clientConfig, in: Self.self) + } + return try ServerConfig( + clientConfig: clientConfig.native(), + databasePacking: databasePacking.native()) + } +} + +extension ServerConfig { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig { + try Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig + .with { config in + config.clientConfig = try clientConfig.proto() + config.databasePacking = try databasePacking.proto() + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() -> DatabaseRow { + DatabaseRow( + entryId: entryID, + entryMetadata: Array(entryMetadata), + vector: vector) + } +} + +extension DatabaseRow { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow { + Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow.with { row in + row.entryID = entryId + row.entryMetadata = Data(entryMetadata) + row.vector = vector + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_Database { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + public func native() -> Database { + Database(rows: rows.map { row in row.native() }) + } +} + +extension Database { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + public func proto() -> Apple_SwiftHomomorphicEncryption_Pnns_V1_Database { + Apple_SwiftHomomorphicEncryption_Pnns_V1_Database.with { database in + database.rows = rows.map { row in row.proto() } + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon upon invalid object. + public func native() throws -> SerializedPlaintextMatrix { + let dimensions = try MatrixDimensions( + rowCount: Int(numRows), + columnCount: Int(numColumns)) + return try SerializedPlaintextMatrix( + dimensions: dimensions, + packing: packing.native(), + plaintexts: plaintexts.map { plaintext in plaintext.native() }) + } +} + +extension SerializedPlaintextMatrix { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix { + try Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix.with { protoMatrix in + protoMatrix.numRows = UInt32(dimensions.rowCount) + protoMatrix.numColumns = UInt32(dimensions.columnCount) + protoMatrix.plaintexts = plaintexts.map { plaintext in plaintext.proto() } + protoMatrix.packing = try packing.proto() + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon upon invalid object. + public func native() throws -> SerializedCiphertextMatrix { + let dimensions = try MatrixDimensions( + rowCount: Int(numRows), + columnCount: Int(numColumns)) + return try SerializedCiphertextMatrix( + dimensions: dimensions, + packing: packing.native(), + ciphertexts: ciphertexts.map { ciphertext in try ciphertext.native() }) + } +} + +extension SerializedCiphertextMatrix { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix { + try Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix.with { protoMatrix in + protoMatrix.numRows = UInt32(dimensions.rowCount) + protoMatrix.numColumns = UInt32(dimensions.columnCount) + protoMatrix.ciphertexts = ciphertexts.map { ciphertext in ciphertext.proto() } + protoMatrix.packing = try packing.proto() + } + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedProcessedDatabase { + /// Converts the protobuf object to a native type. + /// - Returns: The converted native type. + /// - Throws: Error upon upon invalid object. + public func native() throws -> SerializedProcessedDatabase { + try SerializedProcessedDatabase( + plaintextMatrices: plaintextMatrices.map { matrix in try matrix.native() }, + entryIds: entryIds, + entryMetadatas: entryMetadatas.map { metadata in Array(metadata) }, + serverConfig: serverConfig.native()) + } +} + +extension SerializedProcessedDatabase { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedProcessedDatabase { + try Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedProcessedDatabase + .with { protoDatabase in + protoDatabase.plaintextMatrices = try plaintextMatrices.map { matrix in try matrix.proto() } + protoDatabase.entryIds = entryIds + protoDatabase.entryMetadatas = entryMetadatas.map { metadata in Data(metadata) } + protoDatabase.serverConfig = try serverConfig.proto() + } + } +} + +extension Query { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> [Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix] { + try ciphertextMatrices.map { matrix in try matrix.serialize().proto() } + } +} + +extension [Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix] { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func native(context: Context) throws -> Query { + let matrices: [CiphertextMatrix] = try map { matrix in + let native: SerializedCiphertextMatrix = try matrix.native() + return try CiphertextMatrix(deserialize: native, context: context) + } + return Query(ciphertextMatrices: matrices) + } +} + +extension Query { + package func size() throws -> Int { + try proto().map { matrix in try matrix.serializedData().count }.sum() + } +} + +extension Response { + package func size() throws -> Int { + try proto().serializedData().count + } +} diff --git a/Sources/ApplicationProtobuf/PnnsConversionApi.swift b/Sources/ApplicationProtobuf/PnnsConversionApi.swift new file mode 100644 index 00000000..2aa3d6db --- /dev/null +++ b/Sources/ApplicationProtobuf/PnnsConversionApi.swift @@ -0,0 +1,52 @@ +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation + +import HomomorphicEncryption +import HomomorphicEncryptionProtobuf +import PrivateNearestNeighborSearch + +extension Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse { + /// Converts the protobuf object to a native type. + /// - Parameter contexts: Contexts to associate with the native type; one context per plaintext modulus. + /// - Returns: The converted native type. + /// - Throws: Error upon invalid protobuf object. + public func native(contexts: [Context]) throws -> Response { + precondition(contexts.count == reply.count) + let matrices: [CiphertextMatrix] = try zip(reply, contexts).map { matrix, context in + let serialized: SerializedCiphertextMatrix = try matrix.native() + return try CiphertextMatrix(deserialize: serialized, context: context, moduliCount: 1) + } + return Response( + ciphertextMatrices: matrices, + entryIds: entryIds, + entryMetadatas: entryMetadatas.map { metadata in Array(metadata) }) + } +} + +extension Response { + /// Converts the native object into a protobuf object. + /// - Returns: The converted protobuf object. + /// - Throws: Error upon unsupported object. + public func proto() throws -> Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse { + try Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse.with { pnnsResponse in + pnnsResponse.reply = try ciphertextMatrices.map { matrix in + try matrix.serialize(forDecryption: true).proto() + } + pnnsResponse.entryIds = entryIds + pnnsResponse.entryMetadatas = entryMetadatas.map { bytes in Data(bytes) } + } + } +} diff --git a/Sources/ApplicationProtobuf/generated/README.md b/Sources/ApplicationProtobuf/generated/README.md new file mode 100644 index 00000000..6462d949 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/README.md @@ -0,0 +1,15 @@ +# Generated files + +Files in this directory are generated using swift-protobuf. +See the [dependencies](../../../README.md#dependencies) for the swift-protobuf version. + +## Requirements +* [swift-protobuf](https://github.com/apple/swift-protobuf) + +## Generate Swift files +To generate the Swift files: +1. Change directory to `` +2. Run +```sh +./Utilities/generate-protobuf-files.sh +``` diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pir_v1_pir.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pir_v1_pir.pb.swift new file mode 100644 index 00000000..0066cb54 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pir_v1_pir.pb.swift @@ -0,0 +1,832 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/api/pir/v1/pir.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +import HomomorphicEncryptionProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Configuration for one shard of the PIR database. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Number of entries in the shard. + public var numEntries: UInt64 = 0 + + /// Size in bytes of entries in the shard. + public var entrySize: UInt64 = 0 + + /// Dimensions that make up the hypercube. + public var dimensions: [UInt64] = [] + + /// Unique identifier for the shard. + public var shardID: String { + get {return _shardID ?? String()} + set {_shardID = newValue} + } + /// Returns true if `shardID` has been explicitly set. + public var hasShardID: Bool {return self._shardID != nil} + /// Clears the value of `shardID`. Subsequent reads from it will return its default value. + public mutating func clearShardID() {self._shardID = nil} + + /// Whether to compress vectorized PIR response. + public var compressVectorizedPirResponse: Bool { + get {return _compressVectorizedPirResponse ?? false} + set {_compressVectorizedPirResponse = newValue} + } + /// Returns true if `compressVectorizedPirResponse` has been explicitly set. + public var hasCompressVectorizedPirResponse: Bool {return self._compressVectorizedPirResponse != nil} + /// Clears the value of `compressVectorizedPirResponse`. Subsequent reads from it will return its default value. + public mutating func clearCompressVectorizedPirResponse() {self._compressVectorizedPirResponse = nil} + + /// The additional "batching" introduced in vectorized pir to accommodate large entry size. + public var vectorizedPirInternalBatchingSize: UInt64 { + get {return _vectorizedPirInternalBatchingSize ?? 0} + set {_vectorizedPirInternalBatchingSize = newValue} + } + /// Returns true if `vectorizedPirInternalBatchingSize` has been explicitly set. + public var hasVectorizedPirInternalBatchingSize: Bool {return self._vectorizedPirInternalBatchingSize != nil} + /// Clears the value of `vectorizedPirInternalBatchingSize`. Subsequent reads from it will return its default value. + public mutating func clearVectorizedPirInternalBatchingSize() {self._vectorizedPirInternalBatchingSize = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _shardID: String? = nil + fileprivate var _compressVectorizedPirResponse: Bool? = nil + fileprivate var _vectorizedPirInternalBatchingSize: UInt64? = nil +} + +/// Configuration for one PIR usecase. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig: @unchecked Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Encryption parameters. + public var encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters { + get {return _storage._encryptionParameters ?? HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters()} + set {_uniqueStorage()._encryptionParameters = newValue} + } + /// Returns true if `encryptionParameters` has been explicitly set. + public var hasEncryptionParameters: Bool {return _storage._encryptionParameters != nil} + /// Clears the value of `encryptionParameters`. Subsequent reads from it will return its default value. + public mutating func clearEncryptionParameters() {_uniqueStorage()._encryptionParameters = nil} + + /// Configuration for each shard; can be overridden by `pir_shard_configs` (field 10). + public var shardConfigs: [Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig] { + get {return _storage._shardConfigs} + set {_uniqueStorage()._shardConfigs = newValue} + } + + /// Parameters specific to KeywordPIR. + public var keywordPirParams: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters { + get {return _storage._keywordPirParams ?? Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters()} + set {_uniqueStorage()._keywordPirParams = newValue} + } + /// Returns true if `keywordPirParams` has been explicitly set. + public var hasKeywordPirParams: Bool {return _storage._keywordPirParams != nil} + /// Clears the value of `keywordPirParams`. Subsequent reads from it will return its default value. + public mutating func clearKeywordPirParams() {_uniqueStorage()._keywordPirParams = nil} + + /// Server-side PIR algorithm. + public var algorithm: Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm { + get {return _storage._algorithm} + set {_uniqueStorage()._algorithm = newValue} + } + + /// Maximum number of queries allowed in a single request. + public var batchSize: UInt64 { + get {return _storage._batchSize} + set {_uniqueStorage()._batchSize = newValue} + } + + /// Hash of EvaluationKeyConfig. + public var evaluationKeyConfigHash: Data { + get {return _storage._evaluationKeyConfigHash} + set {_uniqueStorage()._evaluationKeyConfigHash = newValue} + } + + /// Configuration for each shard; overrides `shard_configs` (field 2). + public var pirShardConfigs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs { + get {return _storage._pirShardConfigs ?? Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs()} + set {_uniqueStorage()._pirShardConfigs = newValue} + } + /// Returns true if `pirShardConfigs` has been explicitly set. + public var hasPirShardConfigs: Bool {return _storage._pirShardConfigs != nil} + /// Clears the value of `pirShardConfigs`. Subsequent reads from it will return its default value. + public mutating func clearPirShardConfigs() {_uniqueStorage()._pirShardConfigs = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _storage = _StorageClass.defaultInstance +} + +/// Configuration for PIR shards. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Different shard configuration formats. + public var shardConfigs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs.OneOf_ShardConfigs? = nil + + /// Repeated shard configuration. + public var repeatedShardConfig: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig { + get { + if case .repeatedShardConfig(let v)? = shardConfigs {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig() + } + set {shardConfigs = .repeatedShardConfig(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// Different shard configuration formats. + public enum OneOf_ShardConfigs: Equatable, Sendable { + /// Repeated shard configuration. + case repeatedShardConfig(Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig) + + } + + public init() {} +} + +/// Every shard configuration is the same. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Shard configuration for all the shards. + public var shardConfig: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig { + get {return _shardConfig ?? Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig()} + set {_shardConfig = newValue} + } + /// Returns true if `shardConfig` has been explicitly set. + public var hasShardConfig: Bool {return self._shardConfig != nil} + /// Clears the value of `shardConfig`. Subsequent reads from it will return its default value. + public mutating func clearShardConfig() {self._shardConfig = nil} + + /// Number of shards. + public var shardCount: UInt32 = 0 + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _shardConfig: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig? = nil +} + +/// PIR Request. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Shard index where this request should be routed. Can be overridden by shard_id. + public var shardIndex: UInt32 = 0 + + /// Encrypted query. + public var query: Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices { + get {return _query ?? Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices()} + set {_query = newValue} + } + /// Returns true if `query` has been explicitly set. + public var hasQuery: Bool {return self._query != nil} + /// Clears the value of `query`. Subsequent reads from it will return its default value. + public mutating func clearQuery() {self._query = nil} + + /// Evaluation key metadata. + public var evaluationKeyMetadata: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata { + get {return _evaluationKeyMetadata ?? Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata()} + set {_evaluationKeyMetadata = newValue} + } + /// Returns true if `evaluationKeyMetadata` has been explicitly set. + public var hasEvaluationKeyMetadata: Bool {return self._evaluationKeyMetadata != nil} + /// Clears the value of `evaluationKeyMetadata`. Subsequent reads from it will return its default value. + public mutating func clearEvaluationKeyMetadata() {self._evaluationKeyMetadata = nil} + + /// Hash of the `PIRConfig` used to construct the query. + public var configurationHash: Data = Data() + + /// If set, route request to a shard with this `shard_id` instead of `shard_index`. + public var shardID: String { + get {return _shardID ?? String()} + set {_shardID = newValue} + } + /// Returns true if `shardID` has been explicitly set. + public var hasShardID: Bool {return self._shardID != nil} + /// Clears the value of `shardID`. Subsequent reads from it will return its default value. + public mutating func clearShardID() {self._shardID = nil} + + /// If set, evaluation key to query with. Will override evaluation key stored server-side. + public var evaluationKey: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey { + get {return _evaluationKey ?? Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey()} + set {_evaluationKey = newValue} + } + /// Returns true if `evaluationKey` has been explicitly set. + public var hasEvaluationKey: Bool {return self._evaluationKey != nil} + /// Clears the value of `evaluationKey`. Subsequent reads from it will return its default value. + public mutating func clearEvaluationKey() {self._evaluationKey = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _query: Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices? = nil + fileprivate var _evaluationKeyMetadata: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata? = nil + fileprivate var _shardID: String? = nil + fileprivate var _evaluationKey: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey? = nil +} + +/// PIR Response. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Encrypted replies, each of which is a ciphertext vector. + public var replies: [HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_SerializedCiphertextVec] = [] + + /// Stash of entries with the most recent updates that have not yet reached the processed database. + public var stash: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_StashOfEntries { + get {return _stash ?? Apple_SwiftHomomorphicEncryption_Api_Pir_V1_StashOfEntries()} + set {_stash = newValue} + } + /// Returns true if `stash` has been explicitly set. + public var hasStash: Bool {return self._stash != nil} + /// Clears the value of `stash`. Subsequent reads from it will return its default value. + public mutating func clearStash() {self._stash = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _stash: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_StashOfEntries? = nil +} + +/// PIR OPRF Request. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Serialized query. + public var queryElement: Data = Data() + + /// Identifier for PirConfig used to construct this request. + public var configID: Data = Data() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// PIR OPRF Response. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Serialized output of OPRF. + public var evaluatedElement: Data = Data() + + /// Proof of OPRF evaluation. + public var proof: Data = Data() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Stash of entries. +/// +/// Stash is meant to be used as temporary storage until we can update the processed database. +public struct Apple_SwiftHomomorphicEncryption_Api_Pir_V1_StashOfEntries: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Sorted list of hashed keywords. + /// + /// hashed_keyword = Truncate(SHA256(keyword)) + public var hashedKeywords: [UInt64] = [] + + /// The values associated with each keyword in the `hashed_keywords` list. Must be in the same order. + public var values: [Data] = [] + + /// Sorted list of hashed keywords that were removed from the dataset. + /// + /// This list contains hashed keywords that were deleted, but may still be present in the processed database. + /// hashed_keyword = Truncate(SHA256(keyword)) + public var removedHashedKeywords: [UInt64] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.api.pir.v1" + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRShardConfig" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}num_entries\0\u{3}entry_size\0\u{1}dimensions\0\u{3}shard_id\0\u{3}compress_vectorized_pir_response\0\u{3}vectorized_pir_internal_batching_size\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt64Field(value: &self.numEntries) }() + case 2: try { try decoder.decodeSingularUInt64Field(value: &self.entrySize) }() + case 3: try { try decoder.decodeRepeatedUInt64Field(value: &self.dimensions) }() + case 4: try { try decoder.decodeSingularStringField(value: &self._shardID) }() + case 5: try { try decoder.decodeSingularBoolField(value: &self._compressVectorizedPirResponse) }() + case 6: try { try decoder.decodeSingularUInt64Field(value: &self._vectorizedPirInternalBatchingSize) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if self.numEntries != 0 { + try visitor.visitSingularUInt64Field(value: self.numEntries, fieldNumber: 1) + } + if self.entrySize != 0 { + try visitor.visitSingularUInt64Field(value: self.entrySize, fieldNumber: 2) + } + if !self.dimensions.isEmpty { + try visitor.visitPackedUInt64Field(value: self.dimensions, fieldNumber: 3) + } + try { if let v = self._shardID { + try visitor.visitSingularStringField(value: v, fieldNumber: 4) + } }() + try { if let v = self._compressVectorizedPirResponse { + try visitor.visitSingularBoolField(value: v, fieldNumber: 5) + } }() + try { if let v = self._vectorizedPirInternalBatchingSize { + try visitor.visitSingularUInt64Field(value: v, fieldNumber: 6) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig) -> Bool { + if lhs.numEntries != rhs.numEntries {return false} + if lhs.entrySize != rhs.entrySize {return false} + if lhs.dimensions != rhs.dimensions {return false} + if lhs._shardID != rhs._shardID {return false} + if lhs._compressVectorizedPirResponse != rhs._compressVectorizedPirResponse {return false} + if lhs._vectorizedPirInternalBatchingSize != rhs._vectorizedPirInternalBatchingSize {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRConfig" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}encryption_parameters\0\u{3}shard_configs\0\u{3}keyword_pir_params\0\u{1}algorithm\0\u{3}batch_size\0\u{3}evaluation_key_config_hash\0\u{4}\u{4}pir_shard_configs\0\u{c}\u{7}\u{1}\u{c}\u{8}\u{1}\u{c}\u{9}\u{1}") + + fileprivate class _StorageClass { + var _encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters? = nil + var _shardConfigs: [Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfig] = [] + var _keywordPirParams: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters? = nil + var _algorithm: Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm = .aclsPir + var _batchSize: UInt64 = 0 + var _evaluationKeyConfigHash: Data = Data() + var _pirShardConfigs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs? = nil + + // This property is used as the initial default value for new instances of the type. + // The type itself is protecting the reference to its storage via CoW semantics. + // This will force a copy to be made of this reference when the first mutation occurs; + // hence, it is safe to mark this as `nonisolated(unsafe)`. + static nonisolated(unsafe) let defaultInstance = _StorageClass() + + private init() {} + + init(copying source: _StorageClass) { + _encryptionParameters = source._encryptionParameters + _shardConfigs = source._shardConfigs + _keywordPirParams = source._keywordPirParams + _algorithm = source._algorithm + _batchSize = source._batchSize + _evaluationKeyConfigHash = source._evaluationKeyConfigHash + _pirShardConfigs = source._pirShardConfigs + } + } + + fileprivate mutating func _uniqueStorage() -> _StorageClass { + if !isKnownUniquelyReferenced(&_storage) { + _storage = _StorageClass(copying: _storage) + } + return _storage + } + + public mutating func decodeMessage(decoder: inout D) throws { + _ = _uniqueStorage() + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &_storage._encryptionParameters) }() + case 2: try { try decoder.decodeRepeatedMessageField(value: &_storage._shardConfigs) }() + case 3: try { try decoder.decodeSingularMessageField(value: &_storage._keywordPirParams) }() + case 4: try { try decoder.decodeSingularEnumField(value: &_storage._algorithm) }() + case 5: try { try decoder.decodeSingularUInt64Field(value: &_storage._batchSize) }() + case 6: try { try decoder.decodeSingularBytesField(value: &_storage._evaluationKeyConfigHash) }() + case 10: try { try decoder.decodeSingularMessageField(value: &_storage._pirShardConfigs) }() + default: break + } + } + } + } + + public func traverse(visitor: inout V) throws { + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = _storage._encryptionParameters { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + if !_storage._shardConfigs.isEmpty { + try visitor.visitRepeatedMessageField(value: _storage._shardConfigs, fieldNumber: 2) + } + try { if let v = _storage._keywordPirParams { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } }() + if _storage._algorithm != .aclsPir { + try visitor.visitSingularEnumField(value: _storage._algorithm, fieldNumber: 4) + } + if _storage._batchSize != 0 { + try visitor.visitSingularUInt64Field(value: _storage._batchSize, fieldNumber: 5) + } + if !_storage._evaluationKeyConfigHash.isEmpty { + try visitor.visitSingularBytesField(value: _storage._evaluationKeyConfigHash, fieldNumber: 6) + } + try { if let v = _storage._pirShardConfigs { + try visitor.visitSingularMessageField(value: v, fieldNumber: 10) + } }() + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig) -> Bool { + if lhs._storage !== rhs._storage { + let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in + let _storage = _args.0 + let rhs_storage = _args.1 + if _storage._encryptionParameters != rhs_storage._encryptionParameters {return false} + if _storage._shardConfigs != rhs_storage._shardConfigs {return false} + if _storage._keywordPirParams != rhs_storage._keywordPirParams {return false} + if _storage._algorithm != rhs_storage._algorithm {return false} + if _storage._batchSize != rhs_storage._batchSize {return false} + if _storage._evaluationKeyConfigHash != rhs_storage._evaluationKeyConfigHash {return false} + if _storage._pirShardConfigs != rhs_storage._pirShardConfigs {return false} + return true + } + if !storagesAreEqual {return false} + } + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRShardConfigs" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}repeated_shard_config\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig? + var hadOneofValue = false + if let current = self.shardConfigs { + hadOneofValue = true + if case .repeatedShardConfig(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.shardConfigs = .repeatedShardConfig(v) + } + }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if case .repeatedShardConfig(let v)? = self.shardConfigs { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRShardConfigs) -> Bool { + if lhs.shardConfigs != rhs.shardConfigs {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRFixedShardConfig" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}shard_config\0\u{3}shard_count\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._shardConfig) }() + case 2: try { try decoder.decodeSingularUInt32Field(value: &self.shardCount) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = self._shardConfig { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + if self.shardCount != 0 { + try visitor.visitSingularUInt32Field(value: self.shardCount, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRFixedShardConfig) -> Bool { + if lhs._shardConfig != rhs._shardConfig {return false} + if lhs.shardCount != rhs.shardCount {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRRequest" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}shard_index\0\u{1}query\0\u{3}evaluation_key_metadata\0\u{3}configuration_hash\0\u{3}shard_id\0\u{3}evaluation_key\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt32Field(value: &self.shardIndex) }() + case 2: try { try decoder.decodeSingularMessageField(value: &self._query) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._evaluationKeyMetadata) }() + case 4: try { try decoder.decodeSingularBytesField(value: &self.configurationHash) }() + case 5: try { try decoder.decodeSingularStringField(value: &self._shardID) }() + case 6: try { try decoder.decodeSingularMessageField(value: &self._evaluationKey) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if self.shardIndex != 0 { + try visitor.visitSingularUInt32Field(value: self.shardIndex, fieldNumber: 1) + } + try { if let v = self._query { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } }() + try { if let v = self._evaluationKeyMetadata { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } }() + if !self.configurationHash.isEmpty { + try visitor.visitSingularBytesField(value: self.configurationHash, fieldNumber: 4) + } + try { if let v = self._shardID { + try visitor.visitSingularStringField(value: v, fieldNumber: 5) + } }() + try { if let v = self._evaluationKey { + try visitor.visitSingularMessageField(value: v, fieldNumber: 6) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest) -> Bool { + if lhs.shardIndex != rhs.shardIndex {return false} + if lhs._query != rhs._query {return false} + if lhs._evaluationKeyMetadata != rhs._evaluationKeyMetadata {return false} + if lhs.configurationHash != rhs.configurationHash {return false} + if lhs._shardID != rhs._shardID {return false} + if lhs._evaluationKey != rhs._evaluationKey {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRResponse" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}replies\0\u{1}stash\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.replies) }() + case 2: try { try decoder.decodeSingularMessageField(value: &self._stash) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !self.replies.isEmpty { + try visitor.visitRepeatedMessageField(value: self.replies, fieldNumber: 1) + } + try { if let v = self._stash { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse) -> Bool { + if lhs.replies != rhs.replies {return false} + if lhs._stash != rhs._stash {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".OPRFRequest" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}query_element\0\u{3}config_id\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularBytesField(value: &self.queryElement) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.configID) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.queryElement.isEmpty { + try visitor.visitSingularBytesField(value: self.queryElement, fieldNumber: 1) + } + if !self.configID.isEmpty { + try visitor.visitSingularBytesField(value: self.configID, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest) -> Bool { + if lhs.queryElement != rhs.queryElement {return false} + if lhs.configID != rhs.configID {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".OPRFResponse" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}evaluated_element\0\u{1}proof\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularBytesField(value: &self.evaluatedElement) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.proof) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.evaluatedElement.isEmpty { + try visitor.visitSingularBytesField(value: self.evaluatedElement, fieldNumber: 1) + } + if !self.proof.isEmpty { + try visitor.visitSingularBytesField(value: self.proof, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse) -> Bool { + if lhs.evaluatedElement != rhs.evaluatedElement {return false} + if lhs.proof != rhs.proof {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pir_V1_StashOfEntries: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".StashOfEntries" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}hashed_keywords\0\u{1}values\0\u{3}removed_hashed_keywords\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedUInt64Field(value: &self.hashedKeywords) }() + case 2: try { try decoder.decodeRepeatedBytesField(value: &self.values) }() + case 3: try { try decoder.decodeRepeatedUInt64Field(value: &self.removedHashedKeywords) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.hashedKeywords.isEmpty { + try visitor.visitPackedUInt64Field(value: self.hashedKeywords, fieldNumber: 1) + } + if !self.values.isEmpty { + try visitor.visitRepeatedBytesField(value: self.values, fieldNumber: 2) + } + if !self.removedHashedKeywords.isEmpty { + try visitor.visitPackedUInt64Field(value: self.removedHashedKeywords, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_StashOfEntries, rhs: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_StashOfEntries) -> Bool { + if lhs.hashedKeywords != rhs.hashedKeywords {return false} + if lhs.values != rhs.values {return false} + if lhs.removedHashedKeywords != rhs.removedHashedKeywords {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pnns_v1_pnns.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pnns_v1_pnns.pb.swift new file mode 100644 index 00000000..3b754cf2 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_pnns_v1_pnns.pb.swift @@ -0,0 +1,366 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/api/pnns/v1/pnns.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +import HomomorphicEncryptionProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Configuration for one PNNS usecase. +public struct Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Encryption parameters. + public var encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters { + get {return _encryptionParameters ?? HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters()} + set {_encryptionParameters = newValue} + } + /// Returns true if `encryptionParameters` has been explicitly set. + public var hasEncryptionParameters: Bool {return self._encryptionParameters != nil} + /// Clears the value of `encryptionParameters`. Subsequent reads from it will return its default value. + public mutating func clearEncryptionParameters() {self._encryptionParameters = nil} + + /// Factor by which to scale floating-point entries to integers. + public var scalingFactor: UInt64 = 0 + + /// Packing for the query. + public var queryPacking: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking { + get {return _queryPacking ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking()} + set {_queryPacking = newValue} + } + /// Returns true if `queryPacking` has been explicitly set. + public var hasQueryPacking: Bool {return self._queryPacking != nil} + /// Clears the value of `queryPacking`. Subsequent reads from it will return its default value. + public mutating func clearQueryPacking() {self._queryPacking = nil} + + /// Number of entries in each vector. + public var vectorDimension: UInt32 = 0 + + /// Metric for computing distances. + public var distanceMetric: Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric = .cosineSimilarity + + /// hash of EvaluationKeyConfig. + public var evaluationKeyConfigHash: Data = Data() + + /// For plaintext CRT, the list of extra plaintext moduli. + /// The first plaintext modulus will be the one in `encryption_parameters`. + public var extraPlaintextModuli: [UInt64] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters? = nil + fileprivate var _queryPacking: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking? = nil +} + +/// PNNS Request. +public struct Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Optionally, the shard indices where this request should be routed. + public var shardIndices: [UInt32] = [] + + /// Encrypted query, one per plaintext CRT component. + public var query: [Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix] = [] + + /// Key metadata. + public var evaluationKeyMetadata: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata { + get {return _evaluationKeyMetadata ?? Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata()} + set {_evaluationKeyMetadata = newValue} + } + /// Returns true if `evaluationKeyMetadata` has been explicitly set. + public var hasEvaluationKeyMetadata: Bool {return self._evaluationKeyMetadata != nil} + /// Clears the value of `evaluationKeyMetadata`. Subsequent reads from it will return its default value. + public mutating func clearEvaluationKeyMetadata() {self._evaluationKeyMetadata = nil} + + /// Identifier for the PNNSConfig used to construct the query. + public var configID: Data = Data() + + /// If set, evaluation key to query with. Will override evaluation key stored server-side. + public var evaluationKey: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey { + get {return _evaluationKey ?? Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey()} + set {_evaluationKey = newValue} + } + /// Returns true if `evaluationKey` has been explicitly set. + public var hasEvaluationKey: Bool {return self._evaluationKey != nil} + /// Clears the value of `evaluationKey`. Subsequent reads from it will return its default value. + public mutating func clearEvaluationKey() {self._evaluationKey = nil} + + /// Optionally, the shard identifiers where this request should be routed. + /// If set, will override `shard_indices`. + public var shardIds: [String] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _evaluationKeyMetadata: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata? = nil + fileprivate var _evaluationKey: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey? = nil +} + +/// PNNS Shard Response. +public struct Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Encrypted reply, one per plaintext CRT component. + public var reply: [Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix] = [] + + /// A list of entry identifiers the server computed similarities for. + public var entryIds: [UInt64] = [] + + /// Metadata for each entry in the database. + public var entryMetadatas: [Data] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// PNNS Response. +public struct Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// PNNS responses from shards. + public var shardResponses: [Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.api.pnns.v1" + +extension Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PNNSConfig" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}encryption_parameters\0\u{3}scaling_factor\0\u{3}query_packing\0\u{3}vector_dimension\0\u{3}distance_metric\0\u{3}evaluation_key_config_hash\0\u{3}extra_plaintext_moduli\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._encryptionParameters) }() + case 2: try { try decoder.decodeSingularUInt64Field(value: &self.scalingFactor) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._queryPacking) }() + case 4: try { try decoder.decodeSingularUInt32Field(value: &self.vectorDimension) }() + case 5: try { try decoder.decodeSingularEnumField(value: &self.distanceMetric) }() + case 6: try { try decoder.decodeSingularBytesField(value: &self.evaluationKeyConfigHash) }() + case 7: try { try decoder.decodeRepeatedUInt64Field(value: &self.extraPlaintextModuli) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = self._encryptionParameters { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + if self.scalingFactor != 0 { + try visitor.visitSingularUInt64Field(value: self.scalingFactor, fieldNumber: 2) + } + try { if let v = self._queryPacking { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } }() + if self.vectorDimension != 0 { + try visitor.visitSingularUInt32Field(value: self.vectorDimension, fieldNumber: 4) + } + if self.distanceMetric != .cosineSimilarity { + try visitor.visitSingularEnumField(value: self.distanceMetric, fieldNumber: 5) + } + if !self.evaluationKeyConfigHash.isEmpty { + try visitor.visitSingularBytesField(value: self.evaluationKeyConfigHash, fieldNumber: 6) + } + if !self.extraPlaintextModuli.isEmpty { + try visitor.visitPackedUInt64Field(value: self.extraPlaintextModuli, fieldNumber: 7) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig, rhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig) -> Bool { + if lhs._encryptionParameters != rhs._encryptionParameters {return false} + if lhs.scalingFactor != rhs.scalingFactor {return false} + if lhs._queryPacking != rhs._queryPacking {return false} + if lhs.vectorDimension != rhs.vectorDimension {return false} + if lhs.distanceMetric != rhs.distanceMetric {return false} + if lhs.evaluationKeyConfigHash != rhs.evaluationKeyConfigHash {return false} + if lhs.extraPlaintextModuli != rhs.extraPlaintextModuli {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PNNSRequest" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}shard_indices\0\u{1}query\0\u{3}evaluation_key_metadata\0\u{3}config_id\0\u{3}evaluation_key\0\u{3}shard_ids\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedUInt32Field(value: &self.shardIndices) }() + case 2: try { try decoder.decodeRepeatedMessageField(value: &self.query) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._evaluationKeyMetadata) }() + case 4: try { try decoder.decodeSingularBytesField(value: &self.configID) }() + case 5: try { try decoder.decodeSingularMessageField(value: &self._evaluationKey) }() + case 6: try { try decoder.decodeRepeatedStringField(value: &self.shardIds) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !self.shardIndices.isEmpty { + try visitor.visitPackedUInt32Field(value: self.shardIndices, fieldNumber: 1) + } + if !self.query.isEmpty { + try visitor.visitRepeatedMessageField(value: self.query, fieldNumber: 2) + } + try { if let v = self._evaluationKeyMetadata { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } }() + if !self.configID.isEmpty { + try visitor.visitSingularBytesField(value: self.configID, fieldNumber: 4) + } + try { if let v = self._evaluationKey { + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + } }() + if !self.shardIds.isEmpty { + try visitor.visitRepeatedStringField(value: self.shardIds, fieldNumber: 6) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest, rhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest) -> Bool { + if lhs.shardIndices != rhs.shardIndices {return false} + if lhs.query != rhs.query {return false} + if lhs._evaluationKeyMetadata != rhs._evaluationKeyMetadata {return false} + if lhs.configID != rhs.configID {return false} + if lhs._evaluationKey != rhs._evaluationKey {return false} + if lhs.shardIds != rhs.shardIds {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PNNSShardResponse" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}reply\0\u{3}entry_ids\0\u{3}entry_metadatas\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.reply) }() + case 2: try { try decoder.decodeRepeatedUInt64Field(value: &self.entryIds) }() + case 3: try { try decoder.decodeRepeatedBytesField(value: &self.entryMetadatas) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.reply.isEmpty { + try visitor.visitRepeatedMessageField(value: self.reply, fieldNumber: 1) + } + if !self.entryIds.isEmpty { + try visitor.visitPackedUInt64Field(value: self.entryIds, fieldNumber: 2) + } + if !self.entryMetadatas.isEmpty { + try visitor.visitRepeatedBytesField(value: self.entryMetadatas, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse, rhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSShardResponse) -> Bool { + if lhs.reply != rhs.reply {return false} + if lhs.entryIds != rhs.entryIds {return false} + if lhs.entryMetadatas != rhs.entryMetadatas {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PNNSResponse" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}shard_responses\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.shardResponses) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.shardResponses.isEmpty { + try visitor.visitRepeatedMessageField(value: self.shardResponses, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse, rhs: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse) -> Bool { + if lhs.shardResponses != rhs.shardResponses {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_shared_v1_api_shared.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_shared_v1_api_shared.pb.swift new file mode 100644 index 00000000..95c704ed --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_shared_v1_api_shared.pb.swift @@ -0,0 +1,276 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/api/shared/v1/api_shared.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +import HomomorphicEncryptionProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Evaluation key metadata. +public struct Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Timestamp of the (secret) key generation, seconds from Unix epoch. + public var timestamp: UInt64 = 0 + + /// Key identifier (SHA256 of `EvaluationKeyConfig`). + public var identifier: Data = Data() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Status of the evaluation key. +public struct Apple_SwiftHomomorphicEncryption_Api_Shared_V1_KeyStatus: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// When was this key last updated (seconds from Unix epoch), 0 when key is missing. + public var timestamp: UInt64 = 0 + + /// Configuration for the key. + public var keyConfig: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EvaluationKeyConfig { + get {return _keyConfig ?? HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EvaluationKeyConfig()} + set {_keyConfig = newValue} + } + /// Returns true if `keyConfig` has been explicitly set. + public var hasKeyConfig: Bool {return self._keyConfig != nil} + /// Clears the value of `keyConfig`. Subsequent reads from it will return its default value. + public mutating func clearKeyConfig() {self._keyConfig = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _keyConfig: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EvaluationKeyConfig? = nil +} + +/// Container for multiple evaluation keys. +public struct Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeys: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Evaluation keys. + public var keys: [Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Evaluation key upload. +public struct Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Metadata for the key. + public var metadata: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata { + get {return _metadata ?? Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata()} + set {_metadata = newValue} + } + /// Returns true if `metadata` has been explicitly set. + public var hasMetadata: Bool {return self._metadata != nil} + /// Clears the value of `metadata`. Subsequent reads from it will return its default value. + public mutating func clearMetadata() {self._metadata = nil} + + /// Evaluation key. + public var evaluationKey: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_SerializedEvaluationKey { + get {return _evaluationKey ?? HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_SerializedEvaluationKey()} + set {_evaluationKey = newValue} + } + /// Returns true if `evaluationKey` has been explicitly set. + public var hasEvaluationKey: Bool {return self._evaluationKey != nil} + /// Clears the value of `evaluationKey`. Subsequent reads from it will return its default value. + public mutating func clearEvaluationKey() {self._evaluationKey = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _metadata: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata? = nil + fileprivate var _evaluationKey: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_SerializedEvaluationKey? = nil +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.api.shared.v1" + +extension Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".EvaluationKeyMetadata" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}timestamp\0\u{1}identifier\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt64Field(value: &self.timestamp) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.identifier) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.timestamp != 0 { + try visitor.visitSingularUInt64Field(value: self.timestamp, fieldNumber: 1) + } + if !self.identifier.isEmpty { + try visitor.visitSingularBytesField(value: self.identifier, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata, rhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeyMetadata) -> Bool { + if lhs.timestamp != rhs.timestamp {return false} + if lhs.identifier != rhs.identifier {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Shared_V1_KeyStatus: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".KeyStatus" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}timestamp\0\u{3}key_config\0\u{c}\u{3}\u{1}") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt64Field(value: &self.timestamp) }() + case 2: try { try decoder.decodeSingularMessageField(value: &self._keyConfig) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if self.timestamp != 0 { + try visitor.visitSingularUInt64Field(value: self.timestamp, fieldNumber: 1) + } + try { if let v = self._keyConfig { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_KeyStatus, rhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_KeyStatus) -> Bool { + if lhs.timestamp != rhs.timestamp {return false} + if lhs._keyConfig != rhs._keyConfig {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeys: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".EvaluationKeys" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}keys\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.keys) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.keys.isEmpty { + try visitor.visitRepeatedMessageField(value: self.keys, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeys, rhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKeys) -> Bool { + if lhs.keys != rhs.keys {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".EvaluationKey" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}metadata\0\u{3}evaluation_key\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._metadata) }() + case 2: try { try decoder.decodeSingularMessageField(value: &self._evaluationKey) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = self._metadata { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + try { if let v = self._evaluationKey { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey, rhs: Apple_SwiftHomomorphicEncryption_Api_Shared_V1_EvaluationKey) -> Bool { + if lhs._metadata != rhs._metadata {return false} + if lhs._evaluationKey != rhs._evaluationKey {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_v1_api.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_v1_api.pb.swift new file mode 100644 index 00000000..5f1febe7 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_api_v1_api.pb.swift @@ -0,0 +1,953 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/api/v1/api.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Request for server side configurations. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_ConfigRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// List of usecases to fetch configs for. + /// When set to empty array, all configs will be returned. + public var usecases: [String] = [] + + /// For each usecase, the existing config id, if one exists. + public var existingConfigIds: [Data] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Usecase configuration. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_Config: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Configuration. + public var config: Apple_SwiftHomomorphicEncryption_Api_V1_Config.OneOf_Config? = nil + + /// Configuration for a PIR usecase. + public var pirConfig: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig { + get { + if case .pirConfig(let v)? = config {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig() + } + set {config = .pirConfig(newValue)} + } + + /// Configuration for a PNNS usecase. + public var pnnsConfig: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig { + get { + if case .pnnsConfig(let v)? = config {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig() + } + set {config = .pnnsConfig(newValue)} + } + + /// Unique identifier for the configuration. + public var configID: Data = Data() + + /// Indicator that the config is the same config as in the ConfigRequest. If set, all other fields can be unset. + public var reuseExistingConfig: Bool = false + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// Configuration. + public enum OneOf_Config: Equatable, Sendable { + /// Configuration for a PIR usecase. + case pirConfig(Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig) + /// Configuration for a PNNS usecase. + case pnnsConfig(Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig) + + } + + public init() {} +} + +/// Server side configurations. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_ConfigResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// usecases with associated configurations. + public var configs: Dictionary = [:] + + /// Configuration & status of evaluation keys. + public var keyInfo: [Apple_SwiftHomomorphicEncryption_Api_Shared_V1_KeyStatus] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Container for multiple requests. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_Requests: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Requests. + public var requests: [Apple_SwiftHomomorphicEncryption_Api_V1_Request] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Container for multiple responses. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_Responses: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Responses. + public var responses: [Apple_SwiftHomomorphicEncryption_Api_V1_Response] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Generic request. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_Request: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Usecase identifier. + public var usecase: String = String() + + /// Generic request. + public var request: Apple_SwiftHomomorphicEncryption_Api_V1_Request.OneOf_Request? = nil + + /// PIR request. + public var pirRequest: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest { + get { + if case .pirRequest(let v)? = request {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest() + } + set {request = .pirRequest(newValue)} + } + + /// PNNS request. + public var pnnsRequest: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest { + get { + if case .pnnsRequest(let v)? = request {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest() + } + set {request = .pnnsRequest(newValue)} + } + + /// OPRF request. + public var oprfRequest: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest { + get { + if case .oprfRequest(let v)? = request {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest() + } + set {request = .oprfRequest(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// Generic request. + public enum OneOf_Request: Equatable, Sendable { + /// PIR request. + case pirRequest(Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest) + /// PNNS request. + case pnnsRequest(Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest) + /// OPRF request. + case oprfRequest(Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest) + + } + + public init() {} +} + +/// Generic response. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_Response: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Generic response. + public var response: Apple_SwiftHomomorphicEncryption_Api_V1_Response.OneOf_Response? = nil + + /// Response to a `PIRRequest`. + public var pirResponse: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse { + get { + if case .pirResponse(let v)? = response {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse() + } + set {response = .pirResponse(newValue)} + } + + /// Response to a `PNNSRequest`. + public var pnnsResponse: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse { + get { + if case .pnnsResponse(let v)? = response {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse() + } + set {response = .pnnsResponse(newValue)} + } + + /// Response to `OPRFRequest`. + public var oprfResponse: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse { + get { + if case .oprfResponse(let v)? = response {return v} + return Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse() + } + set {response = .oprfResponse(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// Generic response. + public enum OneOf_Response: Equatable, Sendable { + /// Response to a `PIRRequest`. + case pirResponse(Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse) + /// Response to a `PNNSRequest`. + case pnnsResponse(Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse) + /// Response to `OPRFRequest`. + case oprfResponse(Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse) + + } + + public init() {} +} + +/// Error returned by failed API calls. +public struct Apple_SwiftHomomorphicEncryption_Api_V1_Error: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Type of error encountered while processing request. + public var errorType: Apple_SwiftHomomorphicEncryption_Api_V1_Error.OneOf_ErrorType? = nil + + /// Client configuration not found. + public var configVersionNotFound: Apple_SwiftHomomorphicEncryption_Api_V1_Error.ConfigVersionNotFound { + get { + if case .configVersionNotFound(let v)? = errorType {return v} + return Apple_SwiftHomomorphicEncryption_Api_V1_Error.ConfigVersionNotFound() + } + set {errorType = .configVersionNotFound(newValue)} + } + + /// Client evaluation key not found. + public var evaluationKeyNotFound: Apple_SwiftHomomorphicEncryption_Api_V1_Error.EvaluationKeyNotFound { + get { + if case .evaluationKeyNotFound(let v)? = errorType {return v} + return Apple_SwiftHomomorphicEncryption_Api_V1_Error.EvaluationKeyNotFound() + } + set {errorType = .evaluationKeyNotFound(newValue)} + } + + /// Request can not be parsed. + public var invalidRequest: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InvalidRequest { + get { + if case .invalidRequest(let v)? = errorType {return v} + return Apple_SwiftHomomorphicEncryption_Api_V1_Error.InvalidRequest() + } + set {errorType = .invalidRequest(newValue)} + } + + /// Internal error. + public var internalError: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InternalError { + get { + if case .internalError(let v)? = errorType {return v} + return Apple_SwiftHomomorphicEncryption_Api_V1_Error.InternalError() + } + set {errorType = .internalError(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// Type of error encountered while processing request. + public enum OneOf_ErrorType: Equatable, Sendable { + /// Client configuration not found. + case configVersionNotFound(Apple_SwiftHomomorphicEncryption_Api_V1_Error.ConfigVersionNotFound) + /// Client evaluation key not found. + case evaluationKeyNotFound(Apple_SwiftHomomorphicEncryption_Api_V1_Error.EvaluationKeyNotFound) + /// Request can not be parsed. + case invalidRequest(Apple_SwiftHomomorphicEncryption_Api_V1_Error.InvalidRequest) + /// Internal error. + case internalError(Apple_SwiftHomomorphicEncryption_Api_V1_Error.InternalError) + + } + + /// Client configuration not found. + /// + /// Client should retry after fetching new configuration. May include new configuration + /// in `config_response`. In this case, client should use this returned configuration and retry. + public struct ConfigVersionNotFound: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// ConfigResponse that client should use for subsequent requests. + public var configResponse: Apple_SwiftHomomorphicEncryption_Api_V1_ConfigResponse { + get {return _configResponse ?? Apple_SwiftHomomorphicEncryption_Api_V1_ConfigResponse()} + set {_configResponse = newValue} + } + /// Returns true if `configResponse` has been explicitly set. + public var hasConfigResponse: Bool {return self._configResponse != nil} + /// Clears the value of `configResponse`. Subsequent reads from it will return its default value. + public mutating func clearConfigResponse() {self._configResponse = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _configResponse: Apple_SwiftHomomorphicEncryption_Api_V1_ConfigResponse? = nil + } + + /// Evaluation key not found. + /// + /// Client should upload evaluation key and retry. + public struct EvaluationKeyNotFound: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + } + + /// Request can not be parsed successfully. + public struct InvalidRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + } + + /// Internal error. + public struct InternalError: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + } + + public init() {} +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.api.v1" + +extension Apple_SwiftHomomorphicEncryption_Api_V1_ConfigRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".ConfigRequest" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}usecases\0\u{3}existing_config_ids\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedStringField(value: &self.usecases) }() + case 2: try { try decoder.decodeRepeatedBytesField(value: &self.existingConfigIds) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.usecases.isEmpty { + try visitor.visitRepeatedStringField(value: self.usecases, fieldNumber: 1) + } + if !self.existingConfigIds.isEmpty { + try visitor.visitRepeatedBytesField(value: self.existingConfigIds, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_ConfigRequest, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_ConfigRequest) -> Bool { + if lhs.usecases != rhs.usecases {return false} + if lhs.existingConfigIds != rhs.existingConfigIds {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Config: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Config" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}pir_config\0\u{3}pnns_config\0\u{3}config_id\0\u{3}reuse_existing_config\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRConfig? + var hadOneofValue = false + if let current = self.config { + hadOneofValue = true + if case .pirConfig(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.config = .pirConfig(v) + } + }() + case 2: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSConfig? + var hadOneofValue = false + if let current = self.config { + hadOneofValue = true + if case .pnnsConfig(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.config = .pnnsConfig(v) + } + }() + case 3: try { try decoder.decodeSingularBytesField(value: &self.configID) }() + case 4: try { try decoder.decodeSingularBoolField(value: &self.reuseExistingConfig) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + switch self.config { + case .pirConfig?: try { + guard case .pirConfig(let v)? = self.config else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .pnnsConfig?: try { + guard case .pnnsConfig(let v)? = self.config else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case nil: break + } + if !self.configID.isEmpty { + try visitor.visitSingularBytesField(value: self.configID, fieldNumber: 3) + } + if self.reuseExistingConfig != false { + try visitor.visitSingularBoolField(value: self.reuseExistingConfig, fieldNumber: 4) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Config, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Config) -> Bool { + if lhs.config != rhs.config {return false} + if lhs.configID != rhs.configID {return false} + if lhs.reuseExistingConfig != rhs.reuseExistingConfig {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_ConfigResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".ConfigResponse" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}configs\0\u{3}key_info\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap.self, value: &self.configs) }() + case 2: try { try decoder.decodeRepeatedMessageField(value: &self.keyInfo) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.configs.isEmpty { + try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap.self, value: self.configs, fieldNumber: 1) + } + if !self.keyInfo.isEmpty { + try visitor.visitRepeatedMessageField(value: self.keyInfo, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_ConfigResponse, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_ConfigResponse) -> Bool { + if lhs.configs != rhs.configs {return false} + if lhs.keyInfo != rhs.keyInfo {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Requests: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Requests" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}requests\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.requests) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.requests.isEmpty { + try visitor.visitRepeatedMessageField(value: self.requests, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Requests, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Requests) -> Bool { + if lhs.requests != rhs.requests {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Responses: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Responses" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}responses\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.responses) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.responses.isEmpty { + try visitor.visitRepeatedMessageField(value: self.responses, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Responses, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Responses) -> Bool { + if lhs.responses != rhs.responses {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Request: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Request" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}usecase\0\u{3}pir_request\0\u{3}pnns_request\0\u{3}oprf_request\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.usecase) }() + case 2: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRRequest? + var hadOneofValue = false + if let current = self.request { + hadOneofValue = true + if case .pirRequest(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.request = .pirRequest(v) + } + }() + case 3: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSRequest? + var hadOneofValue = false + if let current = self.request { + hadOneofValue = true + if case .pnnsRequest(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.request = .pnnsRequest(v) + } + }() + case 4: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFRequest? + var hadOneofValue = false + if let current = self.request { + hadOneofValue = true + if case .oprfRequest(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.request = .oprfRequest(v) + } + }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !self.usecase.isEmpty { + try visitor.visitSingularStringField(value: self.usecase, fieldNumber: 1) + } + switch self.request { + case .pirRequest?: try { + guard case .pirRequest(let v)? = self.request else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .pnnsRequest?: try { + guard case .pnnsRequest(let v)? = self.request else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case .oprfRequest?: try { + guard case .oprfRequest(let v)? = self.request else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + }() + case nil: break + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Request, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Request) -> Bool { + if lhs.usecase != rhs.usecase {return false} + if lhs.request != rhs.request {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Response: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Response" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}pir_response\0\u{3}pnns_response\0\u{3}oprf_response\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_PIRResponse? + var hadOneofValue = false + if let current = self.response { + hadOneofValue = true + if case .pirResponse(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.response = .pirResponse(v) + } + }() + case 2: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pnns_V1_PNNSResponse? + var hadOneofValue = false + if let current = self.response { + hadOneofValue = true + if case .pnnsResponse(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.response = .pnnsResponse(v) + } + }() + case 3: try { + var v: Apple_SwiftHomomorphicEncryption_Api_Pir_V1_OPRFResponse? + var hadOneofValue = false + if let current = self.response { + hadOneofValue = true + if case .oprfResponse(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.response = .oprfResponse(v) + } + }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + switch self.response { + case .pirResponse?: try { + guard case .pirResponse(let v)? = self.response else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .pnnsResponse?: try { + guard case .pnnsResponse(let v)? = self.response else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .oprfResponse?: try { + guard case .oprfResponse(let v)? = self.response else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case nil: break + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Response, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Response) -> Bool { + if lhs.response != rhs.response {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Error: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Error" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}config_version_not_found\0\u{3}evaluation_key_not_found\0\u{3}invalid_request\0\u{3}internal_error\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Apple_SwiftHomomorphicEncryption_Api_V1_Error.ConfigVersionNotFound? + var hadOneofValue = false + if let current = self.errorType { + hadOneofValue = true + if case .configVersionNotFound(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.errorType = .configVersionNotFound(v) + } + }() + case 2: try { + var v: Apple_SwiftHomomorphicEncryption_Api_V1_Error.EvaluationKeyNotFound? + var hadOneofValue = false + if let current = self.errorType { + hadOneofValue = true + if case .evaluationKeyNotFound(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.errorType = .evaluationKeyNotFound(v) + } + }() + case 3: try { + var v: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InvalidRequest? + var hadOneofValue = false + if let current = self.errorType { + hadOneofValue = true + if case .invalidRequest(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.errorType = .invalidRequest(v) + } + }() + case 4: try { + var v: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InternalError? + var hadOneofValue = false + if let current = self.errorType { + hadOneofValue = true + if case .internalError(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.errorType = .internalError(v) + } + }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + switch self.errorType { + case .configVersionNotFound?: try { + guard case .configVersionNotFound(let v)? = self.errorType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .evaluationKeyNotFound?: try { + guard case .evaluationKeyNotFound(let v)? = self.errorType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .invalidRequest?: try { + guard case .invalidRequest(let v)? = self.errorType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case .internalError?: try { + guard case .internalError(let v)? = self.errorType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + }() + case nil: break + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error) -> Bool { + if lhs.errorType != rhs.errorType {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Error.ConfigVersionNotFound: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = Apple_SwiftHomomorphicEncryption_Api_V1_Error.protoMessageName + ".ConfigVersionNotFound" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}config_response\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._configResponse) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = self._configResponse { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.ConfigVersionNotFound, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.ConfigVersionNotFound) -> Bool { + if lhs._configResponse != rhs._configResponse {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Error.EvaluationKeyNotFound: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = Apple_SwiftHomomorphicEncryption_Api_V1_Error.protoMessageName + ".EvaluationKeyNotFound" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.EvaluationKeyNotFound, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.EvaluationKeyNotFound) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Error.InvalidRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = Apple_SwiftHomomorphicEncryption_Api_V1_Error.protoMessageName + ".InvalidRequest" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InvalidRequest, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InvalidRequest) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Api_V1_Error.InternalError: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = Apple_SwiftHomomorphicEncryption_Api_V1_Error.protoMessageName + ".InternalError" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InternalError, rhs: Apple_SwiftHomomorphicEncryption_Api_V1_Error.InternalError) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir.pb.swift new file mode 100644 index 00000000..7825ccaf --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir.pb.swift @@ -0,0 +1,713 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pir/v1/pir.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +import HomomorphicEncryptionProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// How aggressively to compress the Galois keys needed for expansion. +public enum Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + + /// Generate keys for all permutations. + case unspecified // = 0 + + /// Only generate keys for permutations 2^j + 1 with j <= ceil(log_degree + 1 / 2) + /// reconstruct permutations 2^j + 1 for higher j by composing permutations. + case maximumCompression // = 1 + + /// Add one more key to the maximum compression keys to roughly square root the number + /// of keyswitches required during expansion. + case hybridCompression // = 2 + case UNRECOGNIZED(Int) + + public init() { + self = .unspecified + } + + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .unspecified + case 1: self = .maximumCompression + case 2: self = .hybridCompression + default: self = .UNRECOGNIZED(rawValue) + } + } + + public var rawValue: Int { + switch self { + case .unspecified: return 0 + case .maximumCompression: return 1 + case .hybridCompression: return 2 + case .UNRECOGNIZED(let i): return i + } + } + + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy] = [ + .unspecified, + .maximumCompression, + .hybridCompression, + ] + +} + +/// Scheme used for encrypting database entries in Symmetric PIR. +public enum Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirConfigType: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + + /// Unspecified config type. + case unspecified // = 0 + + /// OPRF P384 AES-192-GCM, 96-bit nonce, 128-bit tag + case oprfP384AesGcm192Nonce96Tag128 // = 1 + case UNRECOGNIZED(Int) + + public init() { + self = .unspecified + } + + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .unspecified + case 1: self = .oprfP384AesGcm192Nonce96Tag128 + default: self = .UNRECOGNIZED(rawValue) + } + } + + public var rawValue: Int { + switch self { + case .unspecified: return 0 + case .oprfP384AesGcm192Nonce96Tag128: return 1 + case .UNRECOGNIZED(let i): return i + } + } + + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirConfigType] = [ + .unspecified, + .oprfP384AesGcm192Nonce96Tag128, + ] + +} + +/// Parameters for PIR. +/// These need to be agreed upon by both the server and client. +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_PirParameters: @unchecked Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Encryption parameters. + public var encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters { + get {return _storage._encryptionParameters ?? HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters()} + set {_uniqueStorage()._encryptionParameters = newValue} + } + /// Returns true if `encryptionParameters` has been explicitly set. + public var hasEncryptionParameters: Bool {return _storage._encryptionParameters != nil} + /// Clears the value of `encryptionParameters`. Subsequent reads from it will return its default value. + public mutating func clearEncryptionParameters() {_uniqueStorage()._encryptionParameters = nil} + + /// Number of entries in the database. + public var numEntries: UInt64 { + get {return _storage._numEntries} + set {_uniqueStorage()._numEntries = newValue} + } + + /// Size in bytes of entries in the database. + public var entrySize: UInt64 { + get {return _storage._entrySize} + set {_uniqueStorage()._entrySize = newValue} + } + + /// Dimensions that make up the hypercube. + public var dimensions: [UInt64] { + get {return _storage._dimensions} + set {_uniqueStorage()._dimensions = newValue} + } + + /// Parameters specific to KeywordPIR. + public var keywordPirParams: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters { + get {return _storage._keywordPirParams ?? Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters()} + set {_uniqueStorage()._keywordPirParams = newValue} + } + /// Returns true if `keywordPirParams` has been explicitly set. + public var hasKeywordPirParams: Bool {return _storage._keywordPirParams != nil} + /// Clears the value of `keywordPirParams`. Subsequent reads from it will return its default value. + public mutating func clearKeywordPirParams() {_uniqueStorage()._keywordPirParams = nil} + + /// Server-side PIR algorithm. + public var algorithm: Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm { + get {return _storage._algorithm} + set {_uniqueStorage()._algorithm = newValue} + } + + /// Maximum number of queries allowed in a single request. + public var batchSize: UInt64 { + get {return _storage._batchSize} + set {_uniqueStorage()._batchSize = newValue} + } + + /// Evaluation key configuration. + public var evaluationKeyConfig: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EvaluationKeyConfig { + get {return _storage._evaluationKeyConfig ?? HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EvaluationKeyConfig()} + set {_uniqueStorage()._evaluationKeyConfig = newValue} + } + /// Returns true if `evaluationKeyConfig` has been explicitly set. + public var hasEvaluationKeyConfig: Bool {return _storage._evaluationKeyConfig != nil} + /// Clears the value of `evaluationKeyConfig`. Subsequent reads from it will return its default value. + public mutating func clearEvaluationKeyConfig() {_uniqueStorage()._evaluationKeyConfig = nil} + + /// Key compression strategy. + public var keyCompressionStrategy: Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy { + get {return _storage._keyCompressionStrategy} + set {_uniqueStorage()._keyCompressionStrategy = newValue} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _storage = _StorageClass.defaultInstance +} + +/// Parameters for keyword PIR. +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The number of hash functions used. + public var numHashFunctions: UInt64 = 0 + + /// Symmetric PIR configuration + public var symmetricPirClientConfig: Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig { + get {return _symmetricPirClientConfig ?? Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig()} + set {_symmetricPirClientConfig = newValue} + } + /// Returns true if `symmetricPirClientConfig` has been explicitly set. + public var hasSymmetricPirClientConfig: Bool {return self._symmetricPirClientConfig != nil} + /// Clears the value of `symmetricPirClientConfig`. Subsequent reads from it will return its default value. + public mutating func clearSymmetricPirClientConfig() {self._symmetricPirClientConfig = nil} + + /// The sharding function to use. + public var shardingFunction: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction { + get {return _shardingFunction ?? Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction()} + set {_shardingFunction = newValue} + } + /// Returns true if `shardingFunction` has been explicitly set. + public var hasShardingFunction: Bool {return self._shardingFunction != nil} + /// Clears the value of `shardingFunction`. Subsequent reads from it will return its default value. + public mutating func clearShardingFunction() {self._shardingFunction = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _symmetricPirClientConfig: Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig? = nil + fileprivate var _shardingFunction: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction? = nil +} + +/// Configuration for the sharding function. +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Sharding function to use. + public var function: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction.OneOf_Function? = nil + + /// Sharding based on SHA256 hash of the keyword. + public var sha256: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256 { + get { + if case .sha256(let v)? = function {return v} + return Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256() + } + set {function = .sha256(newValue)} + } + + /// Sharding depends on a different usecase. + public var doubleMod: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod { + get { + if case .doubleMod(let v)? = function {return v} + return Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod() + } + set {function = .doubleMod(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// Sharding function to use. + public enum OneOf_Function: Equatable, Sendable { + /// Sharding based on SHA256 hash of the keyword. + case sha256(Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256) + /// Sharding depends on a different usecase. + case doubleMod(Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod) + + } + + public init() {} +} + +/// SHA256 sharding function. +/// +/// shard_id = (truncate(SHA256(keyword)) % shard_count). +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Double mod sharding function. +/// +/// shard_id = (truncate(SHA256(keyword)) % other_shard_count) % shard_count. +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Number of shards in the other usecase. + public var otherShardCount: UInt32 = 0 + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Encrypted PIR index. +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// PIR query. + public var ciphertexts: [HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_SerializedCiphertext] = [] + + /// Number of PIR calls. + public var numPirCalls: UInt64 = 0 + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Client specific PIR configuration for Symmetric PIR +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Server public key + public var serverPublicKey: Data = Data() + + /// Symmetric PIR config type + public var configType: Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirConfigType = .unspecified + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pir.v1" + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy: SwiftProtobuf._ProtoNameProviding { + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{2}\0KEY_COMPRESSION_STRATEGY_UNSPECIFIED\0\u{1}KEY_COMPRESSION_STRATEGY_MAXIMUM_COMPRESSION\0\u{1}KEY_COMPRESSION_STRATEGY_HYBRID_COMPRESSION\0") +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirConfigType: SwiftProtobuf._ProtoNameProviding { + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{2}\0SYMMETRIC_PIR_CONFIG_TYPE_UNSPECIFIED\0\u{1}SYMMETRIC_PIR_CONFIG_TYPE_OPRF_P384_AES_GCM_192_NONCE_96_TAG_128\0") +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PirParameters: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PirParameters" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}encryption_parameters\0\u{3}num_entries\0\u{3}entry_size\0\u{1}dimensions\0\u{3}keyword_pir_params\0\u{1}algorithm\0\u{3}batch_size\0\u{3}evaluation_key_config\0\u{3}key_compression_strategy\0\u{c}\u{a}\u{1}\u{c}\u{b}\u{1}\u{c}\u{c}\u{1}") + + fileprivate class _StorageClass { + var _encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters? = nil + var _numEntries: UInt64 = 0 + var _entrySize: UInt64 = 0 + var _dimensions: [UInt64] = [] + var _keywordPirParams: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters? = nil + var _algorithm: Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm = .aclsPir + var _batchSize: UInt64 = 0 + var _evaluationKeyConfig: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EvaluationKeyConfig? = nil + var _keyCompressionStrategy: Apple_SwiftHomomorphicEncryption_Pir_V1_KeyCompressionStrategy = .unspecified + + // This property is used as the initial default value for new instances of the type. + // The type itself is protecting the reference to its storage via CoW semantics. + // This will force a copy to be made of this reference when the first mutation occurs; + // hence, it is safe to mark this as `nonisolated(unsafe)`. + static nonisolated(unsafe) let defaultInstance = _StorageClass() + + private init() {} + + init(copying source: _StorageClass) { + _encryptionParameters = source._encryptionParameters + _numEntries = source._numEntries + _entrySize = source._entrySize + _dimensions = source._dimensions + _keywordPirParams = source._keywordPirParams + _algorithm = source._algorithm + _batchSize = source._batchSize + _evaluationKeyConfig = source._evaluationKeyConfig + _keyCompressionStrategy = source._keyCompressionStrategy + } + } + + fileprivate mutating func _uniqueStorage() -> _StorageClass { + if !isKnownUniquelyReferenced(&_storage) { + _storage = _StorageClass(copying: _storage) + } + return _storage + } + + public mutating func decodeMessage(decoder: inout D) throws { + _ = _uniqueStorage() + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &_storage._encryptionParameters) }() + case 2: try { try decoder.decodeSingularUInt64Field(value: &_storage._numEntries) }() + case 3: try { try decoder.decodeSingularUInt64Field(value: &_storage._entrySize) }() + case 4: try { try decoder.decodeRepeatedUInt64Field(value: &_storage._dimensions) }() + case 5: try { try decoder.decodeSingularMessageField(value: &_storage._keywordPirParams) }() + case 6: try { try decoder.decodeSingularEnumField(value: &_storage._algorithm) }() + case 7: try { try decoder.decodeSingularUInt64Field(value: &_storage._batchSize) }() + case 8: try { try decoder.decodeSingularMessageField(value: &_storage._evaluationKeyConfig) }() + case 9: try { try decoder.decodeSingularEnumField(value: &_storage._keyCompressionStrategy) }() + default: break + } + } + } + } + + public func traverse(visitor: inout V) throws { + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = _storage._encryptionParameters { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + if _storage._numEntries != 0 { + try visitor.visitSingularUInt64Field(value: _storage._numEntries, fieldNumber: 2) + } + if _storage._entrySize != 0 { + try visitor.visitSingularUInt64Field(value: _storage._entrySize, fieldNumber: 3) + } + if !_storage._dimensions.isEmpty { + try visitor.visitPackedUInt64Field(value: _storage._dimensions, fieldNumber: 4) + } + try { if let v = _storage._keywordPirParams { + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + } }() + if _storage._algorithm != .aclsPir { + try visitor.visitSingularEnumField(value: _storage._algorithm, fieldNumber: 6) + } + if _storage._batchSize != 0 { + try visitor.visitSingularUInt64Field(value: _storage._batchSize, fieldNumber: 7) + } + try { if let v = _storage._evaluationKeyConfig { + try visitor.visitSingularMessageField(value: v, fieldNumber: 8) + } }() + if _storage._keyCompressionStrategy != .unspecified { + try visitor.visitSingularEnumField(value: _storage._keyCompressionStrategy, fieldNumber: 9) + } + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PirParameters, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PirParameters) -> Bool { + if lhs._storage !== rhs._storage { + let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in + let _storage = _args.0 + let rhs_storage = _args.1 + if _storage._encryptionParameters != rhs_storage._encryptionParameters {return false} + if _storage._numEntries != rhs_storage._numEntries {return false} + if _storage._entrySize != rhs_storage._entrySize {return false} + if _storage._dimensions != rhs_storage._dimensions {return false} + if _storage._keywordPirParams != rhs_storage._keywordPirParams {return false} + if _storage._algorithm != rhs_storage._algorithm {return false} + if _storage._batchSize != rhs_storage._batchSize {return false} + if _storage._evaluationKeyConfig != rhs_storage._evaluationKeyConfig {return false} + if _storage._keyCompressionStrategy != rhs_storage._keyCompressionStrategy {return false} + return true + } + if !storagesAreEqual {return false} + } + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".KeywordPirParameters" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}num_hash_functions\0\u{4}\u{2}symmetric_pir_client_config\0\u{3}sharding_function\0\u{c}\u{2}\u{1}") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt64Field(value: &self.numHashFunctions) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._symmetricPirClientConfig) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._shardingFunction) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if self.numHashFunctions != 0 { + try visitor.visitSingularUInt64Field(value: self.numHashFunctions, fieldNumber: 1) + } + try { if let v = self._symmetricPirClientConfig { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } }() + try { if let v = self._shardingFunction { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordPirParameters) -> Bool { + if lhs.numHashFunctions != rhs.numHashFunctions {return false} + if lhs._symmetricPirClientConfig != rhs._symmetricPirClientConfig {return false} + if lhs._shardingFunction != rhs._shardingFunction {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRShardingFunction" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}sha256\0\u{3}double_mod\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256? + var hadOneofValue = false + if let current = self.function { + hadOneofValue = true + if case .sha256(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.function = .sha256(v) + } + }() + case 2: try { + var v: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod? + var hadOneofValue = false + if let current = self.function { + hadOneofValue = true + if case .doubleMod(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.function = .doubleMod(v) + } + }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + switch self.function { + case .sha256?: try { + guard case .sha256(let v)? = self.function else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .doubleMod?: try { + guard case .doubleMod(let v)? = self.function else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case nil: break + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunction) -> Bool { + if lhs.function != rhs.function {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRShardingFunctionSHA256" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionSHA256) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".PIRShardingFunctionDoubleMod" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}other_shard_count\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt32Field(value: &self.otherShardCount) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.otherShardCount != 0 { + try visitor.visitSingularUInt32Field(value: self.otherShardCount, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_PIRShardingFunctionDoubleMod) -> Bool { + if lhs.otherShardCount != rhs.otherShardCount {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".EncryptedIndices" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}ciphertexts\0\u{3}num_pir_calls\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.ciphertexts) }() + case 2: try { try decoder.decodeSingularUInt64Field(value: &self.numPirCalls) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.ciphertexts.isEmpty { + try visitor.visitRepeatedMessageField(value: self.ciphertexts, fieldNumber: 1) + } + if self.numPirCalls != 0 { + try visitor.visitSingularUInt64Field(value: self.numPirCalls, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_EncryptedIndices) -> Bool { + if lhs.ciphertexts != rhs.ciphertexts {return false} + if lhs.numPirCalls != rhs.numPirCalls {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".SymmetricPirClientConfig" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}server_public_key\0\u{3}config_type\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularBytesField(value: &self.serverPublicKey) }() + case 2: try { try decoder.decodeSingularEnumField(value: &self.configType) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.serverPublicKey.isEmpty { + try visitor.visitSingularBytesField(value: self.serverPublicKey, fieldNumber: 1) + } + if self.configType != .unspecified { + try visitor.visitSingularEnumField(value: self.configType, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_SymmetricPirClientConfig) -> Bool { + if lhs.serverPublicKey != rhs.serverPublicKey {return false} + if lhs.configType != rhs.configType {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_algorithm.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_algorithm.pb.swift new file mode 100644 index 00000000..fa1b5f13 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_algorithm.pb.swift @@ -0,0 +1,84 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pir/v1/pir_algorithm.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Different algorithms for PIR. +public enum Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + + /// AclsPir. + /// + /// + case aclsPir // = 0 + + /// MulPir. + /// + /// + case mulPir // = 1 + case UNRECOGNIZED(Int) + + public init() { + self = .aclsPir + } + + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .aclsPir + case 1: self = .mulPir + default: self = .UNRECOGNIZED(rawValue) + } + } + + public var rawValue: Int { + switch self { + case .aclsPir: return 0 + case .mulPir: return 1 + case .UNRECOGNIZED(let i): return i + } + } + + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm] = [ + .aclsPir, + .mulPir, + ] + +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_PirAlgorithm: SwiftProtobuf._ProtoNameProviding { + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{2}\0PIR_ALGORITHM_ACLS_PIR\0\u{1}PIR_ALGORITHM_MUL_PIR\0") +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_database.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_database.pb.swift new file mode 100644 index 00000000..839aa149 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pir_v1_pir_database.pb.swift @@ -0,0 +1,136 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pir/v1/pir_database.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Row in a keyword-value database. +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Keyword. + public var keyword: Data = Data() + + /// Value. + public var value: Data = Data() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// A keyword-value database. +public struct Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// List of keyword-value pairs. + public var rows: [Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pir.v1" + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".KeywordDatabaseRow" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}keyword\0\u{1}value\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularBytesField(value: &self.keyword) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.value) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.keyword.isEmpty { + try visitor.visitSingularBytesField(value: self.keyword, fieldNumber: 1) + } + if !self.value.isEmpty { + try visitor.visitSingularBytesField(value: self.value, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabaseRow) -> Bool { + if lhs.keyword != rhs.keyword {return false} + if lhs.value != rhs.value {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".KeywordDatabase" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}rows\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.rows) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.rows.isEmpty { + try visitor.visitRepeatedMessageField(value: self.rows, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase, rhs: Apple_SwiftHomomorphicEncryption_Pir_V1_KeywordDatabase) -> Bool { + if lhs.rows != rhs.rows {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns.pb.swift new file mode 100644 index 00000000..406c33c1 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns.pb.swift @@ -0,0 +1,204 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pnns/v1/pnns.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftProtobuf + +import HomomorphicEncryptionProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Stores a matrix of encrypted values in a serialized ciphertext for use in linear algebra +/// operations +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Number of data rows stored in the ciphertext. + public var numRows: UInt32 = 0 + + /// Number of data columns stored in the ciphertext. + public var numColumns: UInt32 = 0 + + /// Stores the encrypted data. + public var ciphertexts: [HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_SerializedCiphertext] = [] + + /// Packing algorithm for the plaintext data. + public var packing: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking { + get {return _packing ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking()} + set {_packing = newValue} + } + /// Returns true if `packing` has been explicitly set. + public var hasPacking: Bool {return self._packing != nil} + /// Clears the value of `packing`. Subsequent reads from it will return its default value. + public mutating func clearPacking() {self._packing = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _packing: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking? = nil +} + +/// Serialized plaintext matrix +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Number of rows in the data encoded in the plaintext matrix. + public var numRows: UInt32 = 0 + + /// Number of columns in the data encoded in the plaintext matrix. + public var numColumns: UInt32 = 0 + + /// Encoded values. + public var plaintexts: [HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_SerializedPlaintext] = [] + + /// Plaintext packing. + public var packing: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking { + get {return _packing ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking()} + set {_packing = newValue} + } + /// Returns true if `packing` has been explicitly set. + public var hasPacking: Bool {return self._packing != nil} + /// Clears the value of `packing`. Subsequent reads from it will return its default value. + public mutating func clearPacking() {self._packing = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _packing: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking? = nil +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pnns.v1" + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".SerializedCiphertextMatrix" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}num_rows\0\u{3}num_columns\0\u{1}ciphertexts\0\u{1}packing\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt32Field(value: &self.numRows) }() + case 2: try { try decoder.decodeSingularUInt32Field(value: &self.numColumns) }() + case 3: try { try decoder.decodeRepeatedMessageField(value: &self.ciphertexts) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._packing) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if self.numRows != 0 { + try visitor.visitSingularUInt32Field(value: self.numRows, fieldNumber: 1) + } + if self.numColumns != 0 { + try visitor.visitSingularUInt32Field(value: self.numColumns, fieldNumber: 2) + } + if !self.ciphertexts.isEmpty { + try visitor.visitRepeatedMessageField(value: self.ciphertexts, fieldNumber: 3) + } + try { if let v = self._packing { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedCiphertextMatrix) -> Bool { + if lhs.numRows != rhs.numRows {return false} + if lhs.numColumns != rhs.numColumns {return false} + if lhs.ciphertexts != rhs.ciphertexts {return false} + if lhs._packing != rhs._packing {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".SerializedPlaintextMatrix" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}num_rows\0\u{3}num_columns\0\u{1}plaintexts\0\u{1}packing\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt32Field(value: &self.numRows) }() + case 2: try { try decoder.decodeSingularUInt32Field(value: &self.numColumns) }() + case 3: try { try decoder.decodeRepeatedMessageField(value: &self.plaintexts) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._packing) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if self.numRows != 0 { + try visitor.visitSingularUInt32Field(value: self.numRows, fieldNumber: 1) + } + if self.numColumns != 0 { + try visitor.visitSingularUInt32Field(value: self.numColumns, fieldNumber: 2) + } + if !self.plaintexts.isEmpty { + try visitor.visitRepeatedMessageField(value: self.plaintexts, fieldNumber: 3) + } + try { if let v = self._packing { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix) -> Bool { + if lhs.numRows != rhs.numRows {return false} + if lhs.numColumns != rhs.numColumns {return false} + if lhs.plaintexts != rhs.plaintexts {return false} + if lhs._packing != rhs._packing {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_client_config.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_client_config.pb.swift new file mode 100644 index 00000000..4feb8640 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_client_config.pb.swift @@ -0,0 +1,155 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pnns/v1/pnns_client_config.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftProtobuf + +import HomomorphicEncryptionProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// The client configuration. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Encryption parameters. + public var encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters { + get {return _encryptionParameters ?? HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters()} + set {_encryptionParameters = newValue} + } + /// Returns true if `encryptionParameters` has been explicitly set. + public var hasEncryptionParameters: Bool {return self._encryptionParameters != nil} + /// Clears the value of `encryptionParameters`. Subsequent reads from it will return its default value. + public mutating func clearEncryptionParameters() {self._encryptionParameters = nil} + + /// Factor by which to scale floating-point entries before rounding to integers. + public var scalingFactor: UInt64 = 0 + + /// Packing for the query. + public var queryPacking: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking { + get {return _queryPacking ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking()} + set {_queryPacking = newValue} + } + /// Returns true if `queryPacking` has been explicitly set. + public var hasQueryPacking: Bool {return self._queryPacking != nil} + /// Clears the value of `queryPacking`. Subsequent reads from it will return its default value. + public mutating func clearQueryPacking() {self._queryPacking = nil} + + /// Number of entries in each vector. + public var vectorDimension: UInt32 = 0 + + /// Galois elements required for nearest neighbor search. + public var galoisElements: [UInt32] = [] + + /// Metric for distances between vectors. + public var distanceMetric: Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric = .cosineSimilarity + + /// For plaintext CRT, the list of extra plaintext moduli. + /// The first plaintext modulus will be the one in `encryption_parameters`. + public var extraPlaintextModuli: [UInt64] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _encryptionParameters: HomomorphicEncryptionProtobuf.Apple_SwiftHomomorphicEncryption_V1_EncryptionParameters? = nil + fileprivate var _queryPacking: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking? = nil +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pnns.v1" + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".ClientConfig" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}encryption_parameters\0\u{3}scaling_factor\0\u{3}query_packing\0\u{3}vector_dimension\0\u{3}galois_elements\0\u{3}distance_metric\0\u{3}extra_plaintext_moduli\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._encryptionParameters) }() + case 2: try { try decoder.decodeSingularUInt64Field(value: &self.scalingFactor) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._queryPacking) }() + case 4: try { try decoder.decodeSingularUInt32Field(value: &self.vectorDimension) }() + case 5: try { try decoder.decodeRepeatedUInt32Field(value: &self.galoisElements) }() + case 6: try { try decoder.decodeSingularEnumField(value: &self.distanceMetric) }() + case 7: try { try decoder.decodeRepeatedUInt64Field(value: &self.extraPlaintextModuli) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = self._encryptionParameters { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + if self.scalingFactor != 0 { + try visitor.visitSingularUInt64Field(value: self.scalingFactor, fieldNumber: 2) + } + try { if let v = self._queryPacking { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } }() + if self.vectorDimension != 0 { + try visitor.visitSingularUInt32Field(value: self.vectorDimension, fieldNumber: 4) + } + if !self.galoisElements.isEmpty { + try visitor.visitPackedUInt32Field(value: self.galoisElements, fieldNumber: 5) + } + if self.distanceMetric != .cosineSimilarity { + try visitor.visitSingularEnumField(value: self.distanceMetric, fieldNumber: 6) + } + if !self.extraPlaintextModuli.isEmpty { + try visitor.visitPackedUInt64Field(value: self.extraPlaintextModuli, fieldNumber: 7) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig) -> Bool { + if lhs._encryptionParameters != rhs._encryptionParameters {return false} + if lhs.scalingFactor != rhs.scalingFactor {return false} + if lhs._queryPacking != rhs._queryPacking {return false} + if lhs.vectorDimension != rhs.vectorDimension {return false} + if lhs.galoisElements != rhs.galoisElements {return false} + if lhs.distanceMetric != rhs.distanceMetric {return false} + if lhs.extraPlaintextModuli != rhs.extraPlaintextModuli {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_database.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_database.pb.swift new file mode 100644 index 00000000..af0aac5b --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_database.pb.swift @@ -0,0 +1,144 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pnns/v1/pnns_database.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Row in a private nearest neighbor search database. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Unique identifier for the database entry. + public var entryID: UInt64 = 0 + + /// Metadata associated with the entry. + public var entryMetadata: Data = Data() + + /// Vector for use in nearest neighbor search. + public var vector: [Float] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// A private nearest neighbor search database. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_Database: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Rows in the database. + public var rows: [Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow] = [] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pnns.v1" + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".DatabaseRow" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}entry_id\0\u{3}entry_metadata\0\u{1}vector\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt64Field(value: &self.entryID) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.entryMetadata) }() + case 3: try { try decoder.decodeRepeatedFloatField(value: &self.vector) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.entryID != 0 { + try visitor.visitSingularUInt64Field(value: self.entryID, fieldNumber: 1) + } + if !self.entryMetadata.isEmpty { + try visitor.visitSingularBytesField(value: self.entryMetadata, fieldNumber: 2) + } + if !self.vector.isEmpty { + try visitor.visitPackedFloatField(value: self.vector, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_DatabaseRow) -> Bool { + if lhs.entryID != rhs.entryID {return false} + if lhs.entryMetadata != rhs.entryMetadata {return false} + if lhs.vector != rhs.vector {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_Database: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Database" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}rows\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.rows) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.rows.isEmpty { + try visitor.visitRepeatedMessageField(value: self.rows, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_Database, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_Database) -> Bool { + if lhs.rows != rhs.rows {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_distance_metric.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_distance_metric.pb.swift new file mode 100644 index 00000000..ce9dee01 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_distance_metric.pb.swift @@ -0,0 +1,74 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pnns/v1/pnns_distance_metric.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Metric for distances between vectors. +public enum Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + + /// Cosine similarity. + case cosineSimilarity // = 0 + case UNRECOGNIZED(Int) + + public init() { + self = .cosineSimilarity + } + + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .cosineSimilarity + default: self = .UNRECOGNIZED(rawValue) + } + } + + public var rawValue: Int { + switch self { + case .cosineSimilarity: return 0 + case .UNRECOGNIZED(let i): return i + } + } + + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric] = [ + .cosineSimilarity, + ] + +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_DistanceMetric: SwiftProtobuf._ProtoNameProviding { + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{2}\0DISTANCE_METRIC_COSINE_SIMILARITY\0") +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_matrix_packing.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_matrix_packing.pb.swift new file mode 100644 index 00000000..62df6c5f --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_matrix_packing.pb.swift @@ -0,0 +1,375 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pnns/v1/pnns_matrix_packing.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Pre-computed values for matrix-vector multiplication using baby-step, giant-step algorithm. +/// See Section 6.3 of . +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Dimension of the vector; "D" in the reference. + public var vectorDimension: UInt32 = 0 + + /// Baby step; "g" in the reference. + public var babyStep: UInt32 = 0 + + /// Giant step; "h" in the reference. + public var giantStep: UInt32 = 0 + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Different algorithms for packing a matrix of scalar values into plaintexts / ciphertexts. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Different packing formats. + public var matrixPackingType: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking.OneOf_MatrixPackingType? = nil + + /// Dense row packing. + public var denseRow: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow { + get { + if case .denseRow(let v)? = matrixPackingType {return v} + return Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow() + } + set {matrixPackingType = .denseRow(newValue)} + } + + //// Packs the values using a generalized diagonal packing. + //// + //// Includes modifications for the baby-step, giant-step algorithm from Section 6.3 of + //// . + public var diagonal: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal { + get { + if case .diagonal(let v)? = matrixPackingType {return v} + return Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal() + } + set {matrixPackingType = .diagonal(newValue)} + } + + //// As many rows of data are packed sequentially into each SIMD plaintext + //// row as possible, such that no data row is split across multiple SIMD rows, and + //// each data row is zero-padded to the next power of two length. + //// The rows in the final plaintext are repeated as many times as possible within the plaintext, + //// with the constraint that either all or none of the entries stored within the last plaintext + //// row are repeated. + public var denseColumn: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn { + get { + if case .denseColumn(let v)? = matrixPackingType {return v} + return Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn() + } + set {matrixPackingType = .denseColumn(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// Different packing formats. + public enum OneOf_MatrixPackingType: Equatable, Sendable { + /// Dense row packing. + case denseRow(Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow) + //// Packs the values using a generalized diagonal packing. + //// + //// Includes modifications for the baby-step, giant-step algorithm from Section 6.3 of + //// . + case diagonal(Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal) + //// As many rows of data are packed sequentially into each SIMD plaintext + //// row as possible, such that no data row is split across multiple SIMD rows, and + //// each data row is zero-padded to the next power of two length. + //// The rows in the final plaintext are repeated as many times as possible within the plaintext, + //// with the constraint that either all or none of the entries stored within the last plaintext + //// row are repeated. + case denseColumn(Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn) + + } + + public init() {} +} + +/// As many rows of data are packed sequentially into each SIMD row as possible, +/// such that no data row is split across multiple SIMD rows, and +/// each data row is zero-padded to the next power of two length. +/// The rows in the final plaintext/ciphertext are repeated as many times as possible within the plaintext/ciphertext, +/// with the constraint that either all or none of the entries stored within the last plaintext/ciphertext +/// row are repeated. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// Packs the values using a generalized diagonal packing. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Diagonals are rotated according to the baby-step, giant-step algorithm from Section 6.3 of . + public var babyStepGiantStep: Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep { + get {return _babyStepGiantStep ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep()} + set {_babyStepGiantStep = newValue} + } + /// Returns true if `babyStepGiantStep` has been explicitly set. + public var hasBabyStepGiantStep: Bool {return self._babyStepGiantStep != nil} + /// Clears the value of `babyStepGiantStep`. Subsequent reads from it will return its default value. + public mutating func clearBabyStepGiantStep() {self._babyStepGiantStep = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _babyStepGiantStep: Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep? = nil +} + +/// As many columns of data are packed sequentially into each SIMD row as possible, such that no SIMD row +/// contains data from multiple columns. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pnns.v1" + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".BabyStepGiantStep" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}vector_dimension\0\u{3}baby_step\0\u{3}giant_step\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularUInt32Field(value: &self.vectorDimension) }() + case 2: try { try decoder.decodeSingularUInt32Field(value: &self.babyStep) }() + case 3: try { try decoder.decodeSingularUInt32Field(value: &self.giantStep) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.vectorDimension != 0 { + try visitor.visitSingularUInt32Field(value: self.vectorDimension, fieldNumber: 1) + } + if self.babyStep != 0 { + try visitor.visitSingularUInt32Field(value: self.babyStep, fieldNumber: 2) + } + if self.giantStep != 0 { + try visitor.visitSingularUInt32Field(value: self.giantStep, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_BabyStepGiantStep) -> Bool { + if lhs.vectorDimension != rhs.vectorDimension {return false} + if lhs.babyStep != rhs.babyStep {return false} + if lhs.giantStep != rhs.giantStep {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".MatrixPacking" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}dense_row\0\u{1}diagonal\0\u{3}dense_column\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow? + var hadOneofValue = false + if let current = self.matrixPackingType { + hadOneofValue = true + if case .denseRow(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.matrixPackingType = .denseRow(v) + } + }() + case 2: try { + var v: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal? + var hadOneofValue = false + if let current = self.matrixPackingType { + hadOneofValue = true + if case .diagonal(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.matrixPackingType = .diagonal(v) + } + }() + case 3: try { + var v: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn? + var hadOneofValue = false + if let current = self.matrixPackingType { + hadOneofValue = true + if case .denseColumn(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.matrixPackingType = .denseColumn(v) + } + }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + switch self.matrixPackingType { + case .denseRow?: try { + guard case .denseRow(let v)? = self.matrixPackingType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .diagonal?: try { + guard case .diagonal(let v)? = self.matrixPackingType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .denseColumn?: try { + guard case .denseColumn(let v)? = self.matrixPackingType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case nil: break + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking) -> Bool { + if lhs.matrixPackingType != rhs.matrixPackingType {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".MatrixPackingDenseRow" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseRow) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".MatrixPackingDiagonal" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{4}\u{2}baby_step_giant_step\0\u{c}\u{1}\u{1}") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 2: try { try decoder.decodeSingularMessageField(value: &self._babyStepGiantStep) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = self._babyStepGiantStep { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDiagonal) -> Bool { + if lhs._babyStepGiantStep != rhs._babyStepGiantStep {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".MatrixPackingDenseColumn" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPackingDenseColumn) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_processed_database.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_processed_database.pb.swift new file mode 100644 index 00000000..39f90536 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_processed_database.pb.swift @@ -0,0 +1,121 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pnns/v1/pnns_processed_database.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Serialized pre-processed nearest neighbor database. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedProcessedDatabase: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Pre-computed values for the nearest neighbor search, one per plaintext CRT modulus. + public var plaintextMatrices: [Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedPlaintextMatrix] = [] + + /// Unique identifier for each entry in the database. + public var entryIds: [UInt64] = [] + + /// Metadata for each entry in the database. + public var entryMetadatas: [Data] = [] + + /// Configuration used to create the database. + public var serverConfig: Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig { + get {return _serverConfig ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig()} + set {_serverConfig = newValue} + } + /// Returns true if `serverConfig` has been explicitly set. + public var hasServerConfig: Bool {return self._serverConfig != nil} + /// Clears the value of `serverConfig`. Subsequent reads from it will return its default value. + public mutating func clearServerConfig() {self._serverConfig = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _serverConfig: Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig? = nil +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pnns.v1" + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedProcessedDatabase: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".SerializedProcessedDatabase" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}plaintext_matrices\0\u{3}entry_ids\0\u{3}entry_metadatas\0\u{3}server_config\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.plaintextMatrices) }() + case 2: try { try decoder.decodeRepeatedUInt64Field(value: &self.entryIds) }() + case 3: try { try decoder.decodeRepeatedBytesField(value: &self.entryMetadatas) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._serverConfig) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !self.plaintextMatrices.isEmpty { + try visitor.visitRepeatedMessageField(value: self.plaintextMatrices, fieldNumber: 1) + } + if !self.entryIds.isEmpty { + try visitor.visitPackedUInt64Field(value: self.entryIds, fieldNumber: 2) + } + if !self.entryMetadatas.isEmpty { + try visitor.visitRepeatedBytesField(value: self.entryMetadatas, fieldNumber: 3) + } + try { if let v = self._serverConfig { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedProcessedDatabase, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_SerializedProcessedDatabase) -> Bool { + if lhs.plaintextMatrices != rhs.plaintextMatrices {return false} + if lhs.entryIds != rhs.entryIds {return false} + if lhs.entryMetadatas != rhs.entryMetadatas {return false} + if lhs._serverConfig != rhs._serverConfig {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_server_config.pb.swift b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_server_config.pb.swift new file mode 100644 index 00000000..4ac95de6 --- /dev/null +++ b/Sources/ApplicationProtobuf/generated/apple_swift_homomorphic_encryption_pnns_v1_pnns_server_config.pb.swift @@ -0,0 +1,149 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: apple/swift_homomorphic_encryption/pnns/v1/pnns_server_config.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// The server configuration. +public struct Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig: @unchecked Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Configuration shared with the client. + public var clientConfig: Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig { + get {return _storage._clientConfig ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig()} + set {_uniqueStorage()._clientConfig = newValue} + } + /// Returns true if `clientConfig` has been explicitly set. + public var hasClientConfig: Bool {return _storage._clientConfig != nil} + /// Clears the value of `clientConfig`. Subsequent reads from it will return its default value. + public mutating func clearClientConfig() {_uniqueStorage()._clientConfig = nil} + + /// Packing for the plaintext database. + public var databasePacking: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking { + get {return _storage._databasePacking ?? Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking()} + set {_uniqueStorage()._databasePacking = newValue} + } + /// Returns true if `databasePacking` has been explicitly set. + public var hasDatabasePacking: Bool {return _storage._databasePacking != nil} + /// Clears the value of `databasePacking`. Subsequent reads from it will return its default value. + public mutating func clearDatabasePacking() {_uniqueStorage()._databasePacking = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _storage = _StorageClass.defaultInstance +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "apple.swift_homomorphic_encryption.pnns.v1" + +extension Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".ServerConfig" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}client_config\0\u{3}database_packing\0\u{c}\u{3}\u{1}\u{c}\u{4}\u{1}") + + fileprivate class _StorageClass { + var _clientConfig: Apple_SwiftHomomorphicEncryption_Pnns_V1_ClientConfig? = nil + var _databasePacking: Apple_SwiftHomomorphicEncryption_Pnns_V1_MatrixPacking? = nil + + // This property is used as the initial default value for new instances of the type. + // The type itself is protecting the reference to its storage via CoW semantics. + // This will force a copy to be made of this reference when the first mutation occurs; + // hence, it is safe to mark this as `nonisolated(unsafe)`. + static nonisolated(unsafe) let defaultInstance = _StorageClass() + + private init() {} + + init(copying source: _StorageClass) { + _clientConfig = source._clientConfig + _databasePacking = source._databasePacking + } + } + + fileprivate mutating func _uniqueStorage() -> _StorageClass { + if !isKnownUniquelyReferenced(&_storage) { + _storage = _StorageClass(copying: _storage) + } + return _storage + } + + public mutating func decodeMessage(decoder: inout D) throws { + _ = _uniqueStorage() + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &_storage._clientConfig) }() + case 2: try { try decoder.decodeSingularMessageField(value: &_storage._databasePacking) }() + default: break + } + } + } + } + + public func traverse(visitor: inout V) throws { + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = _storage._clientConfig { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } }() + try { if let v = _storage._databasePacking { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } }() + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig, rhs: Apple_SwiftHomomorphicEncryption_Pnns_V1_ServerConfig) -> Bool { + if lhs._storage !== rhs._storage { + let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in + let _storage = _args.0 + let rhs_storage = _args.1 + if _storage._clientConfig != rhs_storage._clientConfig {return false} + if _storage._databasePacking != rhs_storage._databasePacking {return false} + return true + } + if !storagesAreEqual {return false} + } + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Sources/ApplicationProtobuf/protobuf_module_mappings.txtpb b/Sources/ApplicationProtobuf/protobuf_module_mappings.txtpb new file mode 100644 index 00000000..742aae11 --- /dev/null +++ b/Sources/ApplicationProtobuf/protobuf_module_mappings.txtpb @@ -0,0 +1,4 @@ +mapping { + module_name: "HomomorphicEncryptionProtobuf" + proto_file_path: "apple/swift_homomorphic_encryption/v1/he.proto" +} diff --git a/Sources/HomomorphicEncryptionProtobuf/ConversionError.swift b/Sources/HomomorphicEncryptionProtobuf/ConversionError.swift index 4ddde180..eb2b5838 100644 --- a/Sources/HomomorphicEncryptionProtobuf/ConversionError.swift +++ b/Sources/HomomorphicEncryptionProtobuf/ConversionError.swift @@ -1,4 +1,4 @@ -// Copyright 2024 Apple Inc. and the Swift Homomorphic Encryption project authors +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ extension ConversionError: LocalizedError { "Invalid HE scheme" case let .unimplementedScheme(scheme: scheme): "Unimplemented encryption scheme: \(scheme)" - case let .unrecognizedEnumValue(enum: enume, value: value): - "Unrecognized value \(value) in enum \(enume)" + case let .unrecognizedEnumValue(enum: enumeration, value: value): + "Unrecognized value \(value) in enum \(enumeration)" case let .unsetOneof(oneof: oneof, field: field): "Unset oneof in message \(oneof) for field \(field)" } diff --git a/Sources/HomomorphicEncryptionProtobuf/generated/README.md b/Sources/HomomorphicEncryptionProtobuf/generated/README.md index 57ca59ca..6462d949 100644 --- a/Sources/HomomorphicEncryptionProtobuf/generated/README.md +++ b/Sources/HomomorphicEncryptionProtobuf/generated/README.md @@ -1,6 +1,6 @@ # Generated files -Files in this directory are auto-generated using swift-protobuf. +Files in this directory are generated using swift-protobuf. See the [dependencies](../../../README.md#dependencies) for the swift-protobuf version. ## Requirements diff --git a/Sources/PrivateInformationRetrievalProtobuf/ConversionError.swift b/Sources/PrivateInformationRetrievalProtobuf/ConversionError.swift index 4b97a777..50d23c6f 100644 --- a/Sources/PrivateInformationRetrievalProtobuf/ConversionError.swift +++ b/Sources/PrivateInformationRetrievalProtobuf/ConversionError.swift @@ -23,10 +23,10 @@ enum ConversionError: Error { extension ConversionError: LocalizedError { public var errorDescription: String? { switch self { - case let .unrecognizedEnumValue(enum: enume, value: value): - "Unrecognized value \(value) in enum \(enume)" - case let .unspecifiedEnumValue(enum: enume): - "Unspecified value for enum \(enume)" + case let .unrecognizedEnumValue(enum: enumeration, value: value): + "Unrecognized value \(value) in enum \(enumeration)" + case let .unspecifiedEnumValue(enum: enumeration): + "Unspecified value for enum \(enumeration)" } } } diff --git a/Sources/PrivateInformationRetrievalProtobuf/generated/README.md b/Sources/PrivateInformationRetrievalProtobuf/generated/README.md index f863975d..d4881ef8 100644 --- a/Sources/PrivateInformationRetrievalProtobuf/generated/README.md +++ b/Sources/PrivateInformationRetrievalProtobuf/generated/README.md @@ -1,6 +1,6 @@ # Generated files -Files in this directory are auto-generated using swift-protobuf. +Files in this directory are generated using swift-protobuf. See the [dependencies](../../../README.md#dependencies) for the swift-protobuf version. ## Requirements diff --git a/Sources/PrivateNearestNeighborSearchProtobuf/generated/README.md b/Sources/PrivateNearestNeighborSearchProtobuf/generated/README.md index c2097aa2..590d66d2 100644 --- a/Sources/PrivateNearestNeighborSearchProtobuf/generated/README.md +++ b/Sources/PrivateNearestNeighborSearchProtobuf/generated/README.md @@ -1,6 +1,6 @@ # Generated files -Files in this directory are auto-generated using swift-protobuf. +Files in this directory are generated using swift-protobuf. See the [dependencies](../../../README.md#dependencies) for the swift-protobuf version. ## Requirements diff --git a/Tests/ApplicationProtobufTests/PirConversionTests.swift b/Tests/ApplicationProtobufTests/PirConversionTests.swift new file mode 100644 index 00000000..cca145f3 --- /dev/null +++ b/Tests/ApplicationProtobufTests/PirConversionTests.swift @@ -0,0 +1,118 @@ +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import _CryptoExtras +import _TestUtilities +import ApplicationProtobuf +import Crypto +import Foundation +@testable import HomomorphicEncryption +@testable import PrivateInformationRetrieval +import Testing + +@Suite +struct PirConversionTests { + @Test + func keywordDatabase() throws { + let rowCount = 10 + let payloadSize = 5 + let databaseRows = (0..> = try .init(encryptionParameters: .init(from: .n_4096_logq_27_28_28_logt_13)) + let config = try KeywordPirConfig( + dimensionCount: 2, + cuckooTableConfig: .defaultKeywordPir(maxSerializedBucketSize: context.bytesPerPlaintext), + unevenDimensions: true, + keyCompression: .noCompression) + let processedDatabaseWithParameters = try KeywordPirServer>>.process( + database: rows, + config: config, + with: context) + + let processedDatabase = processedDatabaseWithParameters.database + + let pirParameters = try processedDatabaseWithParameters.proto(context: context) + let loadedProcessedDatabaseWithParameters = try pirParameters.native(database: processedDatabase) + #expect(loadedProcessedDatabaseWithParameters == processedDatabaseWithParameters) + } + + @Test(arguments: PirAlgorithm.allCases) + func pirAlgorithm(_ algorithm: PirAlgorithm) throws { + #expect(try algorithm.proto().native() == algorithm) + } + + @Test(arguments: PirKeyCompressionStrategy.allCases) + func pirKeyCompressionStrategy(_ strategy: PirKeyCompressionStrategy) throws { + #expect(try strategy.proto().native() == strategy) + } + + @Test + func oprfQuery() throws { + let element = + "02a36bc90e6db34096346eaf8b7bc40ee1113582155ad3797003ce614c835a874343701d3f2debbd80d97cbe45de6e5f1f" + let query = try OprfQuery(oprfRepresentation: Data(#require(Array(hexEncoded: element)))) + let roundTrip = try query.proto().native() + #expect(roundTrip.oprfRepresentation == query.oprfRepresentation) + } + + @Test + func oprfResponse() throws { + let evaluatedElement = + try Data( + #require(Array( + hexEncoded: """ + 02a7bba589b3e8672aa19e8fd258de2e6aae20101c8d761246de97a6b5ee9cf105febce4327a326\ + 255a3c604f63f600ef6 + """))) + + let proof = + try Data( + #require(Array( + hexEncoded: """ + bfc6cf3859127f5fe25548859856d6b7fa1c7459f0ba5712a806fc091a3000c42d8ba34ff45f32a52\ + e40533efd2a03bc87f3bf4f9f58028297ccb9ccb18ae7182bcd1ef239df77e3be65ef147f3acf8bc9\ + cbfc5524b702263414f043e3b7ca2e + """))) + let rawRepresentation = evaluatedElement + proof + let blindEvaluation = try OprfResponse(rawRepresentation: rawRepresentation) + #expect(try blindEvaluation.proto().native().rawRepresentation == blindEvaluation.rawRepresentation) + } + + @Test + func keywordPirParameter() throws { + var keywordPirParameter = KeywordPirParameter(hashFunctionCount: 2) + var roundTrip = try keywordPirParameter.proto().native() + #expect(roundTrip == keywordPirParameter) + let symmetricPirClientConfig = SymmetricPirClientConfig(serverPublicKey: [], + configType: .OPRF_P384_AES_GCM_192_NONCE_96_TAG_128) + keywordPirParameter = KeywordPirParameter(hashFunctionCount: 2, + symmetricPirClientConfig: symmetricPirClientConfig) + roundTrip = try keywordPirParameter.proto().native() + #expect(roundTrip == keywordPirParameter) + } +} diff --git a/Tests/ApplicationProtobufTests/PnnsConversionTests.swift b/Tests/ApplicationProtobufTests/PnnsConversionTests.swift new file mode 100644 index 00000000..008d89ac --- /dev/null +++ b/Tests/ApplicationProtobufTests/PnnsConversionTests.swift @@ -0,0 +1,266 @@ +// Copyright 2024-2025 Apple Inc. and the Swift Homomorphic Encryption project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +@testable import HomomorphicEncryption +@testable import PrivateNearestNeighborSearch + +import Testing + +func increasingData(dimensions: MatrixDimensions, modulus: T) -> [[T]] { + (0..(_: Scheme.Type) throws { + let vectorDimension = 4 + let clientConfig = try ClientConfig( + encryptionParameters: EncryptionParameters( + from: .insecure_n_8_logq_5x18_logt_5), + scalingFactor: 123, + queryPacking: .denseRow, + vectorDimension: vectorDimension, + evaluationKeyConfig: EvaluationKeyConfig(galoisElements: [3]), + distanceMetric: .cosineSimilarity, + extraPlaintextModuli: Scheme.Scalar.generatePrimes( + significantBitCounts: [15], + preferringSmall: true, + nttDegree: 8)) + #expect(try clientConfig.proto().native() == clientConfig) + + let serverConfig = ServerConfig( + clientConfig: clientConfig, + databasePacking: MatrixPacking + .diagonal( + babyStepGiantStep: BabyStepGiantStep(vectorDimension: vectorDimension))) + #expect(try serverConfig.proto().native() == serverConfig) + } + + try runTest(Bfv.self) + try runTest(Bfv.self) + } + + @Test + func database() throws { + let rows = (0...10).map { rowIndex in + DatabaseRow( + entryId: rowIndex, + entryMetadata: rowIndex.littleEndianBytes, + vector: [Float(rowIndex)]) + } + for row in rows { + #expect(row.proto().native() == row) + } + let database = Database(rows: rows) + #expect(database.proto().native() == database) + } + + @Test + func serializedPlaintextMatrix() throws { + func runTest(_: Scheme.Type) throws { + let encryptionParameters = try EncryptionParameters(from: .insecure_n_8_logq_5x18_logt_5) + let context = try Context(encryptionParameters: encryptionParameters) + + let dimensions = try MatrixDimensions(rowCount: 5, columnCount: 4) + let scalars: [[Scheme.Scalar]] = increasingData( + dimensions: dimensions, + modulus: encryptionParameters.plaintextModulus) + let plaintextMatrix = try PlaintextMatrix( + context: context, + dimensions: dimensions, + packing: .denseColumn, + values: scalars.flatMap(\.self)) + let serialized = try plaintextMatrix.serialize() + #expect(try serialized.proto().native() == serialized) + let deserialized = try PlaintextMatrix(deserialize: serialized, context: context) + #expect(deserialized == plaintextMatrix) + + for moduliCount in 1...self) + try runTest(Bfv.self) + } + + @Test + func serializedCiphertextMatrix() throws { + func runTest(_: Scheme.Type) throws { + let encryptionParameters = try EncryptionParameters(from: .insecure_n_8_logq_5x18_logt_5) + let context = try Context(encryptionParameters: encryptionParameters) + let secretKey = try context.generateSecretKey() + + let dimensions = try MatrixDimensions(rowCount: 5, columnCount: 4) + let scalars: [[Scheme.Scalar]] = increasingData( + dimensions: dimensions, + modulus: encryptionParameters.plaintextModulus) + let plaintextMatrix = try PlaintextMatrix( + context: context, + dimensions: dimensions, + packing: .denseColumn, + values: scalars.flatMap(\.self)) + // Check Canonical Format + do { + let ciphertextMatrix = try plaintextMatrix.encrypt(using: secretKey) + let serialized = try ciphertextMatrix.serialize() + let serializedProto = try serialized.proto() + #expect(try serializedProto.native() == serialized) + } + // Check Evaluation format + do { + let ciphertextMatrix = try plaintextMatrix.encrypt(using: secretKey) + let evalCiphertextMatrix = try ciphertextMatrix.convertToEvalFormat() + let serialized = try evalCiphertextMatrix.serialize() + #expect(try serialized.proto().native() == serialized) + let deserialized = try CiphertextMatrix( + deserialize: serialized, + context: context) + #expect(deserialized == evalCiphertextMatrix) + } + // Check serializeForDecryption + do { + var ciphertextMatrix = try plaintextMatrix.encrypt(using: secretKey) + try ciphertextMatrix.modSwitchDownToSingle() + let serializedForDecryption = try ciphertextMatrix.serialize(forDecryption: true) + let serializedForDecryptionSize = try serializedForDecryption.proto().serializedData().count + + let serialized = try ciphertextMatrix.serialize() + let serializedProto = try serialized.proto() + let serializedSize = try serializedProto.serializedData().count + + #expect(serializedForDecryptionSize < serializedSize) + let deserialized = try CiphertextMatrix( + deserialize: serializedForDecryption, + context: context, moduliCount: 1) + let decrypted = try deserialized.decrypt(using: secretKey) + #expect(decrypted == plaintextMatrix) + } + } + + try runTest(Bfv.self) + try runTest(Bfv.self) + } + + @Test + func query() throws { + func runTest(_: Scheme.Type) throws { + let encryptionParameters = try EncryptionParameters(from: .insecure_n_8_logq_5x18_logt_5) + let context = try Context(encryptionParameters: encryptionParameters) + let secretKey = try context.generateSecretKey() + + let dimensions = try MatrixDimensions(rowCount: 5, columnCount: 4) + let scalars: [[Scheme.Scalar]] = increasingData( + dimensions: dimensions, + modulus: encryptionParameters.plaintextModulus) + let plaintextMatrix = try PlaintextMatrix( + context: context, + dimensions: dimensions, + packing: .denseColumn, + values: scalars.flatMap(\.self)) + let ciphertextMatrices = try (0...3).map { _ in + try plaintextMatrix.encrypt(using: secretKey).convertToCoeffFormat() + } + + let query = Query(ciphertextMatrices: ciphertextMatrices) + let roundtrip = try query.proto().native(context: context) + #expect(roundtrip == query) + } + try runTest(Bfv.self) + try runTest(Bfv.self) + } + + @Test + func serializedProcessedDatabase() throws { + func runTest(_: Scheme.Type) throws { + let encryptionParameters = try EncryptionParameters(from: .insecure_n_8_logq_5x18_logt_5) + let vectorDimension = 4 + + let rows = (0...10).map { rowIndex in + DatabaseRow( + entryId: rowIndex, + entryMetadata: rowIndex.littleEndianBytes, + vector: Array(repeating: Float(rowIndex), count: vectorDimension)) + } + for row in rows { + #expect(row.proto().native() == row) + } + let database = Database(rows: rows) + + let clientConfig = try ClientConfig( + encryptionParameters: encryptionParameters, + scalingFactor: 123, + queryPacking: .denseRow, + vectorDimension: vectorDimension, + evaluationKeyConfig: EvaluationKeyConfig(galoisElements: [3]), + distanceMetric: .cosineSimilarity, + extraPlaintextModuli: Scheme.Scalar + .generatePrimes( + significantBitCounts: [7], + preferringSmall: true, + nttDegree: encryptionParameters.polyDegree)) + let serverConfig = ServerConfig( + clientConfig: clientConfig, + databasePacking: MatrixPacking + .diagonal( + babyStepGiantStep: BabyStepGiantStep(vectorDimension: vectorDimension))) + + let processed = try database.process(config: serverConfig) + let serialized = try processed.serialize() + #expect(try serialized.proto().native() == serialized) + } + try runTest(Bfv.self) + try runTest(Bfv.self) + } +} diff --git a/Utilities/generate-protobuf-files.sh b/Utilities/generate-protobuf-files.sh index 585e6149..2b752b89 100755 --- a/Utilities/generate-protobuf-files.sh +++ b/Utilities/generate-protobuf-files.sh @@ -21,12 +21,16 @@ echo "Updating protobuf files" cd swift-homomorphic-encryption-protobuf echo "Removing HomomorphicEncryptionProtobuf swift protobuf files" -rm ../Sources/HomomorphicEncryptionProtobuf/generated/*.pb.swift +rm -f ../Sources/HomomorphicEncryptionProtobuf/generated/*.pb.swift echo "Regenerating HomomorphicEncryptionProtobuf swift protobuf files" -find apple/swift_homomorphic_encryption/v1/ -name "*.proto" -exec protoc --swift_opt=Visibility=Public --swift_opt=FileNaming=PathToUnderscores --swift_out ../Sources/HomomorphicEncryptionProtobuf/generated {} \; +find apple/swift_homomorphic_encryption/v1/ \ + -name "*.proto" -exec protoc \ + --swift_opt=Visibility=Public \ + --swift_opt=FileNaming=PathToUnderscores \ + --swift_out ../Sources/HomomorphicEncryptionProtobuf/generated {} \; echo "Removing PrivateInformationRetrievalProtobuf swift protobuf files" -rm ../Sources/PrivateInformationRetrievalProtobuf/generated/*.pb.swift +rm -f ../Sources/PrivateInformationRetrievalProtobuf/generated/*.pb.swift echo "Regenerating PrivateInformationRetrievalProtobuf swift protobuf files" find apple/swift_homomorphic_encryption/pir/ \ apple/swift_homomorphic_encryption/api/shared/v1/ \ @@ -49,5 +53,20 @@ find apple/swift_homomorphic_encryption/pnns/ \ --swift_opt=FileNaming=PathToUnderscores \ --swift_out ../Sources/PrivateNearestNeighborSearchProtobuf/generated {} \; +echo "Removing ApplicationProtobuf swift protobuf files" +rm -f ../Sources/ApplicationProtobuf/generated/*.pb.swift +echo "Regenerating ApplicationProtobuf swift protobuf files" +find apple/swift_homomorphic_encryption/pnns/ \ + apple/swift_homomorphic_encryption/pir/ \ + apple/swift_homomorphic_encryption/api/shared/ \ + apple/swift_homomorphic_encryption/api/v1/ \ + apple/swift_homomorphic_encryption/api/pir/v1/pir.proto \ + apple/swift_homomorphic_encryption/api/pnns/v1/pnns.proto \ + -name "*.proto" -exec protoc \ + --swift_opt=ProtoPathModuleMappings=../Sources/ApplicationProtobuf/protobuf_module_mappings.txtpb \ + --swift_opt=Visibility=Public \ + --swift_opt=FileNaming=PathToUnderscores \ + --swift_out ../Sources/ApplicationProtobuf/generated {} \; + cd - echo "Done updating protobuf files"