Skip to content

Commit

Permalink
Fix sharding
Browse files Browse the repository at this point in the history
There was a mistake in sharding. I added a test and made the sharding
compatible with the device code.
  • Loading branch information
karulont committed Jul 31, 2024
1 parent 3051e71 commit e61e2a9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
11 changes: 6 additions & 5 deletions Sources/PrivateInformationRetrieval/KeywordDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import CryptoKit
import Foundation
import HomomorphicEncryption

Expand Down Expand Up @@ -52,11 +53,11 @@ extension KeywordValuePair.Keyword {
/// - Returns: The shard index.
@inlinable
func shardIndex(shardCount: Int) -> Int {
HashKeyword
.indexFromHash(
keywordHash: HashKeyword.hash(keyword: self),
bucketCount: shardCount,
counter: 0)
let digest = SHA256.hash(data: self)
let truncatedHash = digest.withUnsafeBytes { buffer in
buffer.load(as: UInt64.self)
}
return Int(truncatedHash % UInt64(shardCount))
}
}

Expand Down
11 changes: 11 additions & 0 deletions Tests/PrivateInformationRetrievalTests/KeywordDatabaseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,15 @@ class KeywordDatabaseTests: XCTestCase {
XCTAssert(database.shards.contains { shard in shard.value[row.keyword] == row.value })
}
}

func testShardingKnownAnswerTest() throws {
func checkKeywordShard(_ keyword: KeywordValuePair.Keyword, shardCount: Int, expectedShard: Int) {
XCTAssertEqual(keyword.shardIndex(shardCount: shardCount), expectedShard)
}

checkKeywordShard([0, 0, 0, 0], shardCount: 41, expectedShard: 2)
checkKeywordShard([0, 0, 0, 0], shardCount: 1001, expectedShard: 635)
checkKeywordShard([1, 2, 3], shardCount: 1001, expectedShard: 903)
checkKeywordShard([3, 2, 1], shardCount: 1001, expectedShard: 842)
}
}

0 comments on commit e61e2a9

Please sign in to comment.