@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.
@@ -1,9 +1,12 @@
1
1
  /** Re-derive a simulation receipt. The check is verified and reproducible. */
2
+ import { attachClientMeta, validateClientMeta } from "./clientMeta.js";
2
3
  import { createHash } from "node:crypto";
3
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
4
5
  import { dirname, join } from "node:path";
5
6
  import { GuardBlocked, GuardSession, defaultSnapshot, snapshotFromCoins, } from "./guards.js";
7
+ import { CALIBRATION_KIND, verifyReport as verifyCalibrationReport } from "./calibration.js";
6
8
  import { RECON_KIND, verifyReconReceipt } from "./fundingRecon.js";
9
+ import { HOLDING_KIND } from "./holding.js";
7
10
  import { guardedSimulate } from "./guarded.js";
8
11
  import { CURRENT_SIM_DEFAULTS, receiptProfile, simDefaults } from "./vendor/simDefaults.js";
9
12
  import { studyAccounting } from "./study.js";
@@ -118,19 +121,24 @@ export function simulateInputs(inputs) {
118
121
  // Receipts store the snake_case wire form; do not hash the camelCase runtime object.
119
122
  return wireResult(runSim(inputs));
120
123
  }
121
- export function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
124
+ export function buildReceiptFiles(inputs, result, limits, marketSnapshot, clientMetadata) {
122
125
  const inputsBytes = canonicalFileBytes(inputs);
123
126
  const dataSnapshotId = sha256Bytes(inputsBytes);
124
127
  const limitsHash = sha256Json(limits);
125
128
  const marketSnapshotId = sha256Json(marketSnapshot);
126
129
  const resultSha256 = sha256Json(result);
127
- const manifest = {
130
+ let manifest = {
128
131
  data_snapshot_id: dataSnapshotId,
129
132
  files: [{ file: "inputs.json", rows: 1, sha256: dataSnapshotId }],
130
133
  limits_hash: limitsHash,
131
134
  market_snapshot_id: marketSnapshotId,
132
135
  result_sha256: resultSha256,
133
136
  };
137
+ // Issue 97: an opaque hashed block in the manifest only. Undefined or empty leaves the
138
+ // manifest, and so the receipt, byte-identical to a build without it.
139
+ if (clientMetadata !== undefined && clientMetadata.length > 0) {
140
+ manifest = attachClientMeta(manifest, clientMetadata);
141
+ }
134
142
  const manifestBytes = prettyBytes(manifest);
135
143
  const receipt = {
136
144
  data_snapshot_id: dataSnapshotId,
@@ -148,6 +156,11 @@ export function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
148
156
  statement: RECEIPT_STATEMENT,
149
157
  version: RECEIPT_VERSION,
150
158
  };
159
+ // Mirror the Python builder: record study accounting whenever the inputs carry a study block.
160
+ const recordedStudy = studyFromInputs(inputs, simDefaults(CURRENT_SIM_DEFAULTS).numerics === "fixed18" ? "fixed18" : "float");
161
+ if (recordedStudy !== null) {
162
+ receipt.study_accounting = { ...recordedStudy };
163
+ }
151
164
  return {
152
165
  receipt,
153
166
  manifest,
@@ -212,16 +225,113 @@ function insideDirectory(root, ref) {
212
225
  return join(root, candidate);
213
226
  }
214
227
  /** Read a receipt.json file, or a directory that contains one, and check it. */
215
- export function verifyReceiptAt(path) {
216
- const receiptFile = existsSync(path) && statSync(path).isDirectory() ? join(path, "receipt.json") : path;
228
+ /**
229
+ * Base for "no verdict reached": the check did not run to VERIFIED or MISMATCH. Thrown, never
230
+ * folded into a report, and says nothing about whether the record is valid.
231
+ */
232
+ export class NoVerdictError extends Error {
233
+ constructor(message) {
234
+ super(message);
235
+ this.name = "NoVerdictError";
236
+ }
237
+ }
238
+ /**
239
+ * A file is larger than the caller's explicit read limit. Thrown, never folded into a
240
+ * MISMATCH or VERIFIED report: "too big to check" is a resource failure, not a verdict.
241
+ */
242
+ export class ResourceLimitError extends NoVerdictError {
243
+ constructor(message) {
244
+ super(message);
245
+ this.name = "ResourceLimitError";
246
+ }
247
+ }
248
+ /** The record is of a kind this function does not check. No verdict was reached: this is neither
249
+ * VERIFIED nor MISMATCH, and says nothing about whether the record is valid. */
250
+ export class UnsupportedVerificationError extends NoVerdictError {
251
+ constructor(message) {
252
+ super(message);
253
+ this.name = "UnsupportedVerificationError";
254
+ }
255
+ }
256
+ /** The inputs a record is checked against were not supplied (not found beside it). No verdict:
257
+ * a missing file is not evidence that the record is invalid. */
258
+ export class MissingInputsError extends NoVerdictError {
259
+ constructor(message) {
260
+ super(message);
261
+ this.name = "MissingInputsError";
262
+ }
263
+ }
264
+ /** The caller's `maxBytes` is not a positive safe integer. A caller error, thrown before any file
265
+ * is read: it is neither a verdict nor a resource failure. */
266
+ export class InvalidLimitError extends RangeError {
267
+ constructor(message) {
268
+ super(message);
269
+ this.name = "InvalidLimitError";
270
+ }
271
+ }
272
+ function assertLimit(maxBytes) {
273
+ if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
274
+ throw new InvalidLimitError(`maxBytes must be a positive safe integer, got ${String(maxBytes)}`);
275
+ }
276
+ }
277
+ const READ_CHUNK = 64 * 1024;
278
+ /**
279
+ * Read chunks until end of file or one byte past ``maxBytes``. The size comes from the bytes
280
+ * actually read, never from a stat, so a file that grows or is replaced after any size check is
281
+ * still bounded, and a large limit never allocates for the limit.
282
+ */
283
+ export function readChunksCapped(read, maxBytes, name) {
284
+ const chunks = [];
285
+ let total = 0;
286
+ for (;;) {
287
+ const want = Math.min(READ_CHUNK, maxBytes + 1 - total);
288
+ const chunk = Buffer.alloc(want);
289
+ const n = read(chunk, want);
290
+ if (n === 0)
291
+ break;
292
+ total += n;
293
+ if (total > maxBytes) {
294
+ throw new ResourceLimitError(`${name} exceeds the ${maxBytes} byte read limit`);
295
+ }
296
+ chunks.push(n === want ? chunk : chunk.subarray(0, n));
297
+ }
298
+ return Buffer.concat(chunks, total);
299
+ }
300
+ function readCapped(path, maxBytes) {
301
+ if (maxBytes === undefined) {
302
+ return readFileSync(path);
303
+ }
304
+ const fd = openSync(path, "r");
305
+ try {
306
+ const name = path.split(/[\\/]/).pop() ?? path;
307
+ return readChunksCapped((buffer, length) => readSync(fd, buffer, 0, length, null), maxBytes, name);
308
+ }
309
+ finally {
310
+ closeSync(fd);
311
+ }
312
+ }
313
+ export function verifyReceiptAt(path, options = {}) {
314
+ const maxBytes = options.maxBytes;
315
+ assertLimit(maxBytes);
316
+ let receiptFile = path;
317
+ if (existsSync(path) && statSync(path).isDirectory()) {
318
+ receiptFile = join(path, "receipt.json");
319
+ const calibrationFile = join(path, "calibration.json");
320
+ // A directory with no receipt.json but a calibration.json is a calibration report.
321
+ if (!existsSync(receiptFile) && existsSync(calibrationFile)) {
322
+ receiptFile = calibrationFile;
323
+ }
324
+ }
217
325
  if (!existsSync(receiptFile) || !statSync(receiptFile).isFile()) {
218
326
  return report(["receipt.json missing"]);
219
327
  }
220
328
  let loaded;
221
329
  try {
222
- loaded = JSON.parse(readFileSync(receiptFile, "utf8"));
330
+ loaded = JSON.parse(readCapped(receiptFile, maxBytes).toString("utf8"));
223
331
  }
224
- catch {
332
+ catch (error) {
333
+ if (error instanceof NoVerdictError)
334
+ throw error;
225
335
  return report(["receipt json mismatch"]);
226
336
  }
227
337
  const receipt = asObject(loaded);
@@ -235,11 +345,25 @@ export function verifyReceiptAt(path) {
235
345
  if (!existsSync(inputsPath) || !statSync(inputsPath).isFile()) {
236
346
  return report(["inputs.json missing (download it next to receipt.json)"]);
237
347
  }
238
- return verifyReconReceipt(receipt, readFileSync(inputsPath));
348
+ return verifyReconReceipt(receipt, readCapped(inputsPath, maxBytes));
349
+ }
350
+ if (receipt.kind === CALIBRATION_KIND) {
351
+ // A calibration report is checked against calibration-inputs.json beside it. VERIFIED here means the
352
+ // report reproduces from those inputs (self-consistency); it does not authenticate the inputs or any venue.
353
+ const inputsPath = join(root, "calibration-inputs.json");
354
+ if (!existsSync(inputsPath) || !statSync(inputsPath).isFile()) {
355
+ throw new MissingInputsError("calibration-inputs.json missing (keep it next to calibration.json)");
356
+ }
357
+ const checked = verifyCalibrationReport(receipt, readCapped(inputsPath, maxBytes));
358
+ return { ...report(checked.mismatches), scope: "self-consistency-only", venue_authenticated: false };
359
+ }
360
+ if (receipt.kind === HOLDING_KIND) {
361
+ // A holding record needs the fills and the sim receipt it was linked to; verifyHolding takes them.
362
+ throw new UnsupportedVerificationError("a holding record cannot be checked by verifyReceiptAt: use verifyHolding with its fills and sim receipt");
239
363
  }
240
364
  const missing = [];
241
365
  const manifestPath = join(root, "manifest.json");
242
- const manifest = existsSync(manifestPath) && statSync(manifestPath).isFile() ? readFileSync(manifestPath) : null;
366
+ const manifest = existsSync(manifestPath) && statSync(manifestPath).isFile() ? readCapped(manifestPath, maxBytes) : null;
243
367
  if (manifest === null) {
244
368
  missing.push("manifest missing");
245
369
  }
@@ -252,13 +376,15 @@ export function verifyReceiptAt(path) {
252
376
  try {
253
377
  const rawPath = insideDirectory(root, rawRef);
254
378
  if (existsSync(rawPath) && statSync(rawPath).isFile()) {
255
- inputs = readFileSync(rawPath);
379
+ inputs = readCapped(rawPath, maxBytes);
256
380
  }
257
381
  else {
258
382
  missing.push(`${rawRef} missing`);
259
383
  }
260
384
  }
261
- catch {
385
+ catch (error) {
386
+ if (error instanceof NoVerdictError)
387
+ throw error;
262
388
  missing.push("raw_ref mismatch");
263
389
  }
264
390
  }
@@ -340,6 +466,15 @@ function checkManifest(manifest, receipt, mismatches) {
340
466
  mismatches.push(`manifest ${key} mismatch`);
341
467
  }
342
468
  }
469
+ if ("client_metadata" in manifest) {
470
+ try {
471
+ validateClientMeta(manifest.client_metadata);
472
+ }
473
+ catch (error) {
474
+ // Fixed validator messages only; never echo manifest content.
475
+ mismatches.push(`manifest client_metadata mismatch: ${messageOf(error)}`);
476
+ }
477
+ }
343
478
  const files = manifest.files;
344
479
  const rawRef = receipt.raw_ref;
345
480
  if (!Array.isArray(files)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perpbrain/sdk",
3
- "version": "0.1.4",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"