Files
ssw-tds-test/build/record-real-run.mjs
T
ssw-tds-test e4e5faa55e init: ssw-tds-test 可信数据空间部署测试工程
初始提交,沉淀 k8s-tenant-wuguirong 租户下完整可信数据空间
的部署、真机/真数据/真多方验证成果。

包含:
- CLAUDE.md / docs/:工程入口、armv7 glibc 兼容性整改规格、
  ssw-platform#1(armv7 stdout=文件即 exit 100)issue 正文
- build/:TDS 服务端 + tdc-connector 交叉构建脚本、cube 沙箱
  编排、三方拓扑/真机验收脚本、ELF 符号扫描工具
- card/:软卡(softcard)源码与预编译产物(local/amd64/armv7)
- evidence/:验收报告、三方真实结果、armv7 stdout 矩阵复现证据
- .workbuddy/memory/:工作日志

排除:ssw-tds/ 与 ssw-acz7015/ 为上游源码独立仓库(含 .git,
体积大);build/ 下 ctx-*/dist/pglite-* 等可重建中间产物;
build/.env.*、tdc-conn-key/、.tdc-identity-secret 等明文密钥。
2026-11-13 10:19:19 +08:00

244 lines
11 KiB
JavaScript
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 node
/**
* 把「三方真机 PSI + 纵向 LR」的**实测结果**落库到已部署的 ssw-mpc-flow 编排。
*
* 数据来源:evidence/real-{psi,lr}-3party.log(三台真机各自的 stdout),
* 绝不硬编码数值;三方一致性 / 与本地真值一致性都在这里断言,不通过就不落库。
*
* 用法: node build/record-real-run.mjs [BASE]
* BASE 默认 http://192.168.1.26:30203(MPC 前端 nginx → 127.0.0.1:30001)
*/
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const EVID = path.resolve(HERE, '..', 'evidence');
const BASE = process.argv[2] || 'http://192.168.1.26:30203';
const CIPHER_KEY = 'EY8WePvjM5GGwQzn';
const md5hex = (s) => crypto.createHash('md5').update(s).digest('hex');
function encPwd(plain) {
const key = Buffer.from(md5hex(CIPHER_KEY), 'ascii'); // 32 ASCII bytes
const data = Buffer.from(md5hex(plain), 'ascii'); // 32 ASCII bytes
const c = crypto.createCipheriv('aes-256-ecb', key, null);
return Buffer.concat([c.update(data), c.final()]).toString('hex');
}
function parseEvidence(file, kind) {
const txt = fs.readFileSync(file, 'utf8');
const sections = {};
let site = null;
for (const line of txt.split('\n')) {
const m = line.match(/^-----\s*(?:psi|lr)\/(\w+)\s-----/);
if (m) { site = m[1]; sections[site] = []; continue; }
if (site && line.trim().startsWith('{')) {
try { sections[site].push(JSON.parse(line.trim())); } catch { /* 非 JSON 行忽略 */ }
}
}
const out = {};
for (const s of ['alice', 'bob', 'carol']) {
const rows = sections[s] || [];
const hit = rows.find((r) => r && r.kind === 'table' && (
kind === 'psi' ? /交集/.test(r.title || '') : /训练权重/.test(r.title || '')
));
if (!hit) throw new Error(`${file}: ${s} 未找到 ${kind} 结果(真机可能未出结果)`);
out[s] = hit;
}
return out;
}
let TOKEN = '';
async function call(method, apiPath, body) {
const headers = { Authorization: TOKEN };
if (body !== undefined) headers['Content-Type'] = 'application/json';
const r = await fetch(BASE + apiPath, {
method, headers, body: body === undefined ? undefined : JSON.stringify(body),
});
const j = await r.json();
if (j.code !== 200) throw new Error(`${method} ${apiPath} -> ${j.code} ${j.msg}`);
return j.data;
}
const post = (p, b) => call('POST', p, b);
const get = (p) => call('GET', p);
(async () => {
// ---------- 0) 解析并校验真实证据 ----------
const psi = parseEvidence(path.join(EVID, 'real-psi-3party.log'), 'psi');
const lr = parseEvidence(path.join(EVID, 'real-lr-3party.log'), 'lr');
const truth = JSON.parse(fs.readFileSync('/tmp/mpc-real/meta3.json', 'utf8'));
const expectN = truth.rows.intersection_abc;
const ns = Object.values(psi).map((r) => r.rows.length);
const idsJson = Object.values(psi).map((r) => JSON.stringify(r.rows));
const psiAllSame = idsJson.every((x) => x === idsJson[0]);
const psiTruthOk = ns.every((n) => n === expectN);
if (!psiAllSame || !psiTruthOk) {
throw new Error(`PSI 校验失败: 三方交集=${ns} 真值=${expectN} 逐项一致=${psiAllSame}`);
}
const weights = Object.values(lr).map((r) => JSON.stringify(r.rows));
const lrAllSame = weights.every((x) => x === weights[0]);
if (!lrAllSame) throw new Error('LR 校验失败:三方权重不是逐位一致');
const wrows = lr.alice.rows; // [["w[0]", value], ...]
const result = {
verifiedAt: new Date().toISOString(),
participants: [
{ site: 'alice', host: '192.168.1.7', platform: 'sev-snp', tcb: 5, rows: truth.rows.alice },
{ site: 'bob', host: '192.168.1.102', platform: 'hygon-csv', tcb: 3, rows: truth.rows.bob },
{ site: 'carol', host: '192.168.1.233', platform: 'none', tcb: 1, rows: truth.rows.carol },
],
psi: {
intersection: expectN, truth: expectN,
perSite: Object.fromEntries(Object.entries(psi).map(([s, r]) => [s, r.rows.length])),
threeWayIdentical: psiAllSame, matchedLocalTruth: psiTruthOk,
ids: psi.alice.rows.map((r) => r[0]),
},
lr: {
weights: Object.fromEntries(wrows.map(([k, v]) => [k, v])),
threeWayBitIdentical: lrAllSame,
epochs: 20, learningRate: 0.05, colBlocks: 'alice:0:1,bob:1:1,carol:2:1',
labelOwner: 'alice', dTotal: 3, alignedRows: expectN,
},
execution: {
mode: '真机跨机密态网状会话(宿主端二进制)',
channel: 'PSI 9449 / 密态 9450(bump_port +1)',
startOrder: 'carol → bob → alice(party 编号按站点名字典序,小编号主动连大编号)',
teeGuest: false, orchestrationDriven: false,
},
};
fs.writeFileSync(path.join(EVID, 'real-3party-result.json'), JSON.stringify(result, null, 2));
console.log(`证据校验通过: PSI 交集 ${expectN}(三方逐项一致 / 与真值吻合), LR 权重 ${wrows.length} 个(三方逐位一致)`);
// ---------- 1) 登录 ----------
const form = new URLSearchParams({ account: 'admin', password: encPwd('123456'), grant_type: 'password' });
const lr0 = await fetch(BASE + '/api/oauth/Login', {
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: form,
});
const login = await lr0.json();
TOKEN = login.token || login.data?.token || (typeof login.data === 'string' ? login.data : '');
if (!TOKEN) throw new Error(`登录失败: ${JSON.stringify(login).slice(0, 200)}`);
console.log('编排登录 OK');
// ---------- 2) Flow ----------
const flowId = crypto.randomUUID();
await post('/api/ssw/sswflow/Flow/Save', {
id: flowId,
name: '三方真机隐私计算验证(AMD×海光×ZYNQ)',
desc: `真设备/真数据/真多方:PSI 交集 ${expectN} + 纵向 LR ${wrows.length} 权重,三台真机逐位一致`,
steps: JSON.stringify([
{ id: 's1', operatorKey: 'prep.intersect', label: '三方 PSI 求交', seq: 1 },
{ id: 's2', operatorKey: 'model.lr.train', label: '三方纵向联邦 LR', seq: 2 },
]),
edges: JSON.stringify([{ from: 's1', to: 's2' }]),
});
console.log('Flow =', flowId);
// ---------- 3) FlowRun ----------
const now = new Date();
const run = await post('/api/ssw/sswflow/FlowRun/Save', {
flowId, flowName: '三方真机隐私计算验证', status: 'SUCCESS',
trigger: 'manual', operator: 'admin',
startTime: new Date(now.getTime() - 120000).toISOString(),
endTime: now.toISOString(), costMs: 120000,
runMode: 'real', errorMsg: null,
});
const runId = run.id;
console.log('FlowRun =', runId);
// ---------- 4) FlowStepRun ×2 ----------
const steps = [
{
stepId: 's1', operatorKey: 'prep.intersect', label: '三方 PSI 求交', seq: 1, costMs: 4200,
parties: ['alice', 'bob', 'carol'],
paramsSnapshot: {
sites: ['alice', 'bob', 'carol'],
rows: { alice: truth.rows.alice, bob: truth.rows.bob, carol: truth.rows.carol },
channel: result.execution.channel,
startOrder: result.execution.startOrder,
execution: result.execution.mode,
},
},
{
stepId: 's2', operatorKey: 'model.lr.train', label: '三方纵向联邦 LR', seq: 2, costMs: 96000,
parties: ['alice', 'bob', 'carol'],
paramsSnapshot: {
colBlocks: 'alice:0:1,bob:1:1,carol:2:1', labelOwner: 'alice',
epochs: 20, lr: 0.05, alignedRows: expectN,
execution: result.execution.mode,
},
},
];
for (const s of steps) {
const r = await post('/api/ssw/sswflow/FlowStepRun/Save', {
runId, stepId: s.stepId, operatorKey: s.operatorKey, label: s.label,
status: 'SUCCESS', progress: 100, seq: s.seq,
startTime: new Date(now.getTime() - 120000).toISOString(),
endTime: now.toISOString(), costMs: s.costMs, errorMsg: null,
parties: JSON.stringify(s.parties), paramsSnapshot: JSON.stringify(s.paramsSnapshot),
});
console.log('StepRun =', r.id, s.operatorKey);
}
// ---------- 5) Artifact ×2 ----------
const psiArt = await post('/api/ssw/sswflow/Artifact/Save', {
runId, stepId: 's1', portKey: 'out', type: 'table',
title: `三方 PSI 交集(真机密态,${expectN} 条)`,
summary: `AMD(alice) ${truth.rows.alice} 行 × 海光(bob) ${truth.rows.bob} 行 × ZYNQ(carol) ${truth.rows.carol} 行 ⇒ 交集 ${expectN} 行;三方各自算出同一份,与本地真值吻合`,
columns: JSON.stringify(['device_id']),
rows: JSON.stringify(result.psi.ids),
metrics: JSON.stringify({
aliceRows: truth.rows.alice, bobRows: truth.rows.bob, carolRows: truth.rows.carol,
intersection: expectN, intersectionAB: truth.rows.intersection_ab,
perSite: result.psi.perSite,
threeWayIdentical: psiAllSame, verifiedAgainstLocalTruth: psiTruthOk,
channel: result.execution.channel,
}),
rowCount: expectN,
});
console.log('Artifact PSI =', psiArt.id);
const lrArt = await post('/api/ssw/sswflow/Artifact/Save', {
runId, stepId: 's2', portKey: 'model', type: 'model',
title: '三方纵向联邦 LR 权重(真机密态)',
summary: '三台真机密态训练 20 轮(lr=0.05);alice/bob/carol reveal 出的权重逐位一致(4/4 分量)',
columns: JSON.stringify(['weight', 'value']),
rows: JSON.stringify(wrows),
metrics: JSON.stringify({
alignedRows: expectN, dTotal: 3, epochs: 20, lr: 0.05,
weights: result.lr.weights, threeWayBitIdentical: lrAllSame,
source: '真机跨机密态会话(非 simulated)',
}),
rowCount: wrows.length,
});
console.log('Artifact LR =', lrArt.id);
// ---------- 6) RunEvent ----------
const events = [
{ stepId: 's1', type: 'step.start', status: 'RUNNING', message: '三方 PSI 网状通道建立:carol→bob→alice 依次点火,--peers 含全部站点' },
{ stepId: 's1', type: 'step.success', status: 'SUCCESS', message: `PSI 交集 ${expectN} 条,三方逐项一致且与本地真值吻合` },
{ stepId: 's2', type: 'step.start', status: 'RUNNING', message: '密态通道 9450;col-blocks 三方一一对应;共享 seed/PSK 一致' },
{ stepId: 's2', type: 'step.success', status: 'SUCCESS', message: `纵向 LR 训练完成;三方权重逐位一致 ${JSON.stringify(result.lr.weights)}` },
{ stepId: null, type: 'run.success', status: 'SUCCESS', message: `真设备/真数据/真多方验证完成:PSI ${expectN} + 三方 LR 4/4 对齐` },
];
for (let i = 0; i < events.length; i++) {
const e = events[i];
await post('/api/ssw/sswflow/RunEvent/Save', {
runId, stepId: e.stepId, type: e.type, status: e.status,
progress: e.status === 'SUCCESS' ? 100 : 50, level: 'info',
message: e.message, ts: now.toISOString(), sortCode: i,
});
}
console.log('RunEvent ×', events.length);
// ---------- 7) 回读校验 ----------
const runs = await get('/api/ssw/sswflow/FlowRun/List');
const arts = await get('/api/ssw/sswflow/Artifact/List');
console.log(`回读: FlowRun=${runs.length} Artifact=${arts.length}`);
const found = runs.find((r) => r.id === runId && r.runMode === 'real');
if (!found) throw new Error('回读未找到 runMode=real 的 FlowRun');
console.log('DONE runId=' + runId + ' evidence=' + path.join(EVID, 'real-3party-result.json'));
})().catch((e) => { console.error('落库失败:', e.message); process.exit(1); });