@perpbrain/sdk 0.1.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/calibration.d.ts +31 -0
- package/dist/cjs/calibration.js +180 -0
- package/dist/cjs/clientMeta.d.ts +12 -0
- package/dist/cjs/clientMeta.js +83 -0
- package/dist/cjs/fillLink.d.ts +23 -3
- package/dist/cjs/fillLink.js +568 -12
- package/dist/cjs/fixedDecimal.d.ts +11 -0
- package/dist/cjs/fixedDecimal.js +39 -0
- package/dist/cjs/fundingRecon.js +33 -0
- package/dist/cjs/holding.d.ts +48 -0
- package/dist/cjs/holding.js +263 -0
- package/dist/cjs/index.d.ts +8 -2
- package/dist/cjs/index.js +35 -2
- package/dist/cjs/receipt.d.ts +49 -2
- package/dist/cjs/receipt.js +152 -11
- package/dist/esm/calibration.d.ts +31 -0
- package/dist/esm/calibration.js +174 -0
- package/dist/esm/clientMeta.d.ts +12 -0
- package/dist/esm/clientMeta.js +77 -0
- package/dist/esm/fillLink.d.ts +23 -3
- package/dist/esm/fillLink.js +564 -11
- package/dist/esm/fixedDecimal.d.ts +11 -0
- package/dist/esm/fixedDecimal.js +32 -0
- package/dist/esm/fundingRecon.js +33 -0
- package/dist/esm/holding.d.ts +48 -0
- package/dist/esm/holding.js +257 -0
- package/dist/esm/index.d.ts +8 -2
- package/dist/esm/index.js +5 -2
- package/dist/esm/receipt.d.ts +49 -2
- package/dist/esm/receipt.js +146 -11
- package/package.json +1 -1
package/dist/cjs/receipt.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.RECEIPT_VERSION = exports.RECEIPT_KIND = exports.RECEIPT_STATEMENT = void 0;
|
|
4
|
+
exports.InvalidLimitError = exports.MissingInputsError = exports.UnsupportedVerificationError = exports.ResourceLimitError = exports.NoVerdictError = exports.RECEIPT_VERSION = exports.RECEIPT_KIND = exports.RECEIPT_STATEMENT = void 0;
|
|
5
5
|
exports.verifyReceipt = verifyReceipt;
|
|
6
6
|
exports.canonical = canonical;
|
|
7
7
|
exports.sha256Json = sha256Json;
|
|
@@ -14,12 +14,16 @@ exports.buildReceiptFiles = buildReceiptFiles;
|
|
|
14
14
|
exports.writeReceiptDir = writeReceiptDir;
|
|
15
15
|
exports.buildReceiptDir = buildReceiptDir;
|
|
16
16
|
exports.buildGuardedReceipt = buildGuardedReceipt;
|
|
17
|
+
exports.readChunksCapped = readChunksCapped;
|
|
17
18
|
exports.verifyReceiptAt = verifyReceiptAt;
|
|
19
|
+
const clientMeta_ts_1 = require("./clientMeta.js");
|
|
18
20
|
const node_crypto_1 = require("node:crypto");
|
|
19
21
|
const node_fs_1 = require("node:fs");
|
|
20
22
|
const node_path_1 = require("node:path");
|
|
21
23
|
const guards_ts_1 = require("./guards.js");
|
|
24
|
+
const calibration_ts_1 = require("./calibration.js");
|
|
22
25
|
const fundingRecon_ts_1 = require("./fundingRecon.js");
|
|
26
|
+
const holding_ts_1 = require("./holding.js");
|
|
23
27
|
const guarded_ts_1 = require("./guarded.js");
|
|
24
28
|
const simDefaults_ts_1 = require("./vendor/simDefaults.js");
|
|
25
29
|
const study_ts_1 = require("./study.js");
|
|
@@ -134,19 +138,24 @@ function simulateInputs(inputs) {
|
|
|
134
138
|
// Receipts store the snake_case wire form; do not hash the camelCase runtime object.
|
|
135
139
|
return wireResult(runSim(inputs));
|
|
136
140
|
}
|
|
137
|
-
function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
141
|
+
function buildReceiptFiles(inputs, result, limits, marketSnapshot, clientMetadata) {
|
|
138
142
|
const inputsBytes = canonicalFileBytes(inputs);
|
|
139
143
|
const dataSnapshotId = sha256Bytes(inputsBytes);
|
|
140
144
|
const limitsHash = sha256Json(limits);
|
|
141
145
|
const marketSnapshotId = sha256Json(marketSnapshot);
|
|
142
146
|
const resultSha256 = sha256Json(result);
|
|
143
|
-
|
|
147
|
+
let manifest = {
|
|
144
148
|
data_snapshot_id: dataSnapshotId,
|
|
145
149
|
files: [{ file: "inputs.json", rows: 1, sha256: dataSnapshotId }],
|
|
146
150
|
limits_hash: limitsHash,
|
|
147
151
|
market_snapshot_id: marketSnapshotId,
|
|
148
152
|
result_sha256: resultSha256,
|
|
149
153
|
};
|
|
154
|
+
// Issue 97: an opaque hashed block in the manifest only. Undefined or empty leaves the
|
|
155
|
+
// manifest, and so the receipt, byte-identical to a build without it.
|
|
156
|
+
if (clientMetadata !== undefined && clientMetadata.length > 0) {
|
|
157
|
+
manifest = (0, clientMeta_ts_1.attachClientMeta)(manifest, clientMetadata);
|
|
158
|
+
}
|
|
150
159
|
const manifestBytes = prettyBytes(manifest);
|
|
151
160
|
const receipt = {
|
|
152
161
|
data_snapshot_id: dataSnapshotId,
|
|
@@ -164,6 +173,11 @@ function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
|
164
173
|
statement: exports.RECEIPT_STATEMENT,
|
|
165
174
|
version: exports.RECEIPT_VERSION,
|
|
166
175
|
};
|
|
176
|
+
// Mirror the Python builder: record study accounting whenever the inputs carry a study block.
|
|
177
|
+
const recordedStudy = studyFromInputs(inputs, (0, simDefaults_ts_1.simDefaults)(simDefaults_ts_1.CURRENT_SIM_DEFAULTS).numerics === "fixed18" ? "fixed18" : "float");
|
|
178
|
+
if (recordedStudy !== null) {
|
|
179
|
+
receipt.study_accounting = { ...recordedStudy };
|
|
180
|
+
}
|
|
167
181
|
return {
|
|
168
182
|
receipt,
|
|
169
183
|
manifest,
|
|
@@ -228,16 +242,118 @@ function insideDirectory(root, ref) {
|
|
|
228
242
|
return (0, node_path_1.join)(root, candidate);
|
|
229
243
|
}
|
|
230
244
|
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
231
|
-
|
|
232
|
-
|
|
245
|
+
/**
|
|
246
|
+
* Base for "no verdict reached": the check did not run to VERIFIED or MISMATCH. Thrown, never
|
|
247
|
+
* folded into a report, and says nothing about whether the record is valid.
|
|
248
|
+
*/
|
|
249
|
+
class NoVerdictError extends Error {
|
|
250
|
+
constructor(message) {
|
|
251
|
+
super(message);
|
|
252
|
+
this.name = "NoVerdictError";
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
exports.NoVerdictError = NoVerdictError;
|
|
256
|
+
/**
|
|
257
|
+
* A file is larger than the caller's explicit read limit. Thrown, never folded into a
|
|
258
|
+
* MISMATCH or VERIFIED report: "too big to check" is a resource failure, not a verdict.
|
|
259
|
+
*/
|
|
260
|
+
class ResourceLimitError extends NoVerdictError {
|
|
261
|
+
constructor(message) {
|
|
262
|
+
super(message);
|
|
263
|
+
this.name = "ResourceLimitError";
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
exports.ResourceLimitError = ResourceLimitError;
|
|
267
|
+
/** The record is of a kind this function does not check. No verdict was reached: this is neither
|
|
268
|
+
* VERIFIED nor MISMATCH, and says nothing about whether the record is valid. */
|
|
269
|
+
class UnsupportedVerificationError extends NoVerdictError {
|
|
270
|
+
constructor(message) {
|
|
271
|
+
super(message);
|
|
272
|
+
this.name = "UnsupportedVerificationError";
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
exports.UnsupportedVerificationError = UnsupportedVerificationError;
|
|
276
|
+
/** The inputs a record is checked against were not supplied (not found beside it). No verdict:
|
|
277
|
+
* a missing file is not evidence that the record is invalid. */
|
|
278
|
+
class MissingInputsError extends NoVerdictError {
|
|
279
|
+
constructor(message) {
|
|
280
|
+
super(message);
|
|
281
|
+
this.name = "MissingInputsError";
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
exports.MissingInputsError = MissingInputsError;
|
|
285
|
+
/** The caller's `maxBytes` is not a positive safe integer. A caller error, thrown before any file
|
|
286
|
+
* is read: it is neither a verdict nor a resource failure. */
|
|
287
|
+
class InvalidLimitError extends RangeError {
|
|
288
|
+
constructor(message) {
|
|
289
|
+
super(message);
|
|
290
|
+
this.name = "InvalidLimitError";
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
exports.InvalidLimitError = InvalidLimitError;
|
|
294
|
+
function assertLimit(maxBytes) {
|
|
295
|
+
if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
|
|
296
|
+
throw new InvalidLimitError(`maxBytes must be a positive safe integer, got ${String(maxBytes)}`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const READ_CHUNK = 64 * 1024;
|
|
300
|
+
/**
|
|
301
|
+
* Read chunks until end of file or one byte past ``maxBytes``. The size comes from the bytes
|
|
302
|
+
* actually read, never from a stat, so a file that grows or is replaced after any size check is
|
|
303
|
+
* still bounded, and a large limit never allocates for the limit.
|
|
304
|
+
*/
|
|
305
|
+
function readChunksCapped(read, maxBytes, name) {
|
|
306
|
+
const chunks = [];
|
|
307
|
+
let total = 0;
|
|
308
|
+
for (;;) {
|
|
309
|
+
const want = Math.min(READ_CHUNK, maxBytes + 1 - total);
|
|
310
|
+
const chunk = Buffer.alloc(want);
|
|
311
|
+
const n = read(chunk, want);
|
|
312
|
+
if (n === 0)
|
|
313
|
+
break;
|
|
314
|
+
total += n;
|
|
315
|
+
if (total > maxBytes) {
|
|
316
|
+
throw new ResourceLimitError(`${name} exceeds the ${maxBytes} byte read limit`);
|
|
317
|
+
}
|
|
318
|
+
chunks.push(n === want ? chunk : chunk.subarray(0, n));
|
|
319
|
+
}
|
|
320
|
+
return Buffer.concat(chunks, total);
|
|
321
|
+
}
|
|
322
|
+
function readCapped(path, maxBytes) {
|
|
323
|
+
if (maxBytes === undefined) {
|
|
324
|
+
return (0, node_fs_1.readFileSync)(path);
|
|
325
|
+
}
|
|
326
|
+
const fd = (0, node_fs_1.openSync)(path, "r");
|
|
327
|
+
try {
|
|
328
|
+
const name = path.split(/[\\/]/).pop() ?? path;
|
|
329
|
+
return readChunksCapped((buffer, length) => (0, node_fs_1.readSync)(fd, buffer, 0, length, null), maxBytes, name);
|
|
330
|
+
}
|
|
331
|
+
finally {
|
|
332
|
+
(0, node_fs_1.closeSync)(fd);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function verifyReceiptAt(path, options = {}) {
|
|
336
|
+
const maxBytes = options.maxBytes;
|
|
337
|
+
assertLimit(maxBytes);
|
|
338
|
+
let receiptFile = path;
|
|
339
|
+
if ((0, node_fs_1.existsSync)(path) && (0, node_fs_1.statSync)(path).isDirectory()) {
|
|
340
|
+
receiptFile = (0, node_path_1.join)(path, "receipt.json");
|
|
341
|
+
const calibrationFile = (0, node_path_1.join)(path, "calibration.json");
|
|
342
|
+
// A directory with no receipt.json but a calibration.json is a calibration report.
|
|
343
|
+
if (!(0, node_fs_1.existsSync)(receiptFile) && (0, node_fs_1.existsSync)(calibrationFile)) {
|
|
344
|
+
receiptFile = calibrationFile;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
233
347
|
if (!(0, node_fs_1.existsSync)(receiptFile) || !(0, node_fs_1.statSync)(receiptFile).isFile()) {
|
|
234
348
|
return report(["receipt.json missing"]);
|
|
235
349
|
}
|
|
236
350
|
let loaded;
|
|
237
351
|
try {
|
|
238
|
-
loaded = JSON.parse((
|
|
352
|
+
loaded = JSON.parse(readCapped(receiptFile, maxBytes).toString("utf8"));
|
|
239
353
|
}
|
|
240
|
-
catch {
|
|
354
|
+
catch (error) {
|
|
355
|
+
if (error instanceof NoVerdictError)
|
|
356
|
+
throw error;
|
|
241
357
|
return report(["receipt json mismatch"]);
|
|
242
358
|
}
|
|
243
359
|
const receipt = asObject(loaded);
|
|
@@ -251,11 +367,25 @@ function verifyReceiptAt(path) {
|
|
|
251
367
|
if (!(0, node_fs_1.existsSync)(inputsPath) || !(0, node_fs_1.statSync)(inputsPath).isFile()) {
|
|
252
368
|
return report(["inputs.json missing (download it next to receipt.json)"]);
|
|
253
369
|
}
|
|
254
|
-
return (0, fundingRecon_ts_1.verifyReconReceipt)(receipt, (
|
|
370
|
+
return (0, fundingRecon_ts_1.verifyReconReceipt)(receipt, readCapped(inputsPath, maxBytes));
|
|
371
|
+
}
|
|
372
|
+
if (receipt.kind === calibration_ts_1.CALIBRATION_KIND) {
|
|
373
|
+
// A calibration report is checked against calibration-inputs.json beside it. VERIFIED here means the
|
|
374
|
+
// report reproduces from those inputs (self-consistency); it does not authenticate the inputs or any venue.
|
|
375
|
+
const inputsPath = (0, node_path_1.join)(root, "calibration-inputs.json");
|
|
376
|
+
if (!(0, node_fs_1.existsSync)(inputsPath) || !(0, node_fs_1.statSync)(inputsPath).isFile()) {
|
|
377
|
+
throw new MissingInputsError("calibration-inputs.json missing (keep it next to calibration.json)");
|
|
378
|
+
}
|
|
379
|
+
const checked = (0, calibration_ts_1.verifyReport)(receipt, readCapped(inputsPath, maxBytes));
|
|
380
|
+
return { ...report(checked.mismatches), scope: "self-consistency-only", venue_authenticated: false };
|
|
381
|
+
}
|
|
382
|
+
if (receipt.kind === holding_ts_1.HOLDING_KIND) {
|
|
383
|
+
// A holding record needs the fills and the sim receipt it was linked to; verifyHolding takes them.
|
|
384
|
+
throw new UnsupportedVerificationError("a holding record cannot be checked by verifyReceiptAt: use verifyHolding with its fills and sim receipt");
|
|
255
385
|
}
|
|
256
386
|
const missing = [];
|
|
257
387
|
const manifestPath = (0, node_path_1.join)(root, "manifest.json");
|
|
258
|
-
const manifest = (0, node_fs_1.existsSync)(manifestPath) && (0, node_fs_1.statSync)(manifestPath).isFile() ? (
|
|
388
|
+
const manifest = (0, node_fs_1.existsSync)(manifestPath) && (0, node_fs_1.statSync)(manifestPath).isFile() ? readCapped(manifestPath, maxBytes) : null;
|
|
259
389
|
if (manifest === null) {
|
|
260
390
|
missing.push("manifest missing");
|
|
261
391
|
}
|
|
@@ -268,13 +398,15 @@ function verifyReceiptAt(path) {
|
|
|
268
398
|
try {
|
|
269
399
|
const rawPath = insideDirectory(root, rawRef);
|
|
270
400
|
if ((0, node_fs_1.existsSync)(rawPath) && (0, node_fs_1.statSync)(rawPath).isFile()) {
|
|
271
|
-
inputs = (
|
|
401
|
+
inputs = readCapped(rawPath, maxBytes);
|
|
272
402
|
}
|
|
273
403
|
else {
|
|
274
404
|
missing.push(`${rawRef} missing`);
|
|
275
405
|
}
|
|
276
406
|
}
|
|
277
|
-
catch {
|
|
407
|
+
catch (error) {
|
|
408
|
+
if (error instanceof NoVerdictError)
|
|
409
|
+
throw error;
|
|
278
410
|
missing.push("raw_ref mismatch");
|
|
279
411
|
}
|
|
280
412
|
}
|
|
@@ -356,6 +488,15 @@ function checkManifest(manifest, receipt, mismatches) {
|
|
|
356
488
|
mismatches.push(`manifest ${key} mismatch`);
|
|
357
489
|
}
|
|
358
490
|
}
|
|
491
|
+
if ("client_metadata" in manifest) {
|
|
492
|
+
try {
|
|
493
|
+
(0, clientMeta_ts_1.validateClientMeta)(manifest.client_metadata);
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
// Fixed validator messages only; never echo manifest content.
|
|
497
|
+
mismatches.push(`manifest client_metadata mismatch: ${messageOf(error)}`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
359
500
|
const files = manifest.files;
|
|
360
501
|
const rawRef = receipt.raw_ref;
|
|
361
502
|
if (!Array.isArray(files)) {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare const CALIBRATION_KIND = "perpbrain.calibration-report";
|
|
2
|
+
export declare const CALIBRATION_VERSION = 2;
|
|
3
|
+
export declare const CALIBRATION_STATEMENT = "reproducible from the supplied inputs; links are candidates, not venue-authenticated";
|
|
4
|
+
/** Proposed minimum sample gate, not statistical sufficiency. */
|
|
5
|
+
export declare const MIN_SAMPLE = 10;
|
|
6
|
+
type Row = Record<string, unknown>;
|
|
7
|
+
export interface CalibrationCandidate {
|
|
8
|
+
link_record: Row;
|
|
9
|
+
link_sha256: string;
|
|
10
|
+
sim_defaults_version?: unknown;
|
|
11
|
+
group?: string;
|
|
12
|
+
link_inputs?: unknown;
|
|
13
|
+
}
|
|
14
|
+
export interface CalibrationInputs {
|
|
15
|
+
window: unknown;
|
|
16
|
+
sim_defaults_version: unknown;
|
|
17
|
+
candidates: CalibrationCandidate[];
|
|
18
|
+
}
|
|
19
|
+
export interface BuiltReport {
|
|
20
|
+
record: Row;
|
|
21
|
+
recordBytes: Buffer;
|
|
22
|
+
inputsBytes: Buffer;
|
|
23
|
+
}
|
|
24
|
+
export interface ReportVerify {
|
|
25
|
+
status: "VERIFIED" | "MISMATCH";
|
|
26
|
+
mismatches: string[];
|
|
27
|
+
}
|
|
28
|
+
export declare function computeReport(inputs: CalibrationInputs): Row;
|
|
29
|
+
export declare function buildReport(inputs: CalibrationInputs): BuiltReport;
|
|
30
|
+
export declare function verifyReport(record: unknown, inputsBytes: Buffer): ReportVerify;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Calibration report (feedback loop), per pb-specs-28nov.md section 4.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript port of `perpbrain_read.sim.calibration` (report version 2). Read-only:
|
|
5
|
+
* aggregates candidate link records into slippage statistics for a reviewer. Nothing here
|
|
6
|
+
* proves a link is genuine. A candidate is RECOMPUTED (it carries its link_inputs and the link
|
|
7
|
+
* hash and result reproduce from them: integrity only) or UNVERIFIED (only the self-supplied
|
|
8
|
+
* hash was checked). Only RECOMPUTED candidates can meet the sample gate. Duplicates (same link
|
|
9
|
+
* hash, or the same fills under a different link) count once. Arithmetic is integer fixed point
|
|
10
|
+
* (1e18), truncating toward zero, identical to the Python side. No automatic promotion.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { canonical } from "./receipt.js";
|
|
14
|
+
import { computeLink } from "./fillLink.js";
|
|
15
|
+
import { formatFixed, parseStrictFixed, tdiv } from "./fixedDecimal.js";
|
|
16
|
+
export const CALIBRATION_KIND = "perpbrain.calibration-report";
|
|
17
|
+
export const CALIBRATION_VERSION = 2;
|
|
18
|
+
export const CALIBRATION_STATEMENT = "reproducible from the supplied inputs; links are candidates, not venue-authenticated";
|
|
19
|
+
/** Proposed minimum sample gate, not statistical sufficiency. */
|
|
20
|
+
export const MIN_SAMPLE = 10;
|
|
21
|
+
function sha256Hex(raw) {
|
|
22
|
+
return createHash("sha256").update(raw).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
function recomputed(link, cand) {
|
|
25
|
+
const linkIn = cand.link_inputs;
|
|
26
|
+
if (linkIn === null || typeof linkIn !== "object" || Array.isArray(linkIn))
|
|
27
|
+
return false;
|
|
28
|
+
try {
|
|
29
|
+
if (sha256Hex(canonical(linkIn)) !== link.inputs_sha256)
|
|
30
|
+
return false;
|
|
31
|
+
return canonical(computeLink(linkIn)) === canonical(link.result);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function fillsKey(link) {
|
|
38
|
+
const res = (link.result ?? {});
|
|
39
|
+
return canonical({ oids: res.oids ?? null, hashes: res.hashes ?? null });
|
|
40
|
+
}
|
|
41
|
+
function stats(values, basis) {
|
|
42
|
+
const vals = [...values].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
43
|
+
const n = vals.length;
|
|
44
|
+
if (n === 0)
|
|
45
|
+
return null;
|
|
46
|
+
const mid = Math.floor(n / 2);
|
|
47
|
+
const median = n % 2 ? vals[mid] : tdiv(vals[mid - 1] + vals[mid], 2n);
|
|
48
|
+
const sum = vals.reduce((a, b) => a + b, 0n);
|
|
49
|
+
return {
|
|
50
|
+
basis,
|
|
51
|
+
n,
|
|
52
|
+
mean_bps: formatFixed(tdiv(sum, BigInt(n))),
|
|
53
|
+
median_bps: formatFixed(median),
|
|
54
|
+
p90_bps: formatFixed(vals[Math.floor((9 * (n - 1)) / 10)]),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export function computeReport(inputs) {
|
|
58
|
+
const excluded = [];
|
|
59
|
+
const valid = [];
|
|
60
|
+
inputs.candidates.forEach((cand, idx) => {
|
|
61
|
+
const sha = cand.link_sha256;
|
|
62
|
+
const link = cand.link_record;
|
|
63
|
+
const drop = (reason) => excluded.push({ link_sha256: sha, reason });
|
|
64
|
+
if (link.kind !== "perpbrain.execution-link")
|
|
65
|
+
return drop("WRONG_KIND");
|
|
66
|
+
if (sha256Hex(canonical(link)) !== sha)
|
|
67
|
+
return drop("HASH_MISMATCH");
|
|
68
|
+
const res = (link.result ?? {});
|
|
69
|
+
if (res.status !== "LINKED") {
|
|
70
|
+
return drop(typeof res.status === "string" && res.status ? res.status : "NOT_LINKED");
|
|
71
|
+
}
|
|
72
|
+
if (cand.sim_defaults_version !== inputs.sim_defaults_version) {
|
|
73
|
+
return drop("DEFAULTS_VERSION_MISMATCH");
|
|
74
|
+
}
|
|
75
|
+
valid.push({ idx, cand, ok: recomputed(link, cand) });
|
|
76
|
+
});
|
|
77
|
+
// Duplicate groups keep a recomputed candidate over an unrecomputed one, then the earliest.
|
|
78
|
+
const seenHash = new Set();
|
|
79
|
+
const seenFills = new Set();
|
|
80
|
+
const kept = [];
|
|
81
|
+
const order = [...valid].sort((x, y) => Number(!x.ok) - Number(!y.ok) || x.idx - y.idx);
|
|
82
|
+
for (const v of order) {
|
|
83
|
+
const sha = v.cand.link_sha256;
|
|
84
|
+
const key = fillsKey(v.cand.link_record);
|
|
85
|
+
if (seenHash.has(sha)) {
|
|
86
|
+
excluded.push({ link_sha256: sha, reason: "DUPLICATE_LINK" });
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (seenFills.has(key)) {
|
|
90
|
+
excluded.push({ link_sha256: sha, reason: "DUPLICATE_FILLS" });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
seenHash.add(sha);
|
|
94
|
+
seenFills.add(key);
|
|
95
|
+
kept.push(v);
|
|
96
|
+
}
|
|
97
|
+
kept.sort((x, y) => x.idx - y.idx);
|
|
98
|
+
const included = kept.map((k) => k.cand);
|
|
99
|
+
const groups = new Map();
|
|
100
|
+
for (const { cand, ok } of kept) {
|
|
101
|
+
const group = String(cand.group ?? "unknown");
|
|
102
|
+
const res = cand.link_record.result;
|
|
103
|
+
const value = parseStrictFixed(res.slippage_vs_sim_bps, "slippage_vs_sim_bps");
|
|
104
|
+
const items = groups.get(group) ?? [];
|
|
105
|
+
items.push({ value, ok });
|
|
106
|
+
groups.set(group, items);
|
|
107
|
+
}
|
|
108
|
+
const outGroups = {};
|
|
109
|
+
for (const group of [...groups.keys()].sort()) {
|
|
110
|
+
const items = groups.get(group);
|
|
111
|
+
const recVals = items.filter((i) => i.ok).map((i) => i.value);
|
|
112
|
+
outGroups[group] = {
|
|
113
|
+
candidate_count: items.length,
|
|
114
|
+
recomputed_count: recVals.length,
|
|
115
|
+
unrecomputed_count: items.length - recVals.length,
|
|
116
|
+
sufficiency: recVals.length >= MIN_SAMPLE ? "MIN_SAMPLE_MET" : "INSUFFICIENT_DATA",
|
|
117
|
+
candidate_stats: stats(items.map((i) => i.value), "ALL_DEDUPED_CANDIDATES_UNVERIFIED"),
|
|
118
|
+
recomputed_stats: stats(recVals, "RECOMPUTED_ONLY"),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
window: inputs.window,
|
|
123
|
+
sim_defaults_version: inputs.sim_defaults_version,
|
|
124
|
+
included: included.map((c) => c.link_sha256),
|
|
125
|
+
excluded,
|
|
126
|
+
groups: outGroups,
|
|
127
|
+
proposal: null,
|
|
128
|
+
note: "candidate statistics for reviewer judgment; no automatic promotion",
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
export function buildReport(inputs) {
|
|
132
|
+
const raw = canonical(inputs);
|
|
133
|
+
const result = computeReport(inputs);
|
|
134
|
+
const record = {
|
|
135
|
+
kind: CALIBRATION_KIND,
|
|
136
|
+
version: CALIBRATION_VERSION,
|
|
137
|
+
statement: CALIBRATION_STATEMENT,
|
|
138
|
+
inputs_sha256: sha256Hex(raw),
|
|
139
|
+
result,
|
|
140
|
+
result_sha256: sha256Hex(canonical(result)),
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
record,
|
|
144
|
+
recordBytes: Buffer.from(canonical(record) + "\n", "utf8"),
|
|
145
|
+
inputsBytes: Buffer.from(raw + "\n", "utf8"),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
export function verifyReport(record, inputsBytes) {
|
|
149
|
+
const problems = [];
|
|
150
|
+
const body = (record ?? null);
|
|
151
|
+
if (body === null || typeof body !== "object") {
|
|
152
|
+
return { status: "MISMATCH", mismatches: ["record must be an object"] };
|
|
153
|
+
}
|
|
154
|
+
if (body.kind !== CALIBRATION_KIND)
|
|
155
|
+
problems.push("kind");
|
|
156
|
+
if (body.version !== CALIBRATION_VERSION)
|
|
157
|
+
problems.push("version");
|
|
158
|
+
let result;
|
|
159
|
+
try {
|
|
160
|
+
const inputs = JSON.parse(inputsBytes.toString("utf8"));
|
|
161
|
+
if (sha256Hex(canonical(inputs)) !== body.inputs_sha256)
|
|
162
|
+
problems.push("inputs_sha256");
|
|
163
|
+
result = computeReport(inputs);
|
|
164
|
+
}
|
|
165
|
+
catch (exc) {
|
|
166
|
+
problems.push(`inputs: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
167
|
+
return { status: "MISMATCH", mismatches: problems };
|
|
168
|
+
}
|
|
169
|
+
if (canonical(body.result) !== canonical(result))
|
|
170
|
+
problems.push("result");
|
|
171
|
+
if (body.result_sha256 !== sha256Hex(canonical(result)))
|
|
172
|
+
problems.push("result_sha256");
|
|
173
|
+
return { status: problems.length ? "MISMATCH" : "VERIFIED", mismatches: problems };
|
|
174
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare const CLIENT_META_MAX_CANONICAL_BYTES = 4096;
|
|
2
|
+
export declare const CLIENT_META_ALLOWED_KEYS: ReadonlySet<string>;
|
|
3
|
+
export interface ClientMetaEntry {
|
|
4
|
+
key: string;
|
|
5
|
+
value: string;
|
|
6
|
+
}
|
|
7
|
+
/** One opaque entry: the SHA-256 of an off-venue artifact, never the artifact. */
|
|
8
|
+
export declare function makeEntry(key: string, payload: Buffer | string): ClientMetaEntry;
|
|
9
|
+
/** Shape and size checks; the verifier ignores-but-binds the entries themselves. */
|
|
10
|
+
export declare function validateClientMeta(block: unknown): void;
|
|
11
|
+
/** Return a new manifest carrying client_metadata; the input manifest is untouched. */
|
|
12
|
+
export declare function attachClientMeta(manifest: Record<string, unknown>, entries: ClientMetaEntry[]): Record<string, unknown>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional hashed client metadata on receipt manifests (issue 97).
|
|
3
|
+
*
|
|
4
|
+
* TypeScript port of `perpbrain_read.sim.client_meta`. The block lives in the MANIFEST, not
|
|
5
|
+
* the receipt body: the receipt already pins manifest_sha256 and the shipped verifier
|
|
6
|
+
* re-hashes the manifest bytes, so a manifest block is bound end-to-end with no
|
|
7
|
+
* receipt-schema or verifier change. Keys come from a fixed allow-list (no free-text key can
|
|
8
|
+
* carry strategy detail). Values are SHA-256 hex digests only. A digest hides the artifact only
|
|
9
|
+
* if the artifact is high-entropy: a short or guessable input can be recovered by hashing
|
|
10
|
+
* guesses, so salt anything small before hashing. This is hashing, not confidentiality. Absent
|
|
11
|
+
* and null are equivalent and produce byte-identical manifests. Canonical encoding is capped
|
|
12
|
+
* at 4 KiB.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { canonical } from "./receipt.js";
|
|
16
|
+
export const CLIENT_META_MAX_CANONICAL_BYTES = 4096;
|
|
17
|
+
export const CLIENT_META_ALLOWED_KEYS = new Set([
|
|
18
|
+
"offvenue_leg_sha256",
|
|
19
|
+
"note_sha256",
|
|
20
|
+
"strategy_sha256",
|
|
21
|
+
"config_sha256",
|
|
22
|
+
"dataset_sha256",
|
|
23
|
+
"model_sha256",
|
|
24
|
+
"code_sha256",
|
|
25
|
+
]);
|
|
26
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
27
|
+
function sha256Hex(raw) {
|
|
28
|
+
return createHash("sha256").update(raw).digest("hex");
|
|
29
|
+
}
|
|
30
|
+
/** One opaque entry: the SHA-256 of an off-venue artifact, never the artifact. */
|
|
31
|
+
export function makeEntry(key, payload) {
|
|
32
|
+
if (!CLIENT_META_ALLOWED_KEYS.has(key))
|
|
33
|
+
throw new Error("key is not in the allow-list");
|
|
34
|
+
return { key, value: sha256Hex(payload) };
|
|
35
|
+
}
|
|
36
|
+
/** Shape and size checks; the verifier ignores-but-binds the entries themselves. */
|
|
37
|
+
export function validateClientMeta(block) {
|
|
38
|
+
if (block === null || typeof block !== "object") {
|
|
39
|
+
throw new Error("client_metadata version must be 1");
|
|
40
|
+
}
|
|
41
|
+
const body = block;
|
|
42
|
+
if (body.version !== 1)
|
|
43
|
+
throw new Error("client_metadata version must be 1");
|
|
44
|
+
if (Object.keys(body).sort().join(",") !== "entries,version") {
|
|
45
|
+
throw new Error("client_metadata has unknown or missing fields");
|
|
46
|
+
}
|
|
47
|
+
if (!Array.isArray(body.entries))
|
|
48
|
+
throw new Error("client_metadata.entries must be a list");
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
for (const entry of body.entries) {
|
|
51
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
|
|
52
|
+
throw new Error("entry must be an object");
|
|
53
|
+
}
|
|
54
|
+
if (Object.keys(entry).sort().join(",") !== "key,value") {
|
|
55
|
+
throw new Error("entry must have exactly key and value");
|
|
56
|
+
}
|
|
57
|
+
const { key, value } = entry;
|
|
58
|
+
if (typeof key !== "string" || !CLIENT_META_ALLOWED_KEYS.has(key)) {
|
|
59
|
+
throw new Error("key is not in the allow-list");
|
|
60
|
+
}
|
|
61
|
+
if (seen.has(key))
|
|
62
|
+
throw new Error("duplicate key");
|
|
63
|
+
seen.add(key);
|
|
64
|
+
if (typeof value !== "string" || !HEX64.test(value)) {
|
|
65
|
+
throw new Error("value must be a lowercase sha256 hex digest");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (Buffer.byteLength(canonical(block), "utf8") > CLIENT_META_MAX_CANONICAL_BYTES) {
|
|
69
|
+
throw new Error("client_metadata exceeds 4 KiB canonical");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Return a new manifest carrying client_metadata; the input manifest is untouched. */
|
|
73
|
+
export function attachClientMeta(manifest, entries) {
|
|
74
|
+
const block = { version: 1, entries: entries.map((e) => ({ ...e })) };
|
|
75
|
+
validateClientMeta(block);
|
|
76
|
+
return { ...manifest, client_metadata: block };
|
|
77
|
+
}
|
package/dist/esm/fillLink.d.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
export declare const LINK_KIND = "perpbrain.execution-link";
|
|
10
10
|
export declare const LINK_VERSION = 1;
|
|
11
|
+
export declare const LINK_VERSION_V2 = 2;
|
|
11
12
|
export type LinkSelector = "oid" | "hash" | "cloid";
|
|
12
13
|
export type LinkNetwork = "mainnet" | "testnet";
|
|
13
14
|
type Row = Record<string, unknown>;
|
|
@@ -28,6 +29,8 @@ export interface LinkInputs {
|
|
|
28
29
|
receipt_sha256: string;
|
|
29
30
|
sim: SimTrade;
|
|
30
31
|
fills: Row[];
|
|
32
|
+
policy?: unknown;
|
|
33
|
+
bounds?: unknown;
|
|
31
34
|
}
|
|
32
35
|
export interface LinkResult {
|
|
33
36
|
status: "LINKED" | "NO_FILLS" | "MISMATCHED_TRADE";
|
|
@@ -69,9 +72,26 @@ export declare function linkInputs(receipt: unknown, rows: readonly Row[], optio
|
|
|
69
72
|
by: LinkSelector;
|
|
70
73
|
value: unknown;
|
|
71
74
|
tradeIndex?: number;
|
|
75
|
+
policy?: unknown;
|
|
72
76
|
}): LinkInputs;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
77
|
+
/** v2 inputs are canonical in both SDKs only when every number is a JSON integer within the
|
|
78
|
+
* double-safe range and every object key is ASCII. Anything else is refused, never coerced. */
|
|
79
|
+
export declare function checkV2Value(value: unknown): void;
|
|
80
|
+
/** Float spellings (1.0, 1e3) parse differently across languages: refused in the raw bytes. */
|
|
81
|
+
export declare function checkV2Text(raw: string): void;
|
|
82
|
+
/** Structural facts taken from the receipt: the smallest positive bar gap and where the decision
|
|
83
|
+
* time came from ("bar", "book", or "unknown" when timed bars exist but the decision bar is not). */
|
|
84
|
+
export declare function receiptBounds(receipt: unknown): {
|
|
85
|
+
bar_interval_ms: number | null;
|
|
86
|
+
time_field: string;
|
|
87
|
+
};
|
|
88
|
+
/** v1 inputs (no `policy` key) give the v1 result unchanged and malformed rows throw, as in 0.2.1.
|
|
89
|
+
* v2 inputs add `correspondence`; malformed rows give a structured INVALID_INPUT result.
|
|
90
|
+
* `bound` is true only when the caller verified the inputs against the receipt. */
|
|
91
|
+
export declare function computeLink(inputs: LinkInputs, bound?: boolean): LinkResult & Record<string, unknown>;
|
|
92
|
+
/** Without `receipt` a v2 link is built unbound: it can never be positive. */
|
|
93
|
+
export declare function buildLink(inputs: LinkInputs, receipt?: unknown): BuiltLink;
|
|
94
|
+
/** Re-hash the inputs, rerun the comparison and, given the receipt, check the binding. A v2
|
|
95
|
+
* record that claims a receipt-bound decision time needs the receipt to verify. */
|
|
76
96
|
export declare function verifyLink(record: Record<string, unknown>, inputsBytes: Uint8Array, receipt?: unknown): LinkVerify;
|
|
77
97
|
export {};
|