//! Distributed Point Function (DPF) implementation. //! //! This module builds 2-party DPF keys for point functions over a finite //! domain. Given two keys and an index, XORing the two evaluations yields 1 //! at the target index and 0 elsewhere. //! //! API surface: //! - `Dpf(n)` returns a type for a `2^n` domain with `init`, `generateKeys`, `evaluate`, //! `destroyKey`, and `deinit` methods. //! //! References: //! - Daniel Kales' [CPP DPF implementation](https://github.com/dkales/dpf-cpp/) //! - David Heath's Secure Computation slides on PIR, formerly in //! https://courses.grainger.illinois.edu/cs507/fa2025/ but has been moved. const std = @import("std"); const Io = std.Io; const Aes = std.crypto.core.aes.Aes128; const AesEncryptCtx = std.crypto.core.aes.AesEncryptCtx(Aes); const aes_block_length = Aes.key_bits / 8; /// Actual seed size is 127 bits where the MSB must be cleared. const Seed = u128; /// Seed right shift value const seed_msb_right_shift = 127; /// Seed MSB mask. const seed_msb_mask = ~@as(u128, 1 << seed_msb_right_shift); /// Correction word for DPF key, used during evaluation to correct the PRF output /// when constructing the DPF tree. const CorrectionWord = struct { /// Correction seed value seed: Seed, /// Left indicator bit correction left_indicator: u1, /// Right indicator bit correction right_indicator: u1, }; /// Output from a PRG evaluation, containing an expanded seed and an indicator bit. const Expansion = struct { /// Seed output from PRG seed: Seed, /// Indicator bit (0 or 1) determining the path in the DPF tree indicator: u1, }; /// Clears the most significant bit of the seed to ensure a valid 127-bit seed. /// DPF seeds use only 127 bits (MSB must be 0). inline fn clearMsbSeed(seed: *Seed) void { seed.* &= seed_msb_mask; } /// 256-bit key for the PRG (Pseudo-Random Generator). /// Contains two 128-bit AES keys: one for left PRG, another for right PRG. pub const PrgKey = struct { left: [aes_block_length]u8, right: [aes_block_length]u8, }; /// AES-based PRG for DPF. Takes in a `key` AES block, a `seed` that is the /// size of an AES block minus 1, and the `exp` that will be filled. /// /// Function expects `seed` MSB to be cleared. fn prg(ctx: AesEncryptCtx, seed: *const Seed, exp: *Expansion) void { // make sure MSB is cleared std.debug.assert(seed.* >> seed_msb_right_shift != 1); ctx.encrypt(@ptrCast(&exp.seed), @ptrCast(seed)); exp.indicator = @intCast(exp.seed >> seed_msb_right_shift); clearMsbSeed(&exp.seed); } /// Update the `indicator` and `seed` in the `generateKeys` function. /// /// Copies over the expanded seed and indicator, with an additional XOR with /// the `cw` if `indicator` is set. inline fn generateUpdateIndicatorSeed( indicator: *u1, seed: *Seed, prg_out: Expansion, cw: *const CorrectionWord, comptime indicator_side: enum { left_indicator, right_indicator }, ) void { if (indicator.* == 1) { seed.* = prg_out.seed ^ cw.seed; indicator.* = prg_out.indicator ^ @field(cw, @tagName(indicator_side)); } else { seed.* = prg_out.seed; indicator.* = prg_out.indicator; } } /// XORs the indicator bit in the expansion with the corresponding correction word indicator. /// Used during evaluation to apply correction when the indicator is set. inline fn expandKeyUpdateExpansionWithCorrectionWord( exp: *Expansion, cw: *const CorrectionWord, comptime indicator_side: enum { left_indicator, right_indicator }, ) void { exp.indicator ^= @field(cw, @tagName(indicator_side)); } /// DPF (Distributed Point Function) factory. /// Creates a DPF instance for a domain with `2^n` items. /// - `n`: The domain exponent / number of DPF tree levels. /// /// Returns a struct type with `init`, `generateKeys`, `evaluate`, and `deinit` methods. pub fn Dpf(comptime n: comptime_int) type { if (n <= 0) @compileError("Dpf(n) requires n > 0"); const IndexType = std.meta.Int(.unsigned, n); const size = @as(comptime_int, 1) << n; // DPF key pair containing the secret key material. const Key = struct { // Initial seed for PRG expansion seed: Seed, // Base indicator bit (starting point for tree traversal) base_indicator: u1, // Array of correction words for each level of the DPF tree correction_words: [n]CorrectionWord, }; // HashMap context for DPF keys, provides hash and equality functions // for using Keys as HashMap keys. const KeyContext = struct { const Self = @This(); pub fn hash(_: Self, key: *const Key) u32 { var h = std.hash.Fnv1a_32.init(); h.update(@ptrCast(&key.seed)); h.update(&[_]u8{key.base_indicator}); for (key.correction_words) |cw| { h.update(@ptrCast(&cw.seed)); h.update(&[_]u8{ cw.left_indicator, cw.right_indicator }); } return h.final(); } pub fn eql(_: Self, a: *const Key, b: *const Key) bool { if (a.correction_words.len != b.correction_words.len) return false; var result = std.mem.eql(u8, @ptrCast(&a.seed), @ptrCast(&b.seed)) and a.base_indicator == b.base_indicator; for (a.correction_words, b.correction_words) |acw, bcw| { result = result and std.mem.eql(u8, @ptrCast(&acw.seed), @ptrCast(&bcw.seed)) and acw.left_indicator == bcw.left_indicator and acw.right_indicator == bcw.right_indicator; } return result; } }; // Cache for memoizing full key evaluations (key -> array of indicators) const Cache = std.HashMap(*const Key, [size]u1, KeyContext, std.hash_map.default_max_load_percentage); return struct { const Self = @This(); pub const Index = IndexType; pub const domain_size = size; left_prg_key: AesEncryptCtx, right_prg_key: AesEncryptCtx, allocator: std.mem.Allocator, io: Io, cache: Cache, /// Initialize a DPF instance. /// - `allocator`: Memory allocator for key storage and caching /// - `prg_key`: 256-bit key for the PRG (first 128 bits = left key, second 128 bits = right key) /// Returns a DPF instance ready for key generation and evaluation. pub fn init(allocator: std.mem.Allocator, io: Io, prg_key: *const PrgKey) Self { return .{ .left_prg_key = Aes.initEnc(prg_key.left), .right_prg_key = Aes.initEnc(prg_key.right), .allocator = allocator, .io = io, .cache = Cache.init(allocator), }; } /// Free all allocated memory including cached evaluation results. pub fn deinit(self: *Self) void { self.cache.deinit(); } /// Free a key and its correction words. pub fn destroyKey(self: *const Self, key: *Key) void { self.allocator.destroy(key); } /// Generate a key pair for a specific `index` in the DPF domain. pub fn generateKeys(self: *const Self, index: Index) !struct { *Key, *Key } { var key0 = try self.allocator.create(Key); errdefer self.allocator.destroy(key0); var key1 = try self.allocator.create(Key); errdefer self.allocator.destroy(key1); const corr_words = &key0.correction_words; try self.io.randomSecure(@ptrCast(&key0.seed)); try self.io.randomSecure(@ptrCast(&key1.seed)); key0.base_indicator = @intCast(key0.seed >> seed_msb_right_shift); key1.base_indicator = ~key0.base_indicator; clearMsbSeed(&key0.seed); clearMsbSeed(&key1.seed); var indicator0 = key0.base_indicator; var indicator1 = key1.base_indicator; var seed0: Seed = undefined; var seed1: Seed = undefined; seed0 = key0.seed; seed1 = key1.seed; var left_output_for_key0: Expansion = undefined; var right_output_for_key0: Expansion = undefined; var left_output_for_key1: Expansion = undefined; var right_output_for_key1: Expansion = undefined; for (corr_words, 0..) |*cw, level| { prg(self.left_prg_key, &seed0, &left_output_for_key0); prg(self.right_prg_key, &seed0, &right_output_for_key0); prg(self.left_prg_key, &seed1, &left_output_for_key1); prg(self.right_prg_key, &seed1, &right_output_for_key1); // bit checked if it is left or right partition in DPF tree const level_bit = index >> @intCast(n - 1 - level) & 1; if (level_bit == 0) { // left half // cancel out right values cw.seed = right_output_for_key0.seed ^ right_output_for_key1.seed; cw.left_indicator = left_output_for_key0.indicator ^ left_output_for_key1.indicator ^ 1; cw.right_indicator = right_output_for_key0.indicator ^ right_output_for_key1.indicator; // continue on to left partition generateUpdateIndicatorSeed(&indicator0, &seed0, left_output_for_key0, cw, .left_indicator); generateUpdateIndicatorSeed(&indicator1, &seed1, left_output_for_key1, cw, .left_indicator); } else { // right half // cancel out left values cw.seed = left_output_for_key0.seed ^ left_output_for_key1.seed; cw.left_indicator = left_output_for_key0.indicator ^ left_output_for_key1.indicator; cw.right_indicator = right_output_for_key0.indicator ^ right_output_for_key1.indicator ^ 1; // continue on to right partition generateUpdateIndicatorSeed(&indicator0, &seed0, right_output_for_key0, cw, .right_indicator); generateUpdateIndicatorSeed(&indicator1, &seed1, right_output_for_key1, cw, .right_indicator); } } @memcpy(&key1.correction_words, corr_words); return .{ key0, key1 }; } /// Evaluate the DPF using `key` at point `i` and output a single bit. pub fn evaluate(self: *Self, key: *const Key, i: Index) !u1 { const response = try self.cache.getOrPut(key); if (!response.found_existing) { response.value_ptr.* = try self.expandKeyToIndicators(key); } return response.value_ptr.*[@intCast(i)]; } /// Expand a DPF key into a full array of indicator bits. pub fn expandKeyToIndicators(self: *const Self, key: *const Key) ![size]u1 { const StackNode = struct { exp: Expansion, lvl: usize, }; var stack = try self.allocator.alloc(StackNode, n + 1); defer self.allocator.free(stack); stack[0] = .{ .exp = .{ .seed = key.seed, .indicator = key.base_indicator }, .lvl = 0, }; var stack_size: usize = 1; var indicators: [size]u1 = undefined; var indicators_idx: usize = 0; while (stack_size > 0 and indicators_idx < size) { const node = stack[stack_size - 1]; stack_size -= 1; if (node.lvl >= n) { indicators[indicators_idx] = node.exp.indicator; indicators_idx += 1; continue; } var left_exp: Expansion = undefined; var right_exp: Expansion = undefined; prg(self.left_prg_key, &node.exp.seed, &left_exp); prg(self.right_prg_key, &node.exp.seed, &right_exp); if (node.exp.indicator == 1) { const cw = &key.correction_words[node.lvl]; left_exp.seed ^= key.correction_words[node.lvl].seed; right_exp.seed ^= key.correction_words[node.lvl].seed; left_exp.indicator ^= cw.left_indicator; right_exp.indicator ^= cw.right_indicator; } std.debug.assert(stack_size + 2 <= stack.len); stack[stack_size + 1] = .{ .exp = left_exp, .lvl = node.lvl + 1 }; stack[stack_size] = .{ .exp = right_exp, .lvl = node.lvl + 1 }; stack_size += 2; } return indicators; } }; } fn testPrgKey(io: Io) !PrgKey { var prg_key: PrgKey = undefined; try io.randomSecure(&prg_key.left); try io.randomSecure(&prg_key.right); return prg_key; } test "dpf point function correctness small sizes" { const allocator = std.testing.allocator; const io = std.testing.io; const prg_key = try testPrgKey(io); const logns = [_]comptime_int{ 1, 2, 3, 4 }; inline for (logns) |n| { const DpfN = Dpf(n); const size = DpfN.domain_size; for (0..size) |index| { var dpf = DpfN.init(allocator, io, &prg_key); defer dpf.deinit(); const key0, const key1 = try dpf.generateKeys(@intCast(index)); defer { dpf.destroyKey(key0); dpf.destroyKey(key1); } for (0..size) |i| { const e0 = try dpf.evaluate(key0, @intCast(i)); const e1 = try dpf.evaluate(key1, @intCast(i)); const result = e0 ^ e1; if (i == index) { try std.testing.expectEqual(@as(u1, 1), result); } else { try std.testing.expectEqual(@as(u1, 0), result); } } } } } test "dpf point function correctness larger exponent" { const allocator = std.testing.allocator; const io = std.testing.io; const prg_key = try testPrgKey(io); const n = 5; const DpfN = Dpf(n); const size = DpfN.domain_size; for (0..size) |index| { var dpf = DpfN.init(allocator, io, &prg_key); defer dpf.deinit(); const key0, const key1 = try dpf.generateKeys(@intCast(index)); defer { dpf.destroyKey(key0); dpf.destroyKey(key1); } for (0..size) |i| { const e0 = try dpf.evaluate(key0, @intCast(i)); const e1 = try dpf.evaluate(key1, @intCast(i)); const result = e0 ^ e1; if (i == index) { try std.testing.expectEqual(@as(u1, 1), result); } else { try std.testing.expectEqual(@as(u1, 0), result); } } } } test "dpf seed and indicator invariants" { const allocator = std.testing.allocator; const io = std.testing.io; const prg_key = try testPrgKey(io); const n = 3; const DpfN = Dpf(n); const size = DpfN.domain_size; var dpf = DpfN.init(allocator, io, &prg_key); defer dpf.deinit(); for (0..size) |index| { const key0, const key1 = try dpf.generateKeys(@intCast(index)); defer { dpf.destroyKey(key0); dpf.destroyKey(key1); } const key0_msb: u1 = @intCast(key0.seed >> seed_msb_right_shift); const key1_msb: u1 = @intCast(key1.seed >> seed_msb_right_shift); try std.testing.expectEqual(@as(u1, 0), key0_msb); try std.testing.expectEqual(@as(u1, 0), key1_msb); try std.testing.expectEqual(@as(u1, 1), key0.base_indicator ^ key1.base_indicator); } } test "dpf evaluation caches results" { const allocator = std.testing.allocator; const io = std.testing.io; const prg_key = try testPrgKey(io); const n = 4; const DpfN = Dpf(n); const size = DpfN.domain_size; var dpf = DpfN.init(allocator, io, &prg_key); defer dpf.deinit(); const key0, const key1 = try dpf.generateKeys(3); defer { dpf.destroyKey(key0); dpf.destroyKey(key1); } for (0..size) |i| { _ = try dpf.evaluate(key0, @intCast(i)); } try std.testing.expectEqual(@as(usize, 1), dpf.cache.count()); for (0..size) |i| { _ = try dpf.evaluate(key0, @intCast(i)); } try std.testing.expectEqual(@as(usize, 1), dpf.cache.count()); for (0..size) |i| { _ = try dpf.evaluate(key1, @intCast(i)); } try std.testing.expectEqual(@as(usize, 2), dpf.cache.count()); }