-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexercise_settle_data.ts
More file actions
138 lines (121 loc) · 3.99 KB
/
exercise_settle_data.ts
File metadata and controls
138 lines (121 loc) · 3.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import { randomBytes } from "node:crypto";
import { request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
const FACILITATOR_URL = process.env.FACILITATOR_URL || "http://localhost:3003";
const SETTLE_DATA_URL = `${FACILITATOR_URL.replace(/\/$/, "")}/settle_data`;
function randomBytes32Hex(): `0x${string}` {
return `0x${randomBytes(32).toString("hex")}`;
}
function randomAddressHex(): `0x${string}` {
return `0x${randomBytes(20).toString("hex")}`;
}
function toBase64Json(value: unknown): string {
return Buffer.from(JSON.stringify(value), "utf8").toString("base64");
}
async function postJson(
urlString: string,
headers: Record<string, string>,
body: string,
): Promise<{ status: number; body: string }> {
const url = new URL(urlString);
const isHttps = url.protocol === "https:";
const requestFn = isHttps ? httpsRequest : httpRequest;
return new Promise((resolve, reject) => {
const req = requestFn(
{
protocol: url.protocol,
hostname: url.hostname,
port: url.port || (isHttps ? 443 : 80),
path: `${url.pathname}${url.search}`,
method: "POST",
headers: {
...headers,
"Content-Length": Buffer.byteLength(body).toString(),
},
},
res => {
const chunks: Buffer[] = [];
res.on("data", chunk => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
res.on("end", () => {
resolve({
status: res.statusCode ?? 0,
body: Buffer.concat(chunks).toString("utf8"),
});
});
},
);
req.on("error", reject);
req.write(body);
req.end();
});
}
async function callSettleData(args: {
settlementType: "private" | "batch" | "individual";
settlementData?: Record<string, unknown>;
}): Promise<void> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"x-settlement-type": args.settlementType,
};
if (args.settlementData) {
headers["x-settlement-data"] = toBase64Json(args.settlementData);
}
const response = await postJson(SETTLE_DATA_URL, headers, JSON.stringify({}));
const responseText = response.body;
let parsed: unknown = responseText;
try {
parsed = JSON.parse(responseText) as unknown;
} catch {
// keep raw text fallback
}
console.log("--------------------------------------------------");
console.log(`[settle_data] type=${args.settlementType} status=${response.status}`);
console.log(parsed);
}
async function run(): Promise<void> {
console.log(`[settle_data] Using facilitator: ${FACILITATOR_URL}`);
console.log("[settle_data] Sending private settlement...");
await callSettleData({
settlementType: "private",
});
console.log("[settle_data] Sending 3 batch settlement entries...");
for (let i = 1; i <= 3; i += 1) {
await callSettleData({
settlementType: "batch",
settlementData: {
inputHash: randomBytes32Hex(),
outputHash: randomBytes32Hex(),
teeSignature: `batch-tee-signature-${i}`,
},
});
}
console.log("[settle_data] Sending individual settlement...");
const nowUnixSeconds = Math.floor(Date.now() / 1000).toString();
await callSettleData({
settlementType: "individual",
settlementData: {
inputHash: randomBytes32Hex(),
outputHash: randomBytes32Hex(),
teeSignature: "individual-tee-signature",
input: {
prompt: "hello world",
requestId: `req-${Date.now()}`,
},
output: {
text: "sample model output",
score: 0.99,
},
teeId: randomBytes32Hex(),
timestamp: nowUnixSeconds,
ethAddress: randomAddressHex(),
},
});
console.log("--------------------------------------------------");
console.log("[settle_data] Done.");
console.log(
"[settle_data] Note: a batch flush happens when buffer is full or on idle timeout. Set DATA_SETTLEMENT_BATCH_BUFFER_SIZE=3 for immediate flush with this script.",
);
}
await run();