Files
ssw-mpc/crates/mpc-node/tests/psi_cache.rs
T
admin 54781b3f83
ci / gate (push) Waiting to run
refactor: 项目改名 ssw-mpc,crate 统一到 mpc-* 前缀
- 项目与文档标题:nax-rs → ssw-mpc(尚数网-多方安全计算),二进制 nax → mpc
- 18 个 crate 及目录 nax-* → mpc-*,Rust 引用 nax_* → mpc_*
- 环境变量、C 符号、构建/部署脚本:NAX_* → MPC_*、libnax_ray.so → libmpc_ray.so
- 保留协议域分隔常量与 refs/nax 参考实现路径,维持 golden 向量与历史数据兼容
- 新增 [profile.dev] incremental=false
2026-11-05 15:06:12 +08:00

282 lines
10 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 跨会话 PSI:缓存版必须与不缓存版**求交结果完全一致**,而稳态下 EC 次数为零。
//!
//! # 这两条为什么必须一起断言
//!
//! 只断言「结果一致」是不够的:缓存全不命中时结果当然一致,那只是一条更慢的
//! 老路径。只断言「零 EC」更糟:算错了也是零 EC。
//!
//! 所以每条用例都是两半:
//!
//! * `cached_matches_uncached` —— 管**对不对**(含 n=3、含中途增删);
//! * `warm_session_needs_no_ec` —— 管**快不快**(`misses` 就是做过的标量乘次数)。
//!
//! # 为什么用内存管道而不是真 TCP
//!
//! 这里要量的是 EC 与查表,不是网络。`MeshPipe` 的帧传递是 channel,
//! 开销可忽略,于是 `misses` 的差值能干净地换算成墙钟(见 `bench_psi_cache.rs`)。
//!
//! # 刻意**不**断言的事
//!
//! 不断言「缓存版算出来的点与不缓存版相同」—— 它们本来就不同:加速模式把
//! 会话标识换成了关系标识,点空间整个变了。交集相同才是要守的不变量。
use std::thread;
use mpc_node::{run_psi_session, run_psi_session_accelerated, PsiAccel, PsiConfig};
use mpc_psi::cache::BlindCache;
use mpc_psi::id_from_u64;
use mpc_vault::MeshPipe;
/// 一方:site 名 + ID 集合 + 私钥种子(两方必须不同)。
struct Party {
site: &'static str,
ids: Vec<u64>,
seed: [u8; 32],
}
impl Party {
fn config(&self, sites: &[String], my_idx: usize, session: [u8; 32]) -> PsiConfig {
PsiConfig {
site: self.site.to_string(),
sites: sites.to_vec(),
my_idx,
ids: self.ids.iter().map(|v| id_from_u64(*v)).collect(),
seed: self.seed,
session,
}
}
}
fn pair() -> Vec<Party> {
vec![
// alice 0..12,bob 6..18 → 交集 6..12
Party {
site: "alice",
ids: (0..12).collect(),
seed: [0xA1; 32],
},
Party {
site: "bob",
ids: (6..18).collect(),
seed: [0xB2; 32],
},
]
}
/// 跑一场会话,返回(各方交集下标, 各方缓存)。
///
/// `caches` 为空表示**不用缓存**(走 `run_psi_session`,与生产默认一致);
/// 否则长度必须等于方数。`relation` 为 `None` 时加速模式也不启用 ——
/// 缓存与关系标识是一对,不给就都不给。
fn run(
parties: &[Party],
session: [u8; 32],
caches: Vec<BlindCache>,
relation: Option<[u8; 32]>,
) -> (Vec<Vec<usize>>, Vec<BlindCache>) {
let n = parties.len();
assert!(caches.is_empty() || caches.len() == n);
let sites: Vec<String> = parties.iter().map(|p| p.site.to_string()).collect();
// party 编号按字典序,与 `TcpMesh` 一致
let mut sorted = sites.clone();
sorted.sort();
let idx_of = |site: &str| sorted.iter().position(|s| s == site).unwrap();
let endpoints = MeshPipe::mesh(n);
let use_cache = !caches.is_empty();
// **按 party 顺序**发缓存,不能用 `pop()`:每个缓存的索引盐绑在那一方的
// 密钥上,发错人就整表作废(表现为「热会话一次都没命中」)。
let mut cache_iter = caches.into_iter();
let out: Vec<(Vec<usize>, Option<BlindCache>)> = thread::scope(|s| {
let handles: Vec<_> = endpoints
.into_iter()
.enumerate()
.map(|(i, pipe)| {
let cache = if use_cache { cache_iter.next() } else { None };
let cfg = parties[i].config(&sites, idx_of(parties[i].site), session);
let rel = relation;
s.spawn(move || {
let mut cache = cache;
let idx = match (rel, cache.as_mut()) {
(Some(relation), Some(c)) => run_psi_session_accelerated(
pipe,
&cfg,
Some(PsiAccel {
cache: c,
relation,
}),
false,
),
_ => run_psi_session(pipe, &cfg, false),
}
.expect("会话失败");
(idx, cache)
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
let mut idxs: Vec<Vec<usize>> = Vec::with_capacity(n);
let mut remaining: Vec<BlindCache> = Vec::new();
for (idx, cache) in out.into_iter() {
idxs.push(idx);
if let Some(c) = cache {
remaining.push(c);
}
}
// 句柄按 party 顺序 join,所以缓存顺序与 party 顺序一致
assert!(remaining.is_empty() || remaining.len() == n);
(idxs, remaining)
}
/// 关系标识:由排序后的名单派生,两方算出同一个值。
fn relation() -> [u8; 32] {
let sites = pair();
let refs: Vec<&str> = sites.iter().map(|p| p.site).collect();
mpc_psi::strict::relationship_id(&refs)
}
fn caches(n: usize) -> Vec<BlindCache> {
(0..n).map(|_| BlindCache::new()).collect()
}
/// 缓存版与不缓存版:交集必须逐条相同(两方)。
#[test]
fn cached_matches_uncached() {
let p = pair();
let plain = run(&p, [1u8; 32], Vec::new(), None).0;
assert_eq!(plain[0], (6..12).collect::<Vec<_>>(), "基线交集就错了");
let first = run(&p, [2u8; 32], caches(2), Some(relation()));
assert_eq!(first.0, plain, "冷缓存会话的结果必须与基线相同");
let second = run(&p, [3u8; 32], first.1, Some(relation()));
assert_eq!(second.0, plain, "热缓存会话(换了会话标识)结果也必须相同");
}
/// 稳态零 EC:第二次会话一次标量乘都不做。
///
/// `misses` 就是做过的 EC 次数 —— 每个未命中恰好对应一次标量乘,
/// 见 `BlindCache::blind_items` / `reblind`。两方各 `|X|` 次盲化 + `|X|` 次再盲化。
#[test]
fn warm_session_needs_no_ec() {
let p = pair();
let n = p[0].ids.len();
assert_eq!(p[1].ids.len(), n, "这条用例要求两方等长");
let cold = run(&p, [4u8; 32], caches(2), Some(relation()));
for (i, c) in cold.1.iter().enumerate() {
assert_eq!(c.misses(), (2 * n) as u64, "第 {i} 方冷会话该做 2n 次 EC");
assert_eq!(c.hits(), 0);
}
let warm = run(&p, [5u8; 32], cold.1, Some(relation()));
for (i, c) in warm.1.iter().enumerate() {
assert_eq!(
c.misses(),
(2 * n) as u64,
"第 {i} 方热会话**不该**新增 EC(misses 应停在上一次的 2n)"
);
assert_eq!(c.hits(), (2 * n) as u64, "第 {i} 方热会话应全部命中");
}
}
/// 增量:多加一条 ID,只该为这一条付一次 EC。
#[test]
fn incremental_add_costs_one_ec() {
let mut p = pair();
let cold = run(&p, [6u8; 32], caches(2), Some(relation()));
let before: Vec<u64> = cold.1.iter().map(|c| c.misses()).collect();
// alice 多一条(9 号已在交集里,换 100 号不影响交集)
p[0].ids.push(100);
let warm = run(&p, [7u8; 32], cold.1, Some(relation()));
// alice 侧:blind 多算 1 条;reb 用的是 bob 的点,一条没变 → 0
assert_eq!(
warm.1[0].misses() - before[0],
1,
"alice 多一条 ID 只该多一次盲化"
);
// bob 侧:blind 没变;reb 收到 alice 的点里多了一个 → 1
assert_eq!(
warm.1[1].misses() - before[1],
1,
"bob 只该为新增那个点再盲化一次"
);
// 交集是 ID 6..12:alice 那边在行 6..12,bob 那边在行 0..6
assert_eq!(warm.0[0], (6..12).collect::<Vec<_>>());
assert_eq!(warm.0[1], (0..6).collect::<Vec<_>>());
}
/// 关系标识每场都变(等于退回会话级 domain):结果照旧对,但缓存永不命中。
///
/// 这条是**反向守卫** —— 它钉住「缓存之所以有效,是因为 domain 不再按会话变」。
/// 谁要是把 domain 改回每场一换,`cached_matches_uncached` 仍然会绿,
/// 只有这一条会红。
#[test]
fn per_session_relation_means_no_cache_hits() {
let p = pair();
let n = p[0].ids.len();
let mut caches = caches(2);
for s in 0..3u8 {
// 每场换一个「关系」→ 每场都整表作废
let rel = mpc_psi::strict::relationship_id(&[&format!("s{s}"), "bob"]);
let out = run(&p, [8 + s; 32], std::mem::take(&mut caches), Some(rel));
caches = out.1;
assert_eq!(out.0[0], (6..12).collect::<Vec<_>>(), "结果必须仍然正确");
// `misses` 是累计值(`bind` 清表但不清计量),所以是 2n × 已跑场数
for c in &caches {
assert_eq!(
c.misses(),
(2 * n * (s as usize + 1)) as u64,
"每场都该重算 2n 次"
);
assert_eq!(c.hits(), 0, "domain 变了,一条都不该命中");
}
}
}
/// 三方(n=3):每方盲化 1 趟 + 再盲化 2 趟,热缓存同样归零。
#[test]
fn n_way_cached_matches_uncached() {
let p = vec![
Party {
site: "alice",
ids: (0..10).collect(),
seed: [0x11; 32],
},
Party {
site: "bob",
ids: (3..13).collect(),
seed: [0x22; 32],
},
Party {
site: "carol",
ids: (6..16).collect(),
seed: [0x33; 32],
},
];
let n = p[0].ids.len();
let plain = run(&p, [11u8; 32], Vec::new(), None).0;
assert_eq!(plain[0], (6..10).collect::<Vec<_>>(), "三方交集是 6..10");
let rel = mpc_psi::strict::relationship_id(&["alice", "bob", "carol"]);
let cold = run(&p, [12u8; 32], caches(3), Some(rel));
assert_eq!(cold.0, plain, "三方冷缓存结果必须与基线相同");
for (i, c) in cold.1.iter().enumerate() {
assert_eq!(c.misses(), (3 * n) as u64, "第 {i} 方该做 3n 次 EC(1 盲 + 2 再盲)");
}
let warm = run(&p, [13u8; 32], cold.1, Some(rel));
assert_eq!(warm.0, plain);
for (i, c) in warm.1.iter().enumerate() {
assert_eq!(c.misses(), (3 * n) as u64, "第 {i} 方热缓存不该新增 EC");
}
}