@invisi-labs/protocol 1.1.7 → 1.2.1

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 (44) hide show
  1. package/README.md +5 -0
  2. package/dist/chunk-7SS2YSEF.js +199 -0
  3. package/dist/chunk-7SS2YSEF.js.map +1 -0
  4. package/dist/{chunk-BYJ4LXCJ.js → chunk-HHJLFLVJ.js} +616 -714
  5. package/dist/chunk-HHJLFLVJ.js.map +1 -0
  6. package/dist/chunk-MVQQD5W5.js +487 -0
  7. package/dist/chunk-MVQQD5W5.js.map +1 -0
  8. package/dist/chunk-Z2XPYNMC.js +446 -0
  9. package/dist/chunk-Z2XPYNMC.js.map +1 -0
  10. package/dist/contracts.cjs +615 -713
  11. package/dist/contracts.cjs.map +1 -1
  12. package/dist/contracts.d.cts +5 -5
  13. package/dist/contracts.d.ts +5 -5
  14. package/dist/contracts.js +1 -1
  15. package/dist/credit.cjs +3367 -0
  16. package/dist/credit.cjs.map +1 -0
  17. package/dist/credit.d.cts +252 -0
  18. package/dist/credit.d.ts +252 -0
  19. package/dist/credit.js +53 -0
  20. package/dist/credit.js.map +1 -0
  21. package/dist/index.cjs +6054 -6053
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +89 -893
  24. package/dist/index.d.ts +89 -893
  25. package/dist/index.js +2956 -3762
  26. package/dist/index.js.map +1 -1
  27. package/dist/note.cjs +3456 -0
  28. package/dist/note.cjs.map +1 -0
  29. package/dist/note.d.cts +232 -0
  30. package/dist/note.d.ts +232 -0
  31. package/dist/note.js +43 -0
  32. package/dist/note.js.map +1 -0
  33. package/dist/provenance.cjs +558 -0
  34. package/dist/provenance.cjs.map +1 -0
  35. package/dist/provenance.d.cts +188 -0
  36. package/dist/provenance.d.ts +188 -0
  37. package/dist/provenance.js +499 -0
  38. package/dist/provenance.js.map +1 -0
  39. package/dist/{types-Bvakbfeb.d.cts → types-CUnFzl5S.d.cts} +530 -590
  40. package/dist/{types-Bvakbfeb.d.ts → types-CUnFzl5S.d.ts} +530 -590
  41. package/dist/validation-8g0SQVE5.d.ts +235 -0
  42. package/dist/validation-MgURYiNF.d.cts +235 -0
  43. package/package.json +20 -5
  44. package/dist/chunk-BYJ4LXCJ.js.map +0 -1
@@ -0,0 +1,499 @@
1
+ // src/provenance/index.ts
2
+ import { sha256 as sha2562 } from "@noble/hashes/sha256";
3
+ import { ed25519 as ed255192 } from "@noble/curves/ed25519";
4
+ import { AbiCoder, keccak256, getBytes as getBytes2, hexlify as hexlify2, concat as concat2 } from "ethers";
5
+ import { poseidonHash as poseidonHash2 } from "@invisi-labs/primitives";
6
+
7
+ // src/provenance/rotation.ts
8
+ import { sha256 } from "@noble/hashes/sha256";
9
+ import { ed25519 } from "@noble/curves/ed25519";
10
+ import { getBytes, hexlify, concat } from "ethers";
11
+ var bytes32 = (v) => {
12
+ if (!/^0x[0-9a-fA-F]{64}$/.test(v)) throw new Error("Rotation field must be32-byte hex");
13
+ return getBytes(v);
14
+ };
15
+ var time = (v) => {
16
+ if (!/^(0|[1-9][0-9]*)$/.test(v)) throw new Error("Rotation time must be decimal");
17
+ return uint(v, 64);
18
+ };
19
+ function rotationPayload(r) {
20
+ if (r.version !== "1") throw new Error("Unsupported rotation version");
21
+ const pub = bytes32(r.newPublicKey), id = bytes32(r.newKeyId);
22
+ if (hexlify(sha256(pub)) !== hexlify(id)) throw new Error("Rotation key ID mismatch");
23
+ return getBytes(
24
+ concat([
25
+ new Uint8Array([1]),
26
+ bytes32(r.providerId),
27
+ bytes32(r.oldKeyId),
28
+ id,
29
+ pub,
30
+ getBytes("0x" + time(r.activatedAt).toString(16).padStart(16, "0")),
31
+ bytes32(r.previousRotationHash)
32
+ ])
33
+ );
34
+ }
35
+ var rotationMessage = (r) => sha256(
36
+ getBytes(
37
+ concat([
38
+ new TextEncoder().encode("Invisi.Provenance.KeyRotation.v1"),
39
+ rotationPayload(r)
40
+ ])
41
+ )
42
+ );
43
+ var rotationHash = (r) => hexlify(sha256(rotationPayload(r)));
44
+ function verifyRotationChain(initial, records) {
45
+ const provider = hexlify(bytes32(initial.providerId)), now = time(initial.now);
46
+ let previous = hexlify(bytes32(initial.previousRotationHash)), last = time(initial.lastActivatedAt);
47
+ if (last > now) throw new Error("Rotation checkpoint is in the future");
48
+ const keys = {}, validity = {};
49
+ for (const [id, key] of Object.entries(initial.keys)) {
50
+ const canonical = hexlify(bytes32(id));
51
+ if (key.length !== 32) throw new Error("Invalid trusted signing key");
52
+ keys[canonical] = new Uint8Array(key);
53
+ validity[canonical] = { ...initial.validity?.[canonical] ?? { activatedAt: "0" } };
54
+ }
55
+ for (const r of records) {
56
+ rotationPayload(r);
57
+ const old = hexlify(bytes32(r.oldKeyId)), next = hexlify(bytes32(r.newKeyId)), at = time(r.activatedAt), oldKey = keys[old], interval = validity[old];
58
+ if (hexlify(bytes32(r.providerId)) !== provider || hexlify(bytes32(r.previousRotationHash)) !== previous || at <= last || at > now || !oldKey || !interval || interval.retiredAt !== void 0 || at < time(interval.activatedAt) || keys[next])
59
+ throw new Error("Untrusted or out-of-order key rotation");
60
+ if (!/^0x[0-9a-fA-F]{128}$/.test(r.signature) || !ed25519.verify(getBytes(r.signature), rotationMessage(r), oldKey, { zip215: false }))
61
+ throw new Error("Invalid key rotation signature");
62
+ validity[old] = { ...interval, retiredAt: r.activatedAt };
63
+ keys[next] = bytes32(r.newPublicKey);
64
+ validity[next] = { activatedAt: r.activatedAt };
65
+ previous = rotationHash(r);
66
+ last = at;
67
+ }
68
+ return {
69
+ providerId: provider,
70
+ keys,
71
+ validity,
72
+ rotationHash: previous,
73
+ lastActivatedAt: last.toString()
74
+ };
75
+ }
76
+ function withRotationHistory(trust, keyring) {
77
+ if (word(trust.providerId) !== keyring.providerId)
78
+ throw new Error("Rotation provider mismatch");
79
+ return { ...trust, signingKeys: keyring.keys, signingKeyValidity: keyring.validity };
80
+ }
81
+
82
+ // src/provenance/tracking.ts
83
+ var TrackingStaleGenerationError = class extends Error {
84
+ constructor() {
85
+ super("TRACKING_STALE_GENERATION");
86
+ }
87
+ };
88
+ function validateTracking(value, expectedId) {
89
+ if (!value || typeof value !== "object") throw Error("Missing tracking");
90
+ const t = value;
91
+ if (Object.keys(t).some(
92
+ (k) => ![
93
+ "id",
94
+ "status",
95
+ "expiresAt",
96
+ "operationDigest",
97
+ "matched",
98
+ "reasonCode",
99
+ "checkpointSequence"
100
+ ].includes(k)
101
+ ) || typeof t.id !== "string" || !/^([a-f0-9]{48})$/.test(t.id) || expectedId !== void 0 && t.id !== expectedId || typeof t.operationDigest !== "string" || word(t.operationDigest) !== t.operationDigest || typeof t.expiresAt !== "string" || !/^(0|[1-9][0-9]*)$/.test(t.expiresAt))
102
+ throw Error("Invalid tracking identity");
103
+ uint(t.expiresAt, 64);
104
+ if (![
105
+ "pending_confirmation",
106
+ "pending_source",
107
+ "recognized",
108
+ "expired",
109
+ "superseded",
110
+ "stale_generation"
111
+ ].includes(t.status))
112
+ throw Error("Unknown tracking status");
113
+ if (t.status === "stale_generation") throw new TrackingStaleGenerationError();
114
+ if (BigInt(t.expiresAt) < 1n) throw Error("Invalid tracking expiry");
115
+ if (["pending_source", "recognized"].includes(t.status) && !t.matched)
116
+ throw Error("Tracking locator required");
117
+ if (t.matched) {
118
+ const m = t.matched;
119
+ if (Object.keys(m).some((k) => !["txHash", "blockHash", "operationIndex"].includes(k)) || typeof m.txHash !== "string" || word(m.txHash) !== m.txHash || typeof m.blockHash !== "string" || word(m.blockHash) !== m.blockHash || typeof m.operationIndex !== "string" || !/^(0|[1-9][0-9]*)$/.test(m.operationIndex))
120
+ throw Error("Invalid tracking locator");
121
+ uint(m.operationIndex, 32);
122
+ }
123
+ if (t.reasonCode !== void 0 && typeof t.reasonCode !== "string")
124
+ throw Error("Invalid tracking reason");
125
+ return t;
126
+ }
127
+ function preflightTracking(result, operationIndex, operationDigest2) {
128
+ const member = Array.isArray(result.operations) ? result.operations.find(
129
+ (v) => String(v.operationIndex) === operationIndex
130
+ ) : result;
131
+ if (!member || result.broadcastDecision !== "allow" || member.broadcastDecision !== "allow" || word(String(member.operationDigest)) !== word(operationDigest2))
132
+ throw Error("Preflight candidate was not allowed");
133
+ const tracking = validateTracking(member.tracking);
134
+ if (!["pending_confirmation", "pending_source", "recognized"].includes(tracking.status))
135
+ throw Error("Tracking no longer permits broadcast");
136
+ if (tracking.operationDigest !== word(operationDigest2))
137
+ throw Error("Tracking statement mismatch");
138
+ return tracking;
139
+ }
140
+
141
+ // src/provenance/release.ts
142
+ var PROVENANCE_MANIFEST_SHA256 = "6107789c5c0d24c4130bff05da6d389336feb5ccb247c4030eae5198ab05d762";
143
+
144
+ // src/provenance/tree.ts
145
+ import { poseidonHash } from "@invisi-labs/primitives";
146
+ var hash = async (v) => BigInt(await poseidonHash(v.map(field)));
147
+ var RecognizedTree = class {
148
+ leaves = [];
149
+ get leafCount() {
150
+ return this.leaves.length;
151
+ }
152
+ append(value) {
153
+ const leaf = field(value);
154
+ if (!leaf || this.leaves.length >= 2 ** 32) throw new Error("Invalid leaf or full tree");
155
+ this.leaves.push(leaf);
156
+ return this.leaves.length - 1;
157
+ }
158
+ async appendCommitment(scope, commitment) {
159
+ return this.append(await recognizedLeaf(await scopeHash(scope), commitment));
160
+ }
161
+ async membershipForCommitment(scope, commitment) {
162
+ const leaf = await recognizedLeaf(await scopeHash(scope), commitment), index = this.leaves.indexOf(leaf);
163
+ if (index < 0) return void 0;
164
+ return { leafIndex: index, ...await this.path(index) };
165
+ }
166
+ async root() {
167
+ if (this.leaves.length) return (await this.path(0)).root;
168
+ let zero = 0n;
169
+ for (let i = 0; i < 32; i++) zero = await hash([zero, zero]);
170
+ return zero;
171
+ }
172
+ async path(index) {
173
+ if (!Number.isInteger(index) || index < 0 || index >= this.leaves.length)
174
+ throw new Error("Leaf index");
175
+ let zero = 0n, nodes = new Map(this.leaves.map((v, i) => [i, v])), cursor = index;
176
+ const path = [];
177
+ for (let l = 0; l < 32; l++) {
178
+ path.push(nodes.get(cursor % 2 === 0 ? cursor + 1 : cursor - 1) ?? zero);
179
+ const next = /* @__PURE__ */ new Map();
180
+ for (const i of nodes.keys()) {
181
+ const p = Math.floor(i / 2);
182
+ if (!next.has(p))
183
+ next.set(
184
+ p,
185
+ await hash([nodes.get(p * 2) ?? zero, nodes.get(p * 2 + 1) ?? zero])
186
+ );
187
+ }
188
+ zero = await hash([zero, zero]);
189
+ nodes = next;
190
+ cursor = Math.floor(cursor / 2);
191
+ }
192
+ return { path, root: nodes.get(0) ?? zero };
193
+ }
194
+ };
195
+
196
+ // src/provenance/index.ts
197
+ import { provenanceIntentHash } from "@invisi-labs/primitives";
198
+ var DEFAULT_PROVENANCE_ENDPOINT = "https://provenance.invisipay.fi";
199
+ var FIELD_MODULUS = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
200
+ var CAPACITIES = Object.freeze([10, 20, 40, 80, 120, 160, 190]);
201
+ var PUBLIC_INPUTS = Object.freeze([
202
+ "chain_id",
203
+ "protocol_address",
204
+ "token_address",
205
+ "chain_generation",
206
+ "source_count",
207
+ "sources_digest",
208
+ "input_count",
209
+ "operation_digest_hi",
210
+ "operation_digest_lo",
211
+ "input_digest",
212
+ "binding"
213
+ ]);
214
+ var utf8 = (s) => new TextEncoder().encode(s);
215
+ function uint(value, bits) {
216
+ if (typeof value === "number" && !Number.isSafeInteger(value))
217
+ throw new Error("Unsafe integer");
218
+ if (typeof value === "string" && !/^(0|[1-9][0-9]*|0x[0-9a-fA-F]+)$/.test(value))
219
+ throw new Error("Invalid integer encoding");
220
+ const n = BigInt(value);
221
+ if (n < 0n || n >= 1n << BigInt(bits)) throw new Error(`Integer exceeds u${bits}`);
222
+ return n;
223
+ }
224
+ function field(value) {
225
+ const n = uint(value, 256);
226
+ if (n >= FIELD_MODULUS) throw new Error("Noncanonical field");
227
+ return n;
228
+ }
229
+ var word = (value) => "0x" + uint(value, 256).toString(16).padStart(64, "0");
230
+ var DOMAINS = Object.freeze(
231
+ Object.fromEntries(
232
+ Object.entries({
233
+ SCOPE: "Scope",
234
+ NOTE: "Note",
235
+ INPUTS: "Inputs",
236
+ STEP: "Step",
237
+ SOURCES: "Sources",
238
+ SOURCE_STEP: "SourceStep",
239
+ BIND: "Bind"
240
+ }).map(([k, v]) => [
241
+ k,
242
+ BigInt(hexlify2(sha2562(utf8(`Invisi.Provenance.${v}.v1`)))) % FIELD_MODULUS
243
+ ])
244
+ )
245
+ );
246
+ var hash2 = async (values) => BigInt(await poseidonHash2(values.map(field)));
247
+ var limbs = (value) => {
248
+ const n = uint(value, 256);
249
+ return [n >> 128n, n & (1n << 128n) - 1n];
250
+ };
251
+ async function scopeHash(s) {
252
+ const protocol = uint(s.protocolAddress, 160);
253
+ if (!protocol) throw new Error("Zero protocol");
254
+ return hash2([DOMAINS.SCOPE, uint(s.chainId, 64), protocol]);
255
+ }
256
+ var recognizedLeaf = (scope, commitment) => {
257
+ if (field(commitment) === 0n) throw new Error("Zero commitment");
258
+ return hash2([DOMAINS.NOTE, scope, commitment]);
259
+ };
260
+ async function noteOpening(s) {
261
+ const owner = uint(s.owner, 160), amount = uint(s.amount, 128), chain = uint(s.chainId, 64), protocol = uint(s.protocolAddress, 160), token = uint(s.tokenAddress, 160), nonce = field(s.nonce);
262
+ if (!owner || !amount || !protocol || !token)
263
+ throw new Error("Zero note owner, protocol, token or amount");
264
+ const identity = await hash2([2n, owner, nonce]);
265
+ const commitment = await hash2([3n, chain, protocol, identity, token, amount]);
266
+ return { commitment, nullifier: await hash2([4n, chain, protocol, nonce, commitment]) };
267
+ }
268
+ async function inputDigest(nullifiers) {
269
+ let d = await hash2([DOMAINS.INPUTS, nullifiers.length]);
270
+ for (const n of nullifiers) d = await hash2([DOMAINS.STEP, d, n]);
271
+ return d;
272
+ }
273
+ async function sourcesDigest(generation, sources) {
274
+ let d = await hash2([DOMAINS.SOURCES, uint(generation, 64), sources.length]), prior = 0n;
275
+ for (const s of sources) {
276
+ const id = uint(s.treeId, 64), count = uint(s.leafCount, 64);
277
+ if (id <= prior || count < 1n || count > 2n ** 32n)
278
+ throw new Error("Invalid source order or count");
279
+ prior = id;
280
+ d = await hash2([DOMAINS.SOURCE_STEP, d, id, s.root, count]);
281
+ }
282
+ return d;
283
+ }
284
+ async function bindingDigest(s) {
285
+ return hash2([
286
+ DOMAINS.BIND,
287
+ s.scope,
288
+ (() => {
289
+ const token = uint(s.tokenAddress, 160);
290
+ if (!token) throw new Error("Zero token");
291
+ return token;
292
+ })(),
293
+ uint(s.chainGeneration, 64),
294
+ s.sourceCount,
295
+ s.sourcesDigest,
296
+ s.inputCount,
297
+ ...limbs(s.operationDigest),
298
+ s.inputDigest
299
+ ]);
300
+ }
301
+ function operationDigest(s) {
302
+ const chain = uint(s.chainId, 64), protocol = uint(s.protocolAddress, 160), capacity = Number(uint(s.mainCircuitCapacity, 32));
303
+ if (!protocol || !Number.isInteger(capacity) || capacity < 1 || capacity > 190 || s.publicInputs.length !== 17 + 3 * capacity || (s.operationKind ?? 2) !== 2)
304
+ throw new Error("Invalid authenticated transact statement");
305
+ return keccak256(
306
+ AbiCoder.defaultAbiCoder().encode(
307
+ ["string", "uint64", "address", "uint8", "uint32", "bytes32[]"],
308
+ [
309
+ "Invisi.Provenance.Operation.v1",
310
+ chain,
311
+ "0x" + protocol.toString(16).padStart(40, "0"),
312
+ 2,
313
+ capacity,
314
+ s.publicInputs.map((x) => word(field(x)))
315
+ ]
316
+ )
317
+ );
318
+ }
319
+ var CERT_LAYOUT = [
320
+ ["certificateVersion", 1],
321
+ ["providerId", 32],
322
+ ["signingKeyId", 32],
323
+ ["chainId", 8],
324
+ ["protocolAddress", 20],
325
+ ["chainGeneration", 8],
326
+ ["rootSequence", 8],
327
+ ["treeId", 8],
328
+ ["leafCount", 8],
329
+ ["root", 32],
330
+ ["confirmedBlockNumber", 8],
331
+ ["confirmedBlockHash", 32],
332
+ ["decisionLogHash", 32],
333
+ ["previousCheckpointHash", 32],
334
+ ["issuedAt", 8]
335
+ ];
336
+ function rootCertificatePayload(c) {
337
+ if (uint(c.certificateVersion, 8) !== 1n || uint(c.treeId, 64) < 1n || uint(c.leafCount, 64) > 2n ** 32n)
338
+ throw new Error("Invalid certificate version or tree");
339
+ field(c.root);
340
+ return getBytes2(
341
+ concat2(
342
+ CERT_LAYOUT.map(
343
+ ([k, w]) => "0x" + uint(c[k], w * 8).toString(16).padStart(w * 2, "0")
344
+ )
345
+ )
346
+ );
347
+ }
348
+ var checkpointHash = (c) => hexlify2(sha2562(rootCertificatePayload(c))).slice(2);
349
+ var rootCertificateMessage = (c) => sha2562(getBytes2(concat2([utf8("Invisi.Provenance.Root.v1"), rootCertificatePayload(c)])));
350
+ function verifyRootCertificate(c, key) {
351
+ if (!/^0x[0-9a-fA-F]{128}$/.test(c.signature) || key.length !== 32) return false;
352
+ try {
353
+ return ed255192.verify(getBytes2(c.signature), rootCertificateMessage(c), key, {
354
+ zip215: false
355
+ });
356
+ } catch {
357
+ return false;
358
+ }
359
+ }
360
+ function assertCertificateTrust(c, trust) {
361
+ if (Object.keys(c).some((k) => k !== "signature" && !CERT_LAYOUT.some(([name]) => name === k)))
362
+ throw Error("Unknown root certificate field");
363
+ for (const k of ["chainId", "protocolAddress", "chainGeneration", "providerId"])
364
+ if (BigInt(c[k]) !== BigInt(trust[k])) throw new Error("Certificate deployment mismatch");
365
+ const key = trust.signingKeys[word(c.signingKeyId)];
366
+ const validity = trust.signingKeyValidity?.[word(c.signingKeyId)], issuedAt = uint(c.issuedAt, 64);
367
+ if (validity && (issuedAt < BigInt(validity.activatedAt) || validity.retiredAt !== void 0 && issuedAt >= BigInt(validity.retiredAt)))
368
+ throw new Error("Certificate outside signing key validity");
369
+ if (!key || !verifyRootCertificate(c, key)) throw new Error("Untrusted certificate signature");
370
+ }
371
+ function certificateToWire(c) {
372
+ if (Object.keys(c).some((k) => k !== "signature" && !CERT_LAYOUT.some(([name]) => name === k)))
373
+ throw Error("Unknown root certificate field");
374
+ rootCertificatePayload(c);
375
+ const out = {};
376
+ for (const [key, width] of CERT_LAYOUT) {
377
+ const n = uint(c[key], width * 8);
378
+ out[key] = width === 32 || key === "protocolAddress" ? "0x" + n.toString(16).padStart(width * 2, "0") : n.toString();
379
+ }
380
+ if (!/^0x[0-9a-fA-F]{128}$/.test(c.signature))
381
+ throw new Error("Certificate signature encoding");
382
+ out.signature = c.signature.toLowerCase();
383
+ return out;
384
+ }
385
+ async function validateProofBundle(b, t) {
386
+ const keys = [
387
+ "format",
388
+ "circuitId",
389
+ "manifestSha256",
390
+ "target",
391
+ "publicInputs",
392
+ "proof",
393
+ "rootCertificates"
394
+ ];
395
+ if (Object.keys(b).some((k) => !keys.includes(k)) || b.format !== "invisi-provenance-proof-v1" || b.target !== "evm" || b.manifestSha256 !== t.manifestSha256 || !/^0x(?:[0-9a-fA-F]{2})+$/.test(b.proof) || b.proof.length > 131074)
396
+ throw new Error("Unsupported provenance proof bundle");
397
+ const match = /^provenance_k([1-9][0-9]*)$/.exec(b.circuitId), capacity = Number(match?.[1]);
398
+ if (!CAPACITIES.includes(capacity) || b.publicInputs.length !== 11)
399
+ throw new Error("Unsupported provenance circuit or ABI");
400
+ const p = b.publicInputs.map((v) => {
401
+ if (!/^0x[0-9a-fA-F]{64}$/.test(v))
402
+ throw new Error("Public inputs must be canonical words");
403
+ return field(v);
404
+ });
405
+ uint(p[7], 128);
406
+ uint(p[8], 128);
407
+ if (p[0] !== BigInt(t.chainId) || p[1] !== BigInt(t.protocolAddress) || p[3] !== BigInt(t.chainGeneration) || p[4] !== BigInt(b.rootCertificates.length) || p[6] < 1n || p[6] > BigInt(capacity) || p[4] < 1n || p[4] > p[6])
408
+ throw new Error("Proof bundle scope or shape mismatch");
409
+ const sources = b.rootCertificates.map((c) => {
410
+ if (Object.keys(c).some(
411
+ (k) => k !== "signature" && !CERT_LAYOUT.some(([name]) => name === k)
412
+ ))
413
+ throw new Error("Unknown root certificate field");
414
+ assertCertificateTrust(c, t);
415
+ return { treeId: c.treeId, root: c.root, leafCount: c.leafCount };
416
+ });
417
+ const sd = await sourcesDigest(t.chainGeneration, sources);
418
+ if (sd !== p[5]) throw new Error("Proof sources digest mismatch");
419
+ const binding = await bindingDigest({
420
+ scope: await scopeHash(t),
421
+ tokenAddress: p[2],
422
+ chainGeneration: t.chainGeneration,
423
+ sourceCount: p[4],
424
+ sourcesDigest: sd,
425
+ inputCount: p[6],
426
+ operationDigest: p[7] << 128n | p[8],
427
+ inputDigest: p[9]
428
+ });
429
+ if (binding !== p[10]) throw new Error("Proof binding mismatch");
430
+ }
431
+ function proofSidecarToWire(sidecar) {
432
+ if (Object.keys(sidecar).some((k) => !["operationIndex", "proofBundle"].includes(k)))
433
+ throw Error("Unknown proof sidecar field");
434
+ if (Object.keys(sidecar.proofBundle).some(
435
+ (k) => ![
436
+ "format",
437
+ "circuitId",
438
+ "manifestSha256",
439
+ "target",
440
+ "publicInputs",
441
+ "proof",
442
+ "rootCertificates"
443
+ ].includes(k)
444
+ ))
445
+ throw Error("Unknown proof bundle field");
446
+ const b = sidecar.proofBundle;
447
+ if (b.format !== "invisi-provenance-proof-v1" || b.target !== "evm" || !/^provenance_k[1-9][0-9]*$/.test(b.circuitId) || !/^([0-9a-f]{64})$/.test(b.manifestSha256) || b.publicInputs.length !== 11 || !/^0x(?:[0-9a-fA-F]{2})+$/.test(b.proof) || b.proof.length > 131074)
448
+ throw new Error("Invalid public proof sidecar");
449
+ return {
450
+ operationIndex: uint(sidecar.operationIndex, 32).toString(),
451
+ proofBundle: {
452
+ format: b.format,
453
+ target: b.target,
454
+ circuitId: b.circuitId,
455
+ manifestSha256: b.manifestSha256,
456
+ publicInputs: b.publicInputs.map((v) => word(field(v))),
457
+ proof: b.proof,
458
+ rootCertificates: b.rootCertificates.map(certificateToWire)
459
+ }
460
+ };
461
+ }
462
+ export {
463
+ CAPACITIES,
464
+ DEFAULT_PROVENANCE_ENDPOINT,
465
+ DOMAINS,
466
+ FIELD_MODULUS,
467
+ PROVENANCE_MANIFEST_SHA256,
468
+ PUBLIC_INPUTS,
469
+ RecognizedTree,
470
+ TrackingStaleGenerationError,
471
+ assertCertificateTrust,
472
+ bindingDigest,
473
+ certificateToWire,
474
+ checkpointHash,
475
+ field,
476
+ inputDigest,
477
+ limbs,
478
+ noteOpening,
479
+ operationDigest,
480
+ preflightTracking,
481
+ proofSidecarToWire,
482
+ provenanceIntentHash,
483
+ recognizedLeaf,
484
+ rootCertificateMessage,
485
+ rootCertificatePayload,
486
+ rotationHash,
487
+ rotationMessage,
488
+ rotationPayload,
489
+ scopeHash,
490
+ sourcesDigest,
491
+ uint,
492
+ validateProofBundle,
493
+ validateTracking,
494
+ verifyRootCertificate,
495
+ verifyRotationChain,
496
+ withRotationHistory,
497
+ word
498
+ };
499
+ //# sourceMappingURL=provenance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provenance/index.ts","../src/provenance/rotation.ts","../src/provenance/tracking.ts","../src/provenance/release.ts","../src/provenance/tree.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha256\";\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { AbiCoder, keccak256, getBytes, hexlify, concat } from \"ethers\";\nimport { poseidonHash } from \"@invisi-labs/primitives\";\nexport const DEFAULT_PROVENANCE_ENDPOINT = \"https://provenance.invisipay.fi\";\n\nexport type Integer = bigint | string | number;\nexport const FIELD_MODULUS =\n 21888242871839275222246405745257275088548364400416034343698204186575808495617n;\nexport const CAPACITIES: readonly number[] = Object.freeze([10, 20, 40, 80, 120, 160, 190]);\nexport const PUBLIC_INPUTS = Object.freeze([\n \"chain_id\",\n \"protocol_address\",\n \"token_address\",\n \"chain_generation\",\n \"source_count\",\n \"sources_digest\",\n \"input_count\",\n \"operation_digest_hi\",\n \"operation_digest_lo\",\n \"input_digest\",\n \"binding\",\n] as const);\nconst utf8 = (s: string) => new TextEncoder().encode(s);\nexport function uint(value: Integer, bits: number): bigint {\n if (typeof value === \"number\" && !Number.isSafeInteger(value))\n throw new Error(\"Unsafe integer\");\n if (typeof value === \"string\" && !/^(0|[1-9][0-9]*|0x[0-9a-fA-F]+)$/.test(value))\n throw new Error(\"Invalid integer encoding\");\n const n = BigInt(value);\n if (n < 0n || n >= 1n << BigInt(bits)) throw new Error(`Integer exceeds u${bits}`);\n return n;\n}\nexport function field(value: Integer): bigint {\n const n = uint(value, 256);\n if (n >= FIELD_MODULUS) throw new Error(\"Noncanonical field\");\n return n;\n}\nexport const word = (value: Integer): string =>\n \"0x\" + uint(value, 256).toString(16).padStart(64, \"0\");\nexport const DOMAINS = Object.freeze(\n Object.fromEntries(\n Object.entries({\n SCOPE: \"Scope\",\n NOTE: \"Note\",\n INPUTS: \"Inputs\",\n STEP: \"Step\",\n SOURCES: \"Sources\",\n SOURCE_STEP: \"SourceStep\",\n BIND: \"Bind\",\n }).map(([k, v]) => [\n k,\n BigInt(hexlify(sha256(utf8(`Invisi.Provenance.${v}.v1`)))) % FIELD_MODULUS,\n ])\n ) as Record<\"SCOPE\" | \"NOTE\" | \"INPUTS\" | \"STEP\" | \"SOURCES\" | \"SOURCE_STEP\" | \"BIND\", bigint>\n);\nconst hash = async (values: Integer[]): Promise<bigint> =>\n BigInt(await poseidonHash(values.map(field)));\nexport const limbs = (value: Integer): [bigint, bigint] => {\n const n = uint(value, 256);\n return [n >> 128n, n & ((1n << 128n) - 1n)];\n};\nexport interface Scope {\n chainId: Integer;\n protocolAddress: Integer;\n}\nexport async function scopeHash(s: Scope): Promise<bigint> {\n const protocol = uint(s.protocolAddress, 160);\n if (!protocol) throw new Error(\"Zero protocol\");\n return hash([DOMAINS.SCOPE, uint(s.chainId, 64), protocol]);\n}\nexport const recognizedLeaf = (scope: Integer, commitment: Integer): Promise<bigint> => {\n if (field(commitment) === 0n) throw new Error(\"Zero commitment\");\n return hash([DOMAINS.NOTE, scope, commitment]);\n};\nexport interface Opening {\n owner: Integer;\n nonce: Integer;\n amount: Integer;\n}\nexport async function noteOpening(\n s: Pick<Scope, \"chainId\" | \"protocolAddress\"> & Opening & { tokenAddress: Integer }\n): Promise<{ commitment: bigint; nullifier: bigint }> {\n const owner = uint(s.owner, 160),\n amount = uint(s.amount, 128),\n chain = uint(s.chainId, 64),\n protocol = uint(s.protocolAddress, 160),\n token = uint(s.tokenAddress, 160),\n nonce = field(s.nonce);\n if (!owner || !amount || !protocol || !token)\n throw new Error(\"Zero note owner, protocol, token or amount\");\n const identity = await hash([2n, owner, nonce]);\n const commitment = await hash([3n, chain, protocol, identity, token, amount]);\n return { commitment, nullifier: await hash([4n, chain, protocol, nonce, commitment]) };\n}\nexport async function inputDigest(nullifiers: readonly Integer[]): Promise<bigint> {\n let d = await hash([DOMAINS.INPUTS, nullifiers.length]);\n for (const n of nullifiers) d = await hash([DOMAINS.STEP, d, n]);\n return d;\n}\nexport interface Source {\n treeId: Integer;\n root: Integer;\n leafCount: Integer;\n}\nexport async function sourcesDigest(\n generation: Integer,\n sources: readonly Source[]\n): Promise<bigint> {\n let d = await hash([DOMAINS.SOURCES, uint(generation, 64), sources.length]),\n prior = 0n;\n for (const s of sources) {\n const id = uint(s.treeId, 64),\n count = uint(s.leafCount, 64);\n if (id <= prior || count < 1n || count > 2n ** 32n)\n throw new Error(\"Invalid source order or count\");\n prior = id;\n d = await hash([DOMAINS.SOURCE_STEP, d, id, s.root, count]);\n }\n return d;\n}\nexport async function bindingDigest(s: {\n scope: Integer;\n tokenAddress: Integer;\n chainGeneration: Integer;\n sourceCount: Integer;\n sourcesDigest: Integer;\n inputCount: Integer;\n operationDigest: Integer;\n inputDigest: Integer;\n}): Promise<bigint> {\n return hash([\n DOMAINS.BIND,\n s.scope,\n (() => {\n const token = uint(s.tokenAddress, 160);\n if (!token) throw new Error(\"Zero token\");\n return token;\n })(),\n uint(s.chainGeneration, 64),\n s.sourceCount,\n s.sourcesDigest,\n s.inputCount,\n ...limbs(s.operationDigest),\n s.inputDigest,\n ]);\n}\nexport function operationDigest(s: {\n chainId: Integer;\n protocolAddress: Integer;\n operationKind?: number;\n mainCircuitCapacity: Integer;\n publicInputs: readonly Integer[];\n}): string {\n const chain = uint(s.chainId, 64),\n protocol = uint(s.protocolAddress, 160),\n capacity = Number(uint(s.mainCircuitCapacity, 32));\n if (\n !protocol ||\n !Number.isInteger(capacity) ||\n capacity < 1 ||\n capacity > 190 ||\n s.publicInputs.length !== 17 + 3 * capacity ||\n (s.operationKind ?? 2) !== 2\n )\n throw new Error(\"Invalid authenticated transact statement\");\n return keccak256(\n AbiCoder.defaultAbiCoder().encode(\n [\"string\", \"uint64\", \"address\", \"uint8\", \"uint32\", \"bytes32[]\"],\n [\n \"Invisi.Provenance.Operation.v1\",\n chain,\n \"0x\" + protocol.toString(16).padStart(40, \"0\"),\n 2,\n capacity,\n s.publicInputs.map((x) => word(field(x))),\n ]\n )\n );\n}\nconst CERT_LAYOUT = [\n [\"certificateVersion\", 1],\n [\"providerId\", 32],\n [\"signingKeyId\", 32],\n [\"chainId\", 8],\n [\"protocolAddress\", 20],\n [\"chainGeneration\", 8],\n [\"rootSequence\", 8],\n [\"treeId\", 8],\n [\"leafCount\", 8],\n [\"root\", 32],\n [\"confirmedBlockNumber\", 8],\n [\"confirmedBlockHash\", 32],\n [\"decisionLogHash\", 32],\n [\"previousCheckpointHash\", 32],\n [\"issuedAt\", 8],\n] as const;\nexport type RootCertificate = Record<(typeof CERT_LAYOUT)[number][0], Integer> & {\n signature: string;\n};\nexport function rootCertificatePayload(c: Omit<RootCertificate, \"signature\">): Uint8Array {\n if (\n uint(c.certificateVersion, 8) !== 1n ||\n uint(c.treeId, 64) < 1n ||\n uint(c.leafCount, 64) > 2n ** 32n\n )\n throw new Error(\"Invalid certificate version or tree\");\n field(c.root);\n return getBytes(\n concat(\n CERT_LAYOUT.map(\n ([k, w]) =>\n \"0x\" +\n uint(c[k], w * 8)\n .toString(16)\n .padStart(w * 2, \"0\")\n )\n )\n );\n}\nexport const checkpointHash = (c: Omit<RootCertificate, \"signature\">): string =>\n hexlify(sha256(rootCertificatePayload(c))).slice(2);\nexport const rootCertificateMessage = (c: Omit<RootCertificate, \"signature\">): Uint8Array =>\n sha256(getBytes(concat([utf8(\"Invisi.Provenance.Root.v1\"), rootCertificatePayload(c)])));\nexport function verifyRootCertificate(c: RootCertificate, key: Uint8Array): boolean {\n if (!/^0x[0-9a-fA-F]{128}$/.test(c.signature) || key.length !== 32) return false;\n try {\n return ed25519.verify(getBytes(c.signature), rootCertificateMessage(c), key, {\n zip215: false,\n });\n } catch {\n return false;\n }\n}\nexport interface ProofBundle {\n format: \"invisi-provenance-proof-v1\";\n circuitId: string;\n manifestSha256: string;\n target: \"evm\";\n publicInputs: string[];\n proof: string;\n rootCertificates: RootCertificate[];\n}\nexport interface ProofSidecar {\n operationIndex: string;\n proofBundle: ProofBundle;\n}\nexport interface TrustedManifest {\n noirVersion: string;\n bbVersion: string;\n depth: number;\n family: \"provenance\";\n target: \"evm\";\n publicInputs: readonly string[];\n circuits: readonly {\n capacity: number;\n name?: string;\n artifactSha256: string;\n vkSha256: string;\n }[];\n}\nexport interface ManifestIdentity {\n manifest: TrustedManifest;\n sha256: string;\n}\nexport interface TrustContext extends Scope {\n chainGeneration: Integer;\n providerId: Integer;\n signingKeys: Readonly<Record<string, Uint8Array>>;\n manifestSha256: string;\n signingKeyValidity?: Readonly<Record<string, { activatedAt: string; retiredAt?: string }>>;\n}\nexport function assertCertificateTrust(c: RootCertificate, trust: TrustContext): void {\n if (Object.keys(c).some((k) => k !== \"signature\" && !CERT_LAYOUT.some(([name]) => name === k)))\n throw Error(\"Unknown root certificate field\");\n for (const k of [\"chainId\", \"protocolAddress\", \"chainGeneration\", \"providerId\"] as const)\n if (BigInt(c[k]) !== BigInt(trust[k])) throw new Error(\"Certificate deployment mismatch\");\n const key = trust.signingKeys[word(c.signingKeyId)];\n const validity = trust.signingKeyValidity?.[word(c.signingKeyId)],\n issuedAt = uint(c.issuedAt, 64);\n if (\n validity &&\n (issuedAt < BigInt(validity.activatedAt) ||\n (validity.retiredAt !== undefined && issuedAt >= BigInt(validity.retiredAt)))\n )\n throw new Error(\"Certificate outside signing key validity\");\n if (!key || !verifyRootCertificate(c, key)) throw new Error(\"Untrusted certificate signature\");\n}\nexport type PublicResult = Record<string, unknown> & { scope: Scope };\nexport function certificateToWire(c: RootCertificate): RootCertificate {\n if (Object.keys(c).some((k) => k !== \"signature\" && !CERT_LAYOUT.some(([name]) => name === k)))\n throw Error(\"Unknown root certificate field\");\n rootCertificatePayload(c);\n const out = {} as RootCertificate;\n for (const [key, width] of CERT_LAYOUT) {\n const n = uint(c[key], width * 8);\n out[key] =\n width === 32 || key === \"protocolAddress\"\n ? \"0x\" + n.toString(16).padStart(width * 2, \"0\")\n : n.toString();\n }\n if (!/^0x[0-9a-fA-F]{128}$/.test(c.signature))\n throw new Error(\"Certificate signature encoding\");\n out.signature = c.signature.toLowerCase();\n return out;\n}\n\nexport async function validateProofBundle(b: ProofBundle, t: TrustContext): Promise<void> {\n const keys = [\n \"format\",\n \"circuitId\",\n \"manifestSha256\",\n \"target\",\n \"publicInputs\",\n \"proof\",\n \"rootCertificates\",\n ];\n if (\n Object.keys(b).some((k) => !keys.includes(k)) ||\n b.format !== \"invisi-provenance-proof-v1\" ||\n b.target !== \"evm\" ||\n b.manifestSha256 !== t.manifestSha256 ||\n !/^0x(?:[0-9a-fA-F]{2})+$/.test(b.proof) ||\n b.proof.length > 131074\n )\n throw new Error(\"Unsupported provenance proof bundle\");\n const match = /^provenance_k([1-9][0-9]*)$/.exec(b.circuitId),\n capacity = Number(match?.[1]);\n if (!CAPACITIES.includes(capacity) || b.publicInputs.length !== 11)\n throw new Error(\"Unsupported provenance circuit or ABI\");\n const p = b.publicInputs.map((v) => {\n if (!/^0x[0-9a-fA-F]{64}$/.test(v))\n throw new Error(\"Public inputs must be canonical words\");\n return field(v);\n });\n uint(p[7]!, 128);\n uint(p[8]!, 128);\n if (\n p[0] !== BigInt(t.chainId) ||\n p[1] !== BigInt(t.protocolAddress) ||\n p[3] !== BigInt(t.chainGeneration) ||\n p[4] !== BigInt(b.rootCertificates.length) ||\n p[6]! < 1n ||\n p[6]! > BigInt(capacity) ||\n p[4]! < 1n ||\n p[4]! > p[6]!\n )\n throw new Error(\"Proof bundle scope or shape mismatch\");\n const sources = b.rootCertificates.map((c) => {\n if (\n Object.keys(c).some(\n (k) => k !== \"signature\" && !CERT_LAYOUT.some(([name]) => name === k)\n )\n )\n throw new Error(\"Unknown root certificate field\");\n assertCertificateTrust(c, t);\n return { treeId: c.treeId, root: c.root, leafCount: c.leafCount };\n });\n const sd = await sourcesDigest(t.chainGeneration, sources);\n if (sd !== p[5]) throw new Error(\"Proof sources digest mismatch\");\n const binding = await bindingDigest({\n scope: await scopeHash(t),\n tokenAddress: p[2]!,\n chainGeneration: t.chainGeneration,\n sourceCount: p[4]!,\n sourcesDigest: sd,\n inputCount: p[6]!,\n operationDigest: (p[7]! << 128n) | p[8]!,\n inputDigest: p[9]!,\n });\n if (binding !== p[10]) throw new Error(\"Proof binding mismatch\");\n}\n\nexport function proofSidecarToWire(sidecar: ProofSidecar): ProofSidecar {\n if (Object.keys(sidecar).some((k) => ![\"operationIndex\", \"proofBundle\"].includes(k)))\n throw Error(\"Unknown proof sidecar field\");\n if (\n Object.keys(sidecar.proofBundle).some(\n (k) =>\n ![\n \"format\",\n \"circuitId\",\n \"manifestSha256\",\n \"target\",\n \"publicInputs\",\n \"proof\",\n \"rootCertificates\",\n ].includes(k)\n )\n )\n throw Error(\"Unknown proof bundle field\");\n const b = sidecar.proofBundle;\n if (\n b.format !== \"invisi-provenance-proof-v1\" ||\n b.target !== \"evm\" ||\n !/^provenance_k[1-9][0-9]*$/.test(b.circuitId) ||\n !/^([0-9a-f]{64})$/.test(b.manifestSha256) ||\n b.publicInputs.length !== 11 ||\n !/^0x(?:[0-9a-fA-F]{2})+$/.test(b.proof) ||\n b.proof.length > 131074\n )\n throw new Error(\"Invalid public proof sidecar\");\n return {\n operationIndex: uint(sidecar.operationIndex, 32).toString(),\n proofBundle: {\n format: b.format,\n target: b.target,\n circuitId: b.circuitId,\n manifestSha256: b.manifestSha256,\n publicInputs: b.publicInputs.map((v) => word(field(v))),\n proof: b.proof,\n rootCertificates: b.rootCertificates.map(certificateToWire),\n },\n };\n}\n\nexport * from \"./rotation\";\nexport * from \"./tracking\";\nexport * from \"./release\";\nexport * from \"./tree\";\nexport { provenanceIntentHash } from \"@invisi-labs/primitives\";\n","import { sha256 } from \"@noble/hashes/sha256\";\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { getBytes, hexlify, concat } from \"ethers\";\nimport { uint, word } from \"./index\";\nimport type { TrustContext } from \"./index\";\nexport interface RotationRecord {\n version: \"1\";\n providerId: string;\n oldKeyId: string;\n newKeyId: string;\n newPublicKey: string;\n activatedAt: string;\n previousRotationHash: string;\n signature: string;\n}\nexport interface KeyValidity {\n activatedAt: string;\n retiredAt?: string;\n}\nexport interface TrustedKeyring {\n providerId: string;\n keys: Record<string, Uint8Array>;\n validity: Record<string, KeyValidity>;\n rotationHash: string;\n lastActivatedAt: string;\n}\nconst bytes32 = (v: string): Uint8Array => {\n if (!/^0x[0-9a-fA-F]{64}$/.test(v)) throw new Error(\"Rotation field must be32-byte hex\");\n return getBytes(v);\n};\nconst time = (v: string): bigint => {\n if (!/^(0|[1-9][0-9]*)$/.test(v)) throw new Error(\"Rotation time must be decimal\");\n return uint(v, 64);\n};\nexport function rotationPayload(r: RotationRecord): Uint8Array {\n if (r.version !== \"1\") throw new Error(\"Unsupported rotation version\");\n const pub = bytes32(r.newPublicKey),\n id = bytes32(r.newKeyId);\n if (hexlify(sha256(pub)) !== hexlify(id)) throw new Error(\"Rotation key ID mismatch\");\n return getBytes(\n concat([\n new Uint8Array([1]),\n bytes32(r.providerId),\n bytes32(r.oldKeyId),\n id,\n pub,\n getBytes(\"0x\" + time(r.activatedAt).toString(16).padStart(16, \"0\")),\n bytes32(r.previousRotationHash),\n ])\n );\n}\nexport const rotationMessage = (r: RotationRecord): Uint8Array =>\n sha256(\n getBytes(\n concat([\n new TextEncoder().encode(\"Invisi.Provenance.KeyRotation.v1\"),\n rotationPayload(r),\n ])\n )\n );\nexport const rotationHash = (r: RotationRecord): string => hexlify(sha256(rotationPayload(r)));\nexport function verifyRotationChain(\n initial: {\n providerId: string;\n keys: Readonly<Record<string, Uint8Array>>;\n previousRotationHash: string;\n lastActivatedAt: string;\n now: string;\n validity?: Readonly<Record<string, KeyValidity>>;\n },\n records: readonly RotationRecord[]\n): TrustedKeyring {\n const provider = hexlify(bytes32(initial.providerId)),\n now = time(initial.now);\n let previous = hexlify(bytes32(initial.previousRotationHash)),\n last = time(initial.lastActivatedAt);\n if (last > now) throw new Error(\"Rotation checkpoint is in the future\");\n const keys: Record<string, Uint8Array> = {},\n validity: Record<string, KeyValidity> = {};\n for (const [id, key] of Object.entries(initial.keys)) {\n const canonical = hexlify(bytes32(id));\n if (key.length !== 32) throw new Error(\"Invalid trusted signing key\");\n keys[canonical] = new Uint8Array(key);\n validity[canonical] = { ...(initial.validity?.[canonical] ?? { activatedAt: \"0\" }) };\n }\n for (const r of records) {\n rotationPayload(r);\n const old = hexlify(bytes32(r.oldKeyId)),\n next = hexlify(bytes32(r.newKeyId)),\n at = time(r.activatedAt),\n oldKey = keys[old],\n interval = validity[old];\n if (\n hexlify(bytes32(r.providerId)) !== provider ||\n hexlify(bytes32(r.previousRotationHash)) !== previous ||\n at <= last ||\n at > now ||\n !oldKey ||\n !interval ||\n interval.retiredAt !== undefined ||\n at < time(interval.activatedAt) ||\n keys[next]\n )\n throw new Error(\"Untrusted or out-of-order key rotation\");\n if (\n !/^0x[0-9a-fA-F]{128}$/.test(r.signature) ||\n !ed25519.verify(getBytes(r.signature), rotationMessage(r), oldKey, { zip215: false })\n )\n throw new Error(\"Invalid key rotation signature\");\n validity[old] = { ...interval, retiredAt: r.activatedAt };\n keys[next] = bytes32(r.newPublicKey);\n validity[next] = { activatedAt: r.activatedAt };\n previous = rotationHash(r);\n last = at;\n }\n return {\n providerId: provider,\n keys,\n validity,\n rotationHash: previous,\n lastActivatedAt: last.toString(),\n };\n}\nexport function withRotationHistory(trust: TrustContext, keyring: TrustedKeyring): TrustContext {\n if (word(trust.providerId) !== keyring.providerId)\n throw new Error(\"Rotation provider mismatch\");\n return { ...trust, signingKeys: keyring.keys, signingKeyValidity: keyring.validity };\n}\n","import { word, uint, type PublicResult } from \"./index\";\nexport type TrackingStatus =\n | \"pending_confirmation\"\n | \"pending_source\"\n | \"recognized\"\n | \"expired\"\n | \"superseded\"\n | \"stale_generation\";\nexport interface Tracking {\n id: string;\n status: TrackingStatus;\n expiresAt: string;\n operationDigest: string;\n matched?: { txHash: string; blockHash: string; operationIndex: string };\n reasonCode?: string;\n checkpointSequence?: string;\n}\nexport type TrackingResult = PublicResult & { tracking: Tracking };\nexport class TrackingStaleGenerationError extends Error {\n constructor() {\n super(\"TRACKING_STALE_GENERATION\");\n }\n}\nexport function validateTracking(value: unknown, expectedId?: string): Tracking {\n if (!value || typeof value !== \"object\") throw Error(\"Missing tracking\");\n const t = value as Tracking;\n if (\n Object.keys(t).some(\n (k) =>\n ![\n \"id\",\n \"status\",\n \"expiresAt\",\n \"operationDigest\",\n \"matched\",\n \"reasonCode\",\n \"checkpointSequence\",\n ].includes(k)\n ) ||\n typeof t.id !== \"string\" ||\n !/^([a-f0-9]{48})$/.test(t.id) ||\n (expectedId !== undefined && t.id !== expectedId) ||\n typeof t.operationDigest !== \"string\" ||\n word(t.operationDigest) !== t.operationDigest ||\n typeof t.expiresAt !== \"string\" ||\n !/^(0|[1-9][0-9]*)$/.test(t.expiresAt)\n )\n throw Error(\"Invalid tracking identity\");\n uint(t.expiresAt, 64);\n if (\n ![\n \"pending_confirmation\",\n \"pending_source\",\n \"recognized\",\n \"expired\",\n \"superseded\",\n \"stale_generation\",\n ].includes(t.status)\n )\n throw Error(\"Unknown tracking status\");\n if (t.status === \"stale_generation\") throw new TrackingStaleGenerationError();\n if (BigInt(t.expiresAt) < 1n) throw Error(\"Invalid tracking expiry\");\n if ([\"pending_source\", \"recognized\"].includes(t.status) && !t.matched)\n throw Error(\"Tracking locator required\");\n if (t.matched) {\n const m = t.matched;\n if (\n Object.keys(m).some((k) => ![\"txHash\", \"blockHash\", \"operationIndex\"].includes(k)) ||\n typeof m.txHash !== \"string\" ||\n word(m.txHash) !== m.txHash ||\n typeof m.blockHash !== \"string\" ||\n word(m.blockHash) !== m.blockHash ||\n typeof m.operationIndex !== \"string\" ||\n !/^(0|[1-9][0-9]*)$/.test(m.operationIndex)\n )\n throw Error(\"Invalid tracking locator\");\n uint(m.operationIndex, 32);\n }\n if (t.reasonCode !== undefined && typeof t.reasonCode !== \"string\")\n throw Error(\"Invalid tracking reason\");\n return t;\n}\n/** Single evaluation results are flat; aggregate members carry their own tracking records. */\nexport function preflightTracking(\n result: PublicResult,\n operationIndex: string,\n operationDigest: string\n): Tracking {\n const member = Array.isArray(result.operations)\n ? result.operations.find(\n (v: Record<string, unknown>) => String(v.operationIndex) === operationIndex\n )\n : result;\n if (\n !member ||\n result.broadcastDecision !== \"allow\" ||\n member.broadcastDecision !== \"allow\" ||\n word(String(member.operationDigest)) !== word(operationDigest)\n )\n throw Error(\"Preflight candidate was not allowed\");\n const tracking = validateTracking(member.tracking);\n if (![\"pending_confirmation\", \"pending_source\", \"recognized\"].includes(tracking.status))\n throw Error(\"Tracking no longer permits broadcast\");\n if (tracking.operationDigest !== word(operationDigest))\n throw Error(\"Tracking statement mismatch\");\n return tracking;\n}\n","export const PROVENANCE_MANIFEST_SHA256 =\n \"6107789c5c0d24c4130bff05da6d389336feb5ccb247c4030eae5198ab05d762\";\n","import { field, recognizedLeaf, scopeHash, type Integer, type Scope } from \"./index\";\nimport { poseidonHash } from \"@invisi-labs/primitives\";\nconst hash = async (v: Integer[]) => BigInt(await poseidonHash(v.map(field)));\nexport class RecognizedTree {\n private readonly leaves: bigint[] = [];\n get leafCount(): number {\n return this.leaves.length;\n }\n append(value: Integer): number {\n const leaf = field(value);\n if (!leaf || this.leaves.length >= 2 ** 32) throw new Error(\"Invalid leaf or full tree\");\n this.leaves.push(leaf);\n return this.leaves.length - 1;\n }\n async appendCommitment(scope: Scope, commitment: Integer): Promise<number> {\n return this.append(await recognizedLeaf(await scopeHash(scope), commitment));\n }\n async membershipForCommitment(\n scope: Scope,\n commitment: Integer\n ): Promise<{ leafIndex: number; path: bigint[]; root: bigint } | undefined> {\n const leaf = await recognizedLeaf(await scopeHash(scope), commitment),\n index = this.leaves.indexOf(leaf);\n if (index < 0) return undefined;\n return { leafIndex: index, ...(await this.path(index)) };\n }\n async root(): Promise<bigint> {\n if (this.leaves.length) return (await this.path(0)).root;\n let zero = 0n;\n for (let i = 0; i < 32; i++) zero = await hash([zero, zero]);\n return zero;\n }\n async path(index: number): Promise<{ path: bigint[]; root: bigint }> {\n if (!Number.isInteger(index) || index < 0 || index >= this.leaves.length)\n throw new Error(\"Leaf index\");\n let zero = 0n,\n nodes = new Map(this.leaves.map((v, i) => [i, v])),\n cursor = index;\n const path: bigint[] = [];\n for (let l = 0; l < 32; l++) {\n path.push(nodes.get(cursor % 2 === 0 ? cursor + 1 : cursor - 1) ?? zero);\n const next = new Map<number, bigint>();\n for (const i of nodes.keys()) {\n const p = Math.floor(i / 2);\n if (!next.has(p))\n next.set(\n p,\n await hash([nodes.get(p * 2) ?? zero, nodes.get(p * 2 + 1) ?? zero])\n );\n }\n zero = await hash([zero, zero]);\n nodes = next;\n cursor = Math.floor(cursor / 2);\n }\n return { path, root: nodes.get(0) ?? zero };\n }\n}\n"],"mappings":";AAAA,SAAS,UAAAA,eAAc;AACvB,SAAS,WAAAC,gBAAe;AACxB,SAAS,UAAU,WAAW,YAAAC,WAAU,WAAAC,UAAS,UAAAC,eAAc;AAC/D,SAAS,gBAAAC,qBAAoB;;;ACH7B,SAAS,cAAc;AACvB,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,cAAc;AAwB1C,IAAM,UAAU,CAAC,MAA0B;AACvC,MAAI,CAAC,sBAAsB,KAAK,CAAC,EAAG,OAAM,IAAI,MAAM,mCAAmC;A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C,CAAC,mBAAmB,KAAK,EAAE,cAAc,KACzC,EAAE,aAAa,WAAW,MAC1B,CAAC,0BAA0B,KAAK,EAAE,KAAK,KACvC,EAAE,MAAM,SAAS;AAEjB,UAAM,IAAI,MAAM,8BAA8B;AAClD,SAAO;AAAA,IACH,gBAAgB,KAAK,QAAQ,gBAAgB,EAAE,EAAE,SAAS;AAAA,IAC1D,aAAa;AAAA,MACT,QAAQ,EAAE;AAAA,MACV,QAAQ,EAAE;AAAA,MACV,WAAW,EAAE;AAAA,MACb,gBAAgB,EAAE;AAAA,MAClB,cAAc,EAAE,aAAa,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC;AAAA,MACtD,OAAO,EAAE;AAAA,MACT,kBAAkB,EAAE,iBAAiB,IAAI,iBAAiB;AAAA,IAC9D;AAAA,EACJ;AACJ;","names":["sha256","ed25519","getBytes","hexlify","concat","poseidonHash","operationDigest","hexlify","sha256","hash","poseidonHash","getBytes","concat","ed25519"]}