Files
ssw-mpc/tools/check_psi.py
T
admin e01c7f9419 docs: 按新定位重写中文描述,修复参考实现路径误改
- 中文定位从「Rust 重写 Python 算术执行引擎」改为「多方数据协同、数据不出域的安全计算框架」;README/CLAUDE/ARCHITECTURE/GAP_PLAN 同步,沿革小节写明新旧语义差别
- 修复机械替换引入的功能 bug:gen_golden.py / check_psi.py / bench_numpy.py 的 refs/mpc/mpc 路径改回 refs/nax/nax(参考实现真实目录,CI 不跑这些脚本故未暴露)
- 恢复 Python 参考实现包名 import nax;mpc-python 统一改称「Python 参考实现」;远端仓库描述同步
2026-11-05 15:17:28 +08:00

90 lines
2.7 KiB
Python
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.
#!/usr/bin/env python3
"""PSI 语义对照:用参考实现跑同一组数据,确认交集与 Rust 版一致。
# 为什么不能做逐位对照
PSI 每轮都洗牌 + 每次用随机标量,输出天然不确定。
能对照的只有**语义**:同样的两方输入,交集必须是同一批 ID。
# 一处已知差异(不影响交集)
Rust 版 `hash_to_point` 用 SHA-256,参考实现用 SHA-512。
所以两边算出的曲线点**不同**,但 `x ∈ Y` 的判定结果一致 ——
只要协议双方用同一个映射即可。这个脚本验证的正是这一点。
用法:
.venv/bin/python tools/check_psi.py
"""
from __future__ import annotations
import importlib.util
import pathlib
import sys
import types
ROOT = pathlib.Path(__file__).resolve().parent.parent
CRYPTO = ROOT / "refs" / "nax" / "nax" / "crypto"
A_IDS = [1, 2, 3, 4, 5]
B_IDS = [3, 4, 5, 6, 7]
EXPECT = [3, 4, 5]
def load_module(name: str, path: pathlib.Path, source_patch: dict[str, str] | None = None):
"""按文件加载模块;可选地对源码做字面替换(用于拆掉相对导入)。"""
src = path.read_text(encoding="utf-8")
for old, new in (source_patch or {}).items():
src = src.replace(old, new)
mod = types.ModuleType(name)
mod.__file__ = str(path)
sys.modules[name] = mod
exec(compile(src, str(path), "exec"), mod.__dict__)
return mod
def main() -> int:
curve = load_module("ref_curve25519", CRYPTO / "curve25519.py")
psi = load_module(
"ref_psi",
CRYPTO / "psi.py",
{"from .curve25519 import hash_to_point, scalar_mult":
"from ref_curve25519 import hash_to_point, scalar_mult"},
)
# 模拟参考实现 data/psi.py 的两方流程
ka = curve.random_scalar()
kb = curve.random_scalar()
pa, perm_a = psi.blind(A_IDS, ka, seed=7)
pb, perm_b = psi.blind(B_IDS, kb, seed=11)
# 交叉双盲
ab = psi.reblind(pb, ka) # alice 视角:bob 的双盲
ba = psi.reblind(pa, kb) # bob 视角:alice 的双盲
idx_a = psi.resolve(perm_a, psi.match(ba, ab))
idx_b = psi.resolve(perm_b, psi.match(ab, ba))
hits_a = [A_IDS[i] for i in idx_a]
hits_b = [B_IDS[i] for i in idx_b]
print("Python 参考实现(SHA-512 hash_to_point)")
print(f" alice 交集: {hits_a}")
print(f" bob 交集: {hits_b}")
print()
print("Rust mpc-psi(SHA-256 hash_to_point)")
print(f" 期望交集: {EXPECT}")
print()
ok = hits_a == EXPECT and hits_b == EXPECT
if ok:
print("PASS: 两套实现的交集语义一致(哈希映射不同不影响判定)")
return 0
print(f"FAIL: 参考实现得到 {hits_a} / {hits_b},期望 {EXPECT}")
return 1
if __name__ == "__main__":
sys.exit(main())