@gmitch215/folio 1.0.0 → 1.1.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.
Files changed (71) hide show
  1. package/README.md +455 -26
  2. package/dist/affine-state.d.ts +171 -0
  3. package/dist/affine-state.js +763 -0
  4. package/dist/affine.d.ts +160 -0
  5. package/dist/affine.js +571 -0
  6. package/dist/bake.d.ts +8 -3
  7. package/dist/bake.js +5 -2
  8. package/dist/boundaries.d.ts +59 -0
  9. package/dist/boundaries.js +127 -0
  10. package/dist/certified.d.ts +66 -0
  11. package/dist/certified.js +192 -0
  12. package/dist/certify.d.ts +98 -0
  13. package/dist/certify.js +2628 -0
  14. package/dist/compiler.d.ts +37 -1
  15. package/dist/compiler.js +116 -1
  16. package/dist/context.d.ts +47 -0
  17. package/dist/context.js +139 -0
  18. package/dist/coordinator.d.ts +1 -1
  19. package/dist/coordinator.js +54 -5
  20. package/dist/extract.d.ts +114 -1
  21. package/dist/extract.js +1011 -242
  22. package/dist/fold.d.ts +32 -0
  23. package/dist/fold.js +105 -0
  24. package/dist/frames.d.ts +20 -2
  25. package/dist/frames.js +205 -10
  26. package/dist/inline.d.ts +182 -0
  27. package/dist/inline.js +766 -0
  28. package/dist/iteration-admission.d.ts +185 -0
  29. package/dist/iteration-admission.js +201 -0
  30. package/dist/iteration-layout.d.ts +135 -0
  31. package/dist/iteration-layout.js +169 -0
  32. package/dist/iteration-owner.d.ts +45 -0
  33. package/dist/iteration-owner.js +223 -0
  34. package/dist/iteration-worker.d.ts +1 -0
  35. package/dist/iteration-worker.js +216 -0
  36. package/dist/iteration.d.ts +329 -0
  37. package/dist/iteration.js +1210 -0
  38. package/dist/lease.d.ts +45 -0
  39. package/dist/lease.js +274 -0
  40. package/dist/managed.d.ts +78 -0
  41. package/dist/managed.js +448 -27
  42. package/dist/memo.d.ts +99 -0
  43. package/dist/memo.js +250 -0
  44. package/dist/node.d.ts +61 -5
  45. package/dist/node.js +421 -23
  46. package/dist/ownership-redirect.d.ts +30 -0
  47. package/dist/ownership-redirect.js +179 -0
  48. package/dist/ownership-slices.d.ts +44 -0
  49. package/dist/ownership-slices.js +72 -0
  50. package/dist/ownership.d.ts +161 -0
  51. package/dist/ownership.js +6568 -0
  52. package/dist/ranges.d.ts +78 -0
  53. package/dist/ranges.js +263 -0
  54. package/dist/read-scan.d.ts +18 -0
  55. package/dist/read-scan.js +94 -0
  56. package/dist/read-windows.d.ts +103 -0
  57. package/dist/read-windows.js +244 -0
  58. package/dist/router-worker.d.ts +1 -0
  59. package/dist/router-worker.js +4 -0
  60. package/dist/router.d.ts +203 -0
  61. package/dist/router.js +667 -0
  62. package/dist/runs.d.ts +44 -0
  63. package/dist/runs.js +182 -0
  64. package/dist/slices-worker.d.ts +1 -0
  65. package/dist/slices-worker.js +38 -0
  66. package/dist/slices.d.ts +126 -0
  67. package/dist/slices.js +441 -0
  68. package/dist/tasks.d.ts +14 -4
  69. package/dist/tasks.js +23 -9
  70. package/dist/transaction.d.ts +10 -0
  71. package/package.json +44 -4
@@ -0,0 +1,127 @@
1
+ import { bytesEqual, ContextKernel, pick, toHex } from "./affine-state.js";
2
+ const checkStep = (step) => {
3
+ if (!Number.isSafeInteger(step) || step < 1)
4
+ throw new RangeError('invalid step');
5
+ };
6
+ /**
7
+ * Runs the chain serially on a private instance in the calling thread and records the state at
8
+ * every `step` bytes. The copy at each boundary costs a few hundred bytes. The state returned is
9
+ * the one a single call over the whole input returns when the kernel composes over a split.
10
+ */
11
+ export function recordBoundaries(subject, input, options) {
12
+ checkStep(options.step);
13
+ const kernel = new ContextKernel(subject.module, subject.layout.entry);
14
+ const initial = options.initial ?? pick(subject.context, subject.state);
15
+ if (initial.length !== subject.state.length)
16
+ throw new RangeError('invalid initial state length');
17
+ const starts = [];
18
+ let state = initial;
19
+ for (let at = 0; at < input.length; at += options.step) {
20
+ starts.push(state);
21
+ const image = Uint8Array.from(subject.context);
22
+ subject.state.forEach((o, k) => (image[o] = state[k]));
23
+ const out = kernel.run(subject.layout, image, input.subarray(at, at + options.step));
24
+ if (!out)
25
+ throw new Error('the kernel trapped');
26
+ state = pick(out, subject.state);
27
+ }
28
+ return { state, log: { step: options.step, starts } };
29
+ }
30
+ /**
31
+ * Runs every chunk of `input` in parallel from the start state the log recorded for it, on workers
32
+ * started with `serveContext`, and compares each end state with the next recorded start. If all
33
+ * agree, the last end state is the serial result, by induction: each chunk ran from a state that
34
+ * the chunk before it ended in. Nothing about the bytes is trusted or hashed, so a log recorded for
35
+ * other bytes, other lengths or another chain shows up as a difference and never changes the result.
36
+ *
37
+ * At the first difference the real end state of that chunk is a real state, and the rest of the
38
+ * input runs serially from it in one task that records fresh boundaries; the recorded starts after
39
+ * that point are dropped. An edit that changes a chunk's bytes but not its end state (a chain that
40
+ * forgets) is not a difference, so the chunks after it stay valid.
41
+ */
42
+ export function verifyBoundaries(pool, subject, input, log, options = {}) {
43
+ const width = subject.state.length;
44
+ const initial = options.initial ?? pick(subject.context, subject.state);
45
+ if (initial.length !== width)
46
+ throw new RangeError('invalid initial state length');
47
+ const length = input.length;
48
+ const fresh = {
49
+ step: options.step ?? Math.max(1, Math.ceil(length / (2 * pool.width))),
50
+ starts: []
51
+ };
52
+ if (!length)
53
+ return {
54
+ state: initial,
55
+ log: fresh,
56
+ chunks: 0,
57
+ tasks: 0,
58
+ validated: 0,
59
+ mismatchAt: -1,
60
+ fallbackBytes: 0,
61
+ stale: false
62
+ };
63
+ const usable = Number.isSafeInteger(log?.step) &&
64
+ log.step > 0 &&
65
+ Array.isArray(log.starts) &&
66
+ log.starts.length > 0 &&
67
+ log.starts.every((s) => s instanceof Uint8Array && s.length === width) &&
68
+ bytesEqual(log.starts[0], initial);
69
+ const step = usable ? log.step : fresh.step;
70
+ const chunks = usable ? Math.min(log.starts.length, Math.ceil(length / step)) : 0;
71
+ let tasks = 0;
72
+ const submit = (name, from, to) => {
73
+ tasks++;
74
+ return pool.submit(name, input.slice(from, to));
75
+ };
76
+ const handles = Array.from({ length: chunks }, (_, k) => submit(`ctx:${toHex(log.starts[k])}`, k * step, Math.min((k + 1) * step, length)));
77
+ // every chunk up to `done` ran from a state that is the real state at its start
78
+ let done = -1;
79
+ let real = initial;
80
+ let mismatchAt = -1;
81
+ let validated = 0;
82
+ for (let k = 0; k < chunks; k++) {
83
+ const end = pool.join(handles[k]).bytes;
84
+ real = end;
85
+ done = k;
86
+ if (k === chunks - 1)
87
+ break;
88
+ if (!bytesEqual(end, log.starts[k + 1])) {
89
+ mismatchAt = k;
90
+ break;
91
+ }
92
+ validated++;
93
+ }
94
+ const covered = Math.min((done + 1) * step, length);
95
+ const starts = usable ? log.starts.slice(0, done + 1) : [];
96
+ let state = real;
97
+ let fallbackBytes = 0;
98
+ if (covered < length) {
99
+ fallbackBytes = length - covered;
100
+ const task = submit(`ctxrec:${toHex(real)}:${step}`, covered, length);
101
+ // the speculative chunks after a mismatch are joined last so they do not delay the tail
102
+ const rest = pool.join(task).bytes;
103
+ const pieces = rest.length / width;
104
+ starts.push(real);
105
+ for (let p = 0; p < pieces - 1; p++)
106
+ starts.push(rest.slice(p * width, (p + 1) * width));
107
+ state = rest.slice((pieces - 1) * width);
108
+ }
109
+ for (let k = done + 1; k < chunks; k++) {
110
+ try {
111
+ pool.join(handles[k]);
112
+ }
113
+ catch {
114
+ // a speculative chunk that started from a forged state may trap; it is not part of the result
115
+ }
116
+ }
117
+ return {
118
+ state,
119
+ log: { step, starts },
120
+ chunks,
121
+ tasks,
122
+ validated,
123
+ mismatchAt,
124
+ fallbackBytes,
125
+ stale: !usable
126
+ };
127
+ }
@@ -0,0 +1,66 @@
1
+ import { type AffineLayout } from './affine.ts';
2
+ import { type StreamCertificate } from './certify.ts';
3
+ import { type FoldChunk } from './fold.ts';
4
+ import { type TaskLink, type TaskPool } from './tasks.ts';
5
+ /** The task name `serveCertified` answers: `certified:<start state in hex>`. */
6
+ export declare const CERTIFIED_TASK = "certified";
7
+ /** A module that imports one shared memory, and the bytes the executor writes into that memory first. */
8
+ export interface SharedSubject {
9
+ /** The original module with its memory imported as `env.memory` and its data segments made passive. */
10
+ bytes: Uint8Array<ArrayBuffer>;
11
+ /** Data segments and the bytes the first call would write, in address order. */
12
+ prefill: {
13
+ address: number;
14
+ bytes: Uint8Array;
15
+ }[];
16
+ /** The size of the memory the module expects, in pages. */
17
+ pages: number;
18
+ certificate: StreamCertificate;
19
+ }
20
+ /**
21
+ * Rewrites a certified module to run on a memory the caller owns. Only the memory declaration and
22
+ * the data segments change: the functions stay as they were, so the certificate still describes
23
+ * them. The segments become passive so that no instance overwrites the shared bytes, and `prefill`
24
+ * carries what they held, together with the table a lazily initializing module builds on its
25
+ * first call, so every worker starts from the memory the proof assumed.
26
+ */
27
+ export declare function shareCertified(bytes: Uint8Array, certificate: StreamCertificate, pages: number): SharedSubject;
28
+ /** Writes the subject's prefill into `memory`, which must hold `pages` pages. */
29
+ export declare function installPrefill(subject: SharedSubject, memory: WebAssembly.Memory): void;
30
+ /**
31
+ * Runs on the worker side. Instantiates the shared module on the shared memory and answers
32
+ * `certified:<hex state>` tasks: the input is a view of the shared memory, which is read in place,
33
+ * and the output is the 8-byte little-endian end state.
34
+ */
35
+ export declare function serveCertified(link: TaskLink, subject: {
36
+ module: WebAssembly.Module;
37
+ memory: WebAssembly.Memory;
38
+ layout: AffineLayout;
39
+ }): void;
40
+ export interface CertifiedFoldOptions {
41
+ /** State before the first byte. The default is 0. */
42
+ initial?: bigint;
43
+ /** Explicit chunk ranges. The default splits the input into `pool.width` chunks. */
44
+ chunks?: FoldChunk[];
45
+ }
46
+ export interface CertifiedFoldResult {
47
+ state: bigint;
48
+ chunks: number;
49
+ tasks: number;
50
+ }
51
+ /**
52
+ * Folds `input`, a view of `memory`, through the certified kernel on the workers of `pool`, which
53
+ * must run `serveCertified` on that memory. Every chunk runs once from state zero, in place, and
54
+ * the model turns the end states into the state of the serial call. Nothing is compared or run
55
+ * twice: the certificate is what makes the result equal the serial one, so the input must be
56
+ * clear of the memory the proof depends on, which this checks.
57
+ */
58
+ export declare function foldCertified(pool: TaskPool, input: Uint8Array, memory: WebAssembly.Memory, certificate: StreamCertificate, options?: CertifiedFoldOptions): CertifiedFoldResult;
59
+ /**
60
+ * Runs a certified kernel that rewrites its input in place, one call per chunk on the workers of
61
+ * `pool`. Chunks may start without the ones before them, because the byte step ignores the bytes
62
+ * and the model gives the state at every chunk start, so each chunk runs once and writes its own
63
+ * bytes. A chunk that ends in a state the model did not predict means the certificate does not
64
+ * describe the kernel: the input is already rewritten, so this throws instead of returning.
65
+ */
66
+ export declare function reconstructCertified(pool: TaskPool, input: Uint8Array, memory: WebAssembly.Memory, certificate: StreamCertificate, options?: CertifiedFoldOptions): CertifiedFoldResult;
@@ -0,0 +1,192 @@
1
+ import binaryen from 'binaryen';
2
+ import { createHash } from 'node:crypto';
3
+ import { predictEnd } from "./affine.js";
4
+ import { guardInput } from "./certify.js";
5
+ import { chunkRanges } from "./fold.js";
6
+ import { serveTasks } from "./tasks.js";
7
+ /** The task name `serveCertified` answers: `certified:<start state in hex>`. */
8
+ export const CERTIFIED_TASK = 'certified';
9
+ const compactImports = binaryen.Features.CompactImports;
10
+ const PAGE = 65536;
11
+ /**
12
+ * Rewrites a certified module to run on a memory the caller owns. Only the memory declaration and
13
+ * the data segments change: the functions stay as they were, so the certificate still describes
14
+ * them. The segments become passive so that no instance overwrites the shared bytes, and `prefill`
15
+ * carries what they held, together with the table a lazily initializing module builds on its
16
+ * first call, so every worker starts from the memory the proof assumed.
17
+ */
18
+ export function shareCertified(bytes, certificate, pages) {
19
+ if (createHash('sha256').update(bytes).digest('hex') !== certificate.moduleSha256)
20
+ throw new Error('the certificate describes a different module');
21
+ const module = binaryen.readBinary(bytes);
22
+ try {
23
+ module.setFeatures(binaryen.Features.All & ~compactImports);
24
+ const memory = module.getMemoryInfo();
25
+ if (pages < memory.initial || pages > 65536)
26
+ throw new RangeError('pages out of range');
27
+ const prefill = [];
28
+ const count = module.getNumDataSegments();
29
+ for (let i = 0; i < count; i++) {
30
+ const seg = module.getDataSegmentInfo(module.getDataSegmentByIndex(i));
31
+ prefill.push({ address: seg.offset, bytes: new Uint8Array(seg.data) });
32
+ }
33
+ for (const w of certificate.initialization)
34
+ prefill.push({
35
+ address: w.address,
36
+ bytes: Uint8Array.from(w.hex.match(/../g) ?? [], (h) => parseInt(h, 16))
37
+ });
38
+ let text = module.emitText();
39
+ const declared = /\(memory (\$\S+) (\d+)(?: (\d+))?\)/.exec(text);
40
+ if (!declared)
41
+ throw new Error('the module has no plain memory declaration');
42
+ const imported = `(import "env" "memory" (memory ${declared[1]} ${declared[2]} ${pages} shared))`;
43
+ text = text
44
+ .replace(declared[0], '')
45
+ .replace(/^\(module[^\n]*\n/, (head) => `${head} ${imported}\n`);
46
+ text = text.replace(/\(data (\$\S+) \(i32\.const \d+\) /g, '(data $1 ');
47
+ const shared = binaryen.parseText(text);
48
+ try {
49
+ shared.setFeatures(binaryen.Features.All & ~compactImports);
50
+ if (!shared.validate())
51
+ throw new Error('the shared module does not validate');
52
+ return {
53
+ bytes: Uint8Array.from(shared.emitBinary()),
54
+ prefill,
55
+ pages,
56
+ certificate
57
+ };
58
+ }
59
+ finally {
60
+ shared.dispose();
61
+ }
62
+ }
63
+ finally {
64
+ module.dispose();
65
+ }
66
+ }
67
+ /** Writes the subject's prefill into `memory`, which must hold `pages` pages. */
68
+ export function installPrefill(subject, memory) {
69
+ if (memory.buffer.byteLength !== subject.pages * PAGE)
70
+ throw new RangeError('the memory is not the size the module was prepared for');
71
+ for (const part of subject.prefill)
72
+ new Uint8Array(memory.buffer, part.address, part.bytes.length).set(part.bytes);
73
+ }
74
+ /**
75
+ * Runs on the worker side. Instantiates the shared module on the shared memory and answers
76
+ * `certified:<hex state>` tasks: the input is a view of the shared memory, which is read in place,
77
+ * and the output is the 8-byte little-endian end state.
78
+ */
79
+ export function serveCertified(link, subject) {
80
+ const instance = new WebAssembly.Instance(subject.module, { env: { memory: subject.memory } });
81
+ const fn = instance.exports[subject.layout.entry];
82
+ const { layout } = subject;
83
+ serveTasks(link, (name, input) => {
84
+ const [task, hex] = name.split(':');
85
+ if (task !== CERTIFIED_TASK || !hex || typeof input === 'string')
86
+ throw new Error(`unknown task ${name}`);
87
+ const args = [0, 0, 0];
88
+ const state = BigInt(`0x${hex}`);
89
+ args[layout.state] =
90
+ layout.bits === 32 ? Number(BigInt.asIntN(32, state)) : BigInt.asIntN(64, state);
91
+ args[layout.ptr] = input.byteOffset;
92
+ args[layout.len] = input.length;
93
+ const end = BigInt.asUintN(layout.bits, BigInt(fn(...args)));
94
+ const out = new Uint8Array(8);
95
+ new DataView(out.buffer).setBigUint64(0, end, true);
96
+ return out;
97
+ });
98
+ }
99
+ /**
100
+ * Folds `input`, a view of `memory`, through the certified kernel on the workers of `pool`, which
101
+ * must run `serveCertified` on that memory. Every chunk runs once from state zero, in place, and
102
+ * the model turns the end states into the state of the serial call. Nothing is compared or run
103
+ * twice: the certificate is what makes the result equal the serial one, so the input must be
104
+ * clear of the memory the proof depends on, which this checks.
105
+ */
106
+ export function foldCertified(pool, input, memory, certificate, options = {}) {
107
+ if (certificate.output)
108
+ throw new RangeError('the kernel rewrites its input: use reconstructCertified');
109
+ const run = open(pool, input, memory, certificate, options);
110
+ if (!run.chunks)
111
+ return { state: run.whole(), chunks: 1, tasks: run.tasks() };
112
+ const handles = run.chunks.map((chunk) => run.submit(0n, chunk));
113
+ let state = run.initial;
114
+ run.chunks.forEach((chunk, i) => {
115
+ state = predictEnd(certificate.model, state, chunk.end - chunk.start, run.endOf(handles[i]));
116
+ });
117
+ return { state, chunks: run.chunks.length, tasks: run.tasks() };
118
+ }
119
+ /** Checks the input and the chunk ranges, and returns the calls that submit and join one chunk. */
120
+ function open(pool, input, memory, certificate, options) {
121
+ if (input.buffer !== memory.buffer)
122
+ throw new RangeError('the input is not a view of the memory');
123
+ if (!guardInput(certificate, memory.buffer.byteLength, input.byteOffset, input.length))
124
+ throw new RangeError('the input leaves the memory or overlaps what the certificate depends on');
125
+ const initial = BigInt.asUintN(certificate.model.bits, options.initial ?? 0n);
126
+ let tasks = 0;
127
+ const submit = (state, chunk) => {
128
+ tasks++;
129
+ return pool.submit(`${CERTIFIED_TASK}:${state.toString(16)}`, input.subarray(chunk.start, chunk.end), { share: true });
130
+ };
131
+ const endOf = (handle) => {
132
+ const part = pool.join(handle).bytes;
133
+ return new DataView(part.buffer, part.byteOffset).getBigUint64(0, true);
134
+ };
135
+ // the serial call itself, which also covers a zero length call that is not the identity
136
+ const whole = () => endOf(submit(initial, { start: 0, end: input.length }));
137
+ const base = { initial, submit, endOf, whole, tasks: () => tasks };
138
+ if (input.length === 0 || (options.chunks?.length ?? 0) === 1)
139
+ return { ...base, chunks: undefined };
140
+ const chunks = options.chunks ?? chunkRanges(input.length, pool.width, 1);
141
+ if (chunks.length === 1)
142
+ return { ...base, chunks: undefined };
143
+ let at = 0;
144
+ for (const [i, chunk] of chunks.entries()) {
145
+ if (chunk.start !== at || chunk.end <= chunk.start)
146
+ throw new RangeError(`chunk ${i} is not contiguous`);
147
+ at = chunk.end;
148
+ }
149
+ if (at !== input.length)
150
+ throw new RangeError(`chunks cover ${at} of ${input.length} bytes`);
151
+ return { ...base, chunks };
152
+ }
153
+ /**
154
+ * The state after `length` bytes from state zero, for a step that ignores its byte: the doubling
155
+ * that builds a chunk's offset needs no run of the kernel.
156
+ */
157
+ function zeroRun(certificate, length) {
158
+ const { model, output } = certificate;
159
+ let power = output.step;
160
+ let size = 1;
161
+ let result = 0n;
162
+ for (let n = length; n > 0; n = Math.floor(n / 2)) {
163
+ if (n % 2 === 1)
164
+ result = predictEnd(model, result, size, power);
165
+ power = predictEnd(model, power, size, power);
166
+ size *= 2;
167
+ }
168
+ return result;
169
+ }
170
+ /**
171
+ * Runs a certified kernel that rewrites its input in place, one call per chunk on the workers of
172
+ * `pool`. Chunks may start without the ones before them, because the byte step ignores the bytes
173
+ * and the model gives the state at every chunk start, so each chunk runs once and writes its own
174
+ * bytes. A chunk that ends in a state the model did not predict means the certificate does not
175
+ * describe the kernel: the input is already rewritten, so this throws instead of returning.
176
+ */
177
+ export function reconstructCertified(pool, input, memory, certificate, options = {}) {
178
+ if (certificate.output?.step === undefined)
179
+ throw new RangeError('the certificate does not let chunks start without the ones before them');
180
+ const run = open(pool, input, memory, certificate, options);
181
+ if (!run.chunks)
182
+ return { state: run.whole(), chunks: 1, tasks: run.tasks() };
183
+ const starts = [run.initial];
184
+ for (const chunk of run.chunks)
185
+ starts.push(predictEnd(certificate.model, starts[starts.length - 1], chunk.end - chunk.start, zeroRun(certificate, chunk.end - chunk.start)));
186
+ const handles = run.chunks.map((chunk, i) => run.submit(starts[i], chunk));
187
+ handles.forEach((handle, i) => {
188
+ if (run.endOf(handle) !== starts[i + 1])
189
+ throw new Error(`chunk ${i} ended in a state the certificate did not predict`);
190
+ });
191
+ return { state: starts[starts.length - 1], chunks: run.chunks.length, tasks: run.tasks() };
192
+ }
@@ -0,0 +1,98 @@
1
+ import type { AffineLayout, AffineModel } from './affine.ts';
2
+ /**
3
+ * `gf2` forms are bit-level affine over xor, `z2w` forms are word-level affine over add and
4
+ * multiply, and `zp` forms are exact integers over two 16-bit digits with a residue after every
5
+ * reduction, for state that holds two residues mod one constant, as Adler-32 does.
6
+ */
7
+ export type CertifiedRing = 'gf2' | 'z2w' | 'zp';
8
+ export interface CertifyOptions {
9
+ /** Parameter positions of the state, the pointer and the length. The default is 0, 1, 2. */
10
+ layout?: {
11
+ state: number;
12
+ ptr: number;
13
+ len: number;
14
+ };
15
+ /**
16
+ * Lengths below this run concretely and the rest as quotient and remainder. The default tries 4
17
+ * and then 16, because a smaller block is cheaper and a function with a larger unroll needs more.
18
+ */
19
+ block?: number;
20
+ /** Wall clock limit of the whole call, across the block ladder, in milliseconds. The default is 30000. */
21
+ maxMs?: number;
22
+ /** Restricts the analysis to one ring. The default tries `gf2`, then `z2w`, then `zp`. */
23
+ ring?: CertifiedRing;
24
+ }
25
+ export interface CertificateRange {
26
+ address: number;
27
+ length: number;
28
+ sha256: string;
29
+ }
30
+ /**
31
+ * A call over `len` bytes at `ptr` also replaces byte `i` of that range with a fixed function of
32
+ * the input byte and the fold state before it, and writes nothing else. When the byte step ignores
33
+ * the input bytes, `step` is its result from state zero, which with the model gives every state
34
+ * along the input without running the kernel, so chunks can run in place from their own start.
35
+ */
36
+ export interface CertificateOutput {
37
+ inPlace: true;
38
+ step?: bigint;
39
+ }
40
+ export interface CertificateWrite {
41
+ address: number;
42
+ hex: string;
43
+ }
44
+ /**
45
+ * A proof that `entry(state, ptr, len)` is, for every length of at least one byte, the left fold of
46
+ * one affine byte step over the input, and the model of that step. The claim holds when the module
47
+ * bytes hash to `moduleSha256`, the input range stays inside `memory` and avoids `exclusions`, and
48
+ * the memory the proof read still holds `image` once `initialization` has run.
49
+ */
50
+ export interface StreamCertificate {
51
+ kind: 'certificate';
52
+ schema: 'folio.certificate.v1';
53
+ checker: string;
54
+ moduleSha256: string;
55
+ entry: string;
56
+ ring: CertifiedRing;
57
+ bits: 32 | 64;
58
+ block: number;
59
+ layout: AffineLayout;
60
+ model: AffineModel;
61
+ /** Present when the call also rewrites its input, which `CertificateOutput` describes. */
62
+ output?: CertificateOutput;
63
+ /** What a call over zero bytes returns: the state itself, or a function of it. */
64
+ zeroLength: 'identity' | 'transforms';
65
+ /** Memory the proof read, as it must be when the call starts. */
66
+ image: CertificateRange[];
67
+ /** Bytes the first call writes before it reads them, for modules that build a table lazily. */
68
+ initialization: CertificateWrite[];
69
+ /** Byte ranges, start inclusive and end exclusive, that an input must not overlap. */
70
+ exclusions: [number, number][];
71
+ stats: {
72
+ paths: number;
73
+ loops: number;
74
+ expressions: number;
75
+ };
76
+ }
77
+ export interface CertificateRefusal {
78
+ kind: 'refusal';
79
+ reason: string;
80
+ attempts: {
81
+ ring: CertifiedRing;
82
+ reason: string;
83
+ }[];
84
+ }
85
+ export declare const CHECKER = "folio-stream-certifier-2";
86
+ /**
87
+ * Decides whether `entry(state, ptr, len)` in `bytes` is the byte fold of one affine step, for every
88
+ * length of at least one byte. The proof runs the function symbolically: lengths below `block`
89
+ * one by one, and every other length as `block * q + r` for each remainder r with `q` symbolic.
90
+ * A loop whose trip count depends on `q` is summarized by induction over its iterations. The
91
+ * checker either returns a certificate or the reason it could not prove the claim. Refusing says
92
+ * nothing about the function, and an internal failure is also a refusal.
93
+ */
94
+ export declare function certifyStream(bytes: Uint8Array, entry: string, options?: CertifyOptions): StreamCertificate | CertificateRefusal;
95
+ /** Re-derives the certificate from the module and compares everything except the work counters. */
96
+ export declare function verifyCertificate(bytes: Uint8Array, certificate: StreamCertificate): boolean;
97
+ /** Whether `[ptr, ptr + len)` lies in memory and clear of every byte the proof depends on. */
98
+ export declare function guardInput(certificate: StreamCertificate, memoryBytes: number, pointer: number, length: number): boolean;