Files
ssw-mvp/nax/examples/01_hello_mpc.py
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

74 lines
2.8 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.
"""示例 1:密文算术入门。
三家机构各自持有一份数据,谁都不想给别人看,但要一起算出结果。
要点:
* ``site.put`` 把数据留在参与方本地,driver 拿不到;
* ``vault.share`` 把它切成加性分片,任何单方分片都是均匀随机数;
* 之后的 ``+ - * @`` 全在密文上做,明文自始至终没有重组过;
* 只有显式 ``reveal`` 才会把结果还原给指定的一方。
"""
import numpy as np
from _common import backend, kv, title
import nax
def main() -> None:
nax.init(["alice", "bob", "carol"], backend=backend(), seed=2024)
alice, bob, carol = nax.site("alice"), nax.site("bob"), nax.site("carol")
box = nax.vault([alice, bob, carol], seed=7)
title("1. 各方把自己的数据放进安全域")
a_val = np.array([1.5, -2.0, 3.25, 0.5])
b_val = np.array([2.0, 4.0, -1.0, 8.0])
x = box.share(alice.put(a_val))
y = box.share(bob.put(b_val))
kv("alice 的向量", a_val)
kv("bob 的向量", b_val)
kv("秘密引用", x)
title("2. 看看分片长什么样(仅演示,生产中拿不到)")
for name, h in x.shares.items():
raw = nax.get_cluster().fetch(h, force=True)
kv(f"{name} 持有的分片", f"{raw[:2]} ... (uint64 环上的均匀随机数)")
kv("三片之和 == 原始值?", "是,但需要三方同时凑齐才行")
title("3. 在密文上做四则运算")
z = x * y + 1.0 # 密文 × 密文,再加公开常数
w = (x - y) * 0.5 # 密文 - 密文,再乘公开标量
kv("x*y+1 密文结果", z.reveal(to=alice).fetch())
kv("x*y+1 明文校验", a_val * b_val + 1.0)
kv("(x-y)/2 密文结果", w.reveal(to=bob).fetch())
kv("(x-y)/2 明文校验", (a_val - b_val) * 0.5)
title("4. 矩阵乘与归约")
m_val = np.arange(12, dtype=np.float64).reshape(4, 3) / 3.0
m = box.share(carol.put(m_val))
prod = x.reshape(1, 4) @ m # 密文 @ 密文
kv("x @ M 密文结果", prod.reveal(to=alice).fetch().round(4))
kv("x @ M 明文校验", (a_val.reshape(1, 4) @ m_val).round(4))
kv("sum(x) 密文结果", float(x.sum().reveal(to=alice).fetch()))
kv("mean(M) 密文结果", float(m.mean().reveal(to=alice).fetch()))
title("5. 非线性:sigmoid 的多项式逼近")
t_val = np.array([-4.0, -1.0, 0.0, 1.0, 4.0])
t = box.share(alice.put(t_val))
for deg in (3, 5, 7, 9):
got = box.sigmoid(t, degree=deg).reveal(to=alice).fetch()
err = np.abs(got - 1 / (1 + np.exp(-t_val))).max()
kv(f"{deg} 次逼近 最大误差", f"{err:.5f}")
title("6. 审计日志:整场计算都留痕")
summary = nax.audit().summary()
for op, cnt in sorted(summary.items(), key=lambda kv_: -kv_[1])[:8]:
kv(op, cnt)
nax.shutdown()
if __name__ == "__main__":
main()