@guardefi/cli 0.0.0-stage → 0.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 (45) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +18 -0
  3. package/README.md +31 -2
  4. package/assurance/cli-check.js +446 -0
  5. package/assurance/cli-project-paths.js +56 -0
  6. package/assurance/cli-storage.js +289 -0
  7. package/assurance/cli-ui.js +617 -0
  8. package/assurance/guardefi-public.js +66 -0
  9. package/assurance/release-policy.js +212 -0
  10. package/core/behavioral-diff.js +555 -0
  11. package/core/canonical-json.js +9 -0
  12. package/core/engine/abi.js +99 -0
  13. package/core/engine/assumptions.json +86 -0
  14. package/core/engine/bytecode.js +119 -0
  15. package/core/engine/callee-binding.js +140 -0
  16. package/core/engine/deployment.js +175 -0
  17. package/core/engine/external-effects.js +40 -0
  18. package/core/engine/harness.js +503 -0
  19. package/core/engine/index.js +638 -0
  20. package/core/engine/integrity.js +124 -0
  21. package/core/engine/model.js +369 -0
  22. package/core/engine/policy.js +59 -0
  23. package/core/engine/proof-certificate.js +69 -0
  24. package/core/engine/provenance.js +354 -0
  25. package/core/engine/screen.js +117 -0
  26. package/core/engine/upgrade-authority.js +327 -0
  27. package/core/generic.js +334 -0
  28. package/core/hardhat.js +114 -0
  29. package/core/isl/behavior-profile.js +169 -0
  30. package/core/isl/behavior-solidity.js +267 -0
  31. package/core/isl/behavior-storage.js +151 -0
  32. package/core/isl/behavior-verify.js +223 -0
  33. package/core/isl/getter-profile.js +149 -0
  34. package/core/isl/vendor/NOTICE.md +38 -0
  35. package/core/isl/vendor/isl-parser.cjs +5872 -0
  36. package/core/isl-compiler.js +19 -0
  37. package/core/isl-firewall.js +1396 -0
  38. package/core/keccak.js +89 -0
  39. package/core/prove.js +376 -0
  40. package/core/release-receipt.js +793 -0
  41. package/core/rpc.js +74 -0
  42. package/core/tools.js +129 -0
  43. package/core/verdict-policy.js +195 -0
  44. package/docs/public-cli.md +32 -0
  45. package/package.json +29 -4
@@ -0,0 +1,793 @@
1
+ // Open Protocol Release Receipt Standard (v1 & v2 execution-bound profile).
2
+ // Zero external dependencies: third parties (auditors, Safe signers, exchanges,
3
+ // insurers) can validate receipt integrity, full transaction execution bindings,
4
+ // expiration/revocation, epistemic scope, and Ed25519 attestations offline.
5
+ const { createHash, createPrivateKey, createPublicKey, sign, verify } = require('node:crypto');
6
+ const { canonical } = require('./canonical-json');
7
+ const { keccak256 } = require('./keccak');
8
+ const { evaluateAuthoritativeReleaseGate } = require('./verdict-policy');
9
+
10
+ const SCHEMA_V1 = 'guardefi.release-receipt.v1';
11
+ const SCHEMA_V2 = 'guardefi.release-receipt.v2';
12
+ const SCHEMA = SCHEMA_V1; // Default schema constant preserved for v1 callers; v2 opted in when execution/policy/assumptions supplied or schemaVersion=2
13
+ const SUPPORTED_SCHEMAS = new Set([SCHEMA_V1, SCHEMA_V2]);
14
+
15
+ const ALGORITHM = 'SHA-256';
16
+ const CANONICALIZATION = 'sorted-json-v1';
17
+ const SIGNING_DOMAIN = 'GuardeFi.ReleaseReceipt.v1\0';
18
+ const ONCHAIN_DOMAIN = 'GuardeFi.ReleaseReceiptCommitment.v1\0';
19
+
20
+ const EPISTEMIC_CLASSES = Object.freeze(['PROVEN', 'BOUNDED', 'OBSERVED', 'UNKNOWN']);
21
+ const CLAIM_OUTCOMES = Object.freeze(['satisfied', 'violated', 'unresolved']);
22
+ const RELEASE_DECISIONS = Object.freeze(['SHIP', 'REVIEW', 'NO_SHIP']);
23
+
24
+ const HEX32 = /^0x[0-9a-f]{64}$/i;
25
+ const DIGEST = /^[0-9a-f]{64}$/;
26
+ const ADDRESS = /^0x[0-9a-f]{40}$/i;
27
+ const HEX_BYTES = /^0x(?:[0-9a-f]{2})*$/i;
28
+
29
+ function sha256Hex(input) {
30
+ return createHash('sha256').update(input, 'utf8').digest('hex');
31
+ }
32
+
33
+ function digestBody(body) {
34
+ return sha256Hex(canonical(body));
35
+ }
36
+
37
+ function onChainReceiptCommitment(bodyDigest) {
38
+ if (typeof bodyDigest !== 'string' || !DIGEST.test(bodyDigest)) {
39
+ throw new Error('Receipt body digest must be a 64-character lowercase hex SHA-256.');
40
+ }
41
+ return '0x' + sha256Hex(ONCHAIN_DOMAIN + bodyDigest);
42
+ }
43
+
44
+ function classifyCheck(check = {}) {
45
+ const status = String(check.status || (check.proven ? 'proven' : 'unknown')).toLowerCase();
46
+ const source = String(check.source || check.group || 'engine');
47
+ const mandatory = check.mandatory !== false;
48
+ const hasBounds = Boolean(
49
+ (typeof check.bounded === 'number' && check.bounded > 0) ||
50
+ (typeof check.boundedLoops === 'number' && check.boundedLoops > 0) ||
51
+ (Array.isArray(check.bounds) && check.bounds.length > 0) ||
52
+ status === 'bounded'
53
+ );
54
+
55
+ if (status === 'failed' || status === 'violated') {
56
+ const epistemicClass = source === 'rpc-observation' || check.epistemicClass === 'OBSERVED'
57
+ ? 'OBSERVED'
58
+ : hasBounds || check.epistemicClass === 'BOUNDED' ? 'BOUNDED' : 'PROVEN';
59
+ return { epistemicClass, outcome: 'violated', mandatory };
60
+ }
61
+
62
+ if (source === 'rpc-observation' || check.epistemicClass === 'OBSERVED' || status === 'observed') {
63
+ return {
64
+ epistemicClass: 'OBSERVED',
65
+ outcome: status === 'inconclusive' || status === 'unknown' ? 'unresolved' : 'satisfied',
66
+ mandatory,
67
+ };
68
+ }
69
+
70
+ if (status === 'bounded' || (status === 'proven' && hasBounds) || status === 'accepted') {
71
+ return { epistemicClass: 'BOUNDED', outcome: 'satisfied', mandatory };
72
+ }
73
+
74
+ if (status === 'proven' || status === 'satisfied') {
75
+ return {
76
+ epistemicClass: check.epistemicClass === 'BOUNDED' ? 'BOUNDED' : 'PROVEN',
77
+ outcome: 'satisfied',
78
+ mandatory,
79
+ };
80
+ }
81
+
82
+ return { epistemicClass: 'UNKNOWN', outcome: 'unresolved', mandatory };
83
+ }
84
+
85
+ function computeEpistemicSummary(claims, openObligations = 0) {
86
+ if (!Array.isArray(claims) || claims.length === 0) {
87
+ throw new Error('A release receipt requires at least one verification claim.');
88
+ }
89
+ if (!Number.isSafeInteger(openObligations) || openObligations < 0) {
90
+ throw new Error('openObligations must be a non-negative integer.');
91
+ }
92
+ const summary = {
93
+ total: claims.length,
94
+ proven: 0,
95
+ bounded: 0,
96
+ observed: 0,
97
+ unknown: 0,
98
+ violated: 0,
99
+ boundedMandatory: 0,
100
+ openObligations,
101
+ };
102
+
103
+ for (const claim of claims) {
104
+ if (!EPISTEMIC_CLASSES.includes(claim.epistemicClass) || !CLAIM_OUTCOMES.includes(claim.outcome)) {
105
+ throw new Error(`Invalid claim classification on ${claim.id || 'unnamed claim'}.`);
106
+ }
107
+ if (claim.epistemicClass === 'PROVEN') summary.proven++;
108
+ else if (claim.epistemicClass === 'BOUNDED') summary.bounded++;
109
+ else if (claim.epistemicClass === 'OBSERVED') summary.observed++;
110
+ else if (claim.epistemicClass === 'UNKNOWN') summary.unknown++;
111
+
112
+ if (claim.outcome === 'violated') summary.violated++;
113
+ if (claim.epistemicClass === 'BOUNDED' && claim.mandatory && claim.outcome === 'satisfied') {
114
+ summary.boundedMandatory++;
115
+ }
116
+ }
117
+ return summary;
118
+ }
119
+
120
+ function deriveReleaseDecision(epistemicSummary) {
121
+ return evaluateAuthoritativeReleaseGate({ epistemicSummary }).decision;
122
+ }
123
+
124
+ function buildScopeNotice(decision, summary) {
125
+ const parts = [
126
+ 'Receipt digest proves byte integrity of recorded evidence, not whole-protocol correctness outside declared checks.',
127
+ ];
128
+ if (decision === 'SHIP') {
129
+ parts.push(`All ${summary.total} recorded checks satisfied (${summary.proven} proven, ${summary.observed} observed) with 0 open obligations.`);
130
+ } else if (decision === 'REVIEW') {
131
+ parts.push(
132
+ `Unresolved or bounded scope requires human review before release: ${summary.bounded} bounded, ${summary.unknown} unknown, ${summary.openObligations} open obligations.`
133
+ );
134
+ } else {
135
+ parts.push(`Release blocked: ${summary.violated} check violation(s) detected.`);
136
+ }
137
+ return parts.join(' ');
138
+ }
139
+
140
+ function normalizeContractBinding(contract, label, allowNull = false) {
141
+ if (contract === null && allowNull) return null;
142
+ if (!contract || typeof contract.name !== 'string' || !contract.name.trim()) {
143
+ throw new Error(`Receipt ${label} binding requires a contract name.`);
144
+ }
145
+ if (typeof contract.bytecodeHash !== 'string' || !HEX32.test(contract.bytecodeHash)) {
146
+ throw new Error(`Receipt ${label} binding requires a 32-byte 0x bytecodeHash.`);
147
+ }
148
+ const address = contract.address ? String(contract.address).toLowerCase() : null;
149
+ if (address !== null && !ADDRESS.test(address)) {
150
+ throw new Error(`Receipt ${label} address must be a 20-byte hex EVM address.`);
151
+ }
152
+ return {
153
+ name: contract.name.trim(),
154
+ bytecodeHash: contract.bytecodeHash.toLowerCase(),
155
+ address,
156
+ };
157
+ }
158
+
159
+ function normalizeExecutionBinding(execution) {
160
+ if (execution === null || execution === undefined) return null;
161
+ if (typeof execution !== 'object' || Array.isArray(execution)) {
162
+ throw new Error('Receipt execution envelope must be an object.');
163
+ }
164
+ if (!ADDRESS.test(execution.target || '')) {
165
+ throw new Error('Execution binding requires a 20-byte target address.');
166
+ }
167
+ let calldataHash = execution.calldataHash ? String(execution.calldataHash).toLowerCase() : null;
168
+ if (execution.calldata !== undefined) {
169
+ if (!HEX_BYTES.test(execution.calldata)) throw new Error('Execution calldata must be 0x-hex bytes.');
170
+ const computed = keccak256(execution.calldata);
171
+ if (calldataHash && calldataHash !== computed) {
172
+ throw new Error('Execution calldataHash does not match supplied calldata.');
173
+ }
174
+ calldataHash = computed;
175
+ }
176
+ if (!calldataHash || !HEX32.test(calldataHash)) {
177
+ throw new Error('Execution binding requires calldata or a 32-byte 0x calldataHash.');
178
+ }
179
+ const value = BigInt(execution.value ?? 0);
180
+ if (value < 0n) throw new Error('Execution value must be non-negative.');
181
+ const operation = Number(execution.operation ?? 0);
182
+ if (operation !== 0 && operation !== 1) {
183
+ throw new Error('Execution operation must be 0 (Call) or 1 (DelegateCall).');
184
+ }
185
+ if (operation === 1) {
186
+ throw new Error('DelegateCall execution envelopes are forbidden in Protocol Release Receipts.');
187
+ }
188
+ const safeNonce = execution.safeNonce === null || execution.safeNonce === undefined
189
+ ? null : Number(execution.safeNonce);
190
+ const guardNonce = execution.guardNonce === null || execution.guardNonce === undefined
191
+ ? null : Number(execution.guardNonce);
192
+ if (safeNonce !== null && (!Number.isSafeInteger(safeNonce) || safeNonce < 0)) {
193
+ throw new Error('Execution safeNonce must be a non-negative integer.');
194
+ }
195
+ if (guardNonce !== null && (!Number.isSafeInteger(guardNonce) || guardNonce < 0)) {
196
+ throw new Error('Execution guardNonce must be a non-negative integer.');
197
+ }
198
+ return {
199
+ target: execution.target.toLowerCase(),
200
+ calldataHash,
201
+ value: value.toString(),
202
+ operation,
203
+ safeNonce,
204
+ guardNonce,
205
+ };
206
+ }
207
+
208
+ function normalizeStateAssumptions(assumptions) {
209
+ if (assumptions === null || assumptions === undefined) return null;
210
+ if (typeof assumptions !== 'object' || Array.isArray(assumptions)) {
211
+ throw new Error('Receipt stateAssumptions must be an object.');
212
+ }
213
+ if (!Number.isSafeInteger(Number(assumptions.block)) || Number(assumptions.block) < 0) {
214
+ throw new Error('stateAssumptions requires a non-negative block number.');
215
+ }
216
+ if (!HEX32.test(assumptions.blockHash || '')) {
217
+ throw new Error('stateAssumptions requires a 32-byte 0x blockHash.');
218
+ }
219
+ if (assumptions.proxyImplementation && !ADDRESS.test(assumptions.proxyImplementation)) {
220
+ throw new Error('stateAssumptions.proxyImplementation must be a valid address.');
221
+ }
222
+ if (assumptions.proxyImplementationHash && !HEX32.test(assumptions.proxyImplementationHash)) {
223
+ throw new Error('stateAssumptions.proxyImplementationHash must be a 32-byte 0x hash.');
224
+ }
225
+ if (assumptions.dependencyReportDigest && !DIGEST.test(assumptions.dependencyReportDigest)) {
226
+ throw new Error('stateAssumptions.dependencyReportDigest must be a 64-char SHA-256 hex digest.');
227
+ }
228
+ const normalized = {
229
+ block: Number(assumptions.block),
230
+ blockHash: assumptions.blockHash.toLowerCase(),
231
+ proxyImplementation: assumptions.proxyImplementation ? assumptions.proxyImplementation.toLowerCase() : null,
232
+ proxyImplementationHash: assumptions.proxyImplementationHash ? assumptions.proxyImplementationHash.toLowerCase() : null,
233
+ dependencyReportDigest: assumptions.dependencyReportDigest ? assumptions.dependencyReportDigest.toLowerCase() : null,
234
+ dependencies: Array.isArray(assumptions.dependencies) ? assumptions.dependencies.map((d) => ({
235
+ id: String(d.id),
236
+ address: String(d.address).toLowerCase(),
237
+ codehash: d.codehash ? String(d.codehash).toLowerCase() : null,
238
+ implementation: d.implementation ? String(d.implementation).toLowerCase() : null,
239
+ getters: d.getters || {},
240
+ })) : [],
241
+ };
242
+ return {
243
+ ...normalized,
244
+ assumptionRoot: '0x' + sha256Hex('GuardeFi.StateAssumptions.v1\0' + canonical(normalized)),
245
+ };
246
+ }
247
+
248
+ function normalizePolicyBinding(policy, issuedAt) {
249
+ if (policy === null || policy === undefined) return null;
250
+ if (typeof policy !== 'object' || Array.isArray(policy)) {
251
+ throw new Error('Receipt policy binding must be an object.');
252
+ }
253
+ const expiresAt = policy.expiresAt || null;
254
+ if (expiresAt !== null) {
255
+ if (!Number.isFinite(Date.parse(expiresAt))) throw new Error('policy.expiresAt must be ISO-8601.');
256
+ if (Date.parse(expiresAt) <= Date.parse(issuedAt)) {
257
+ throw new Error('policy.expiresAt must be strictly after issuedAt.');
258
+ }
259
+ }
260
+ const policyHash = policy.policyHash ? String(policy.policyHash).toLowerCase() : null;
261
+ if (policyHash !== null && !HEX32.test(policyHash)) {
262
+ throw new Error('policy.policyHash must be a 32-byte 0x hash.');
263
+ }
264
+ return {
265
+ orgPolicyId: policy.orgPolicyId ? String(policy.orgPolicyId) : 'default-strict',
266
+ policyHash: policyHash || keccak256('GuardeFi.DefaultOrgPolicy.v1'),
267
+ expiresAt,
268
+ };
269
+ }
270
+
271
+ function createReleaseReceipt({
272
+ schemaVersion = null,
273
+ id,
274
+ issuedAt = new Date().toISOString(),
275
+ expiresAt = null,
276
+ protocol,
277
+ chainId = null,
278
+ proxy = null,
279
+ block = null,
280
+ blockHash = null,
281
+ baseline = null,
282
+ candidate,
283
+ initCalldataHash = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470',
284
+ intent = {},
285
+ execution = null,
286
+ stateAssumptions = null,
287
+ policy = null,
288
+ claims = [],
289
+ openObligations = 0,
290
+ behavioralSummary = null,
291
+ sourceEvidenceDigest = null,
292
+ } = {}) {
293
+ if (typeof id !== 'string' || !id.trim()) throw new Error('Receipt requires a non-empty id.');
294
+ if (typeof issuedAt !== 'string' || !Number.isFinite(Date.parse(issuedAt))) {
295
+ throw new Error('Receipt requires an ISO-8601 issuedAt timestamp.');
296
+ }
297
+ if (typeof protocol !== 'string' || !protocol.trim()) {
298
+ throw new Error('Receipt requires a protocol name.');
299
+ }
300
+ if (chainId !== null && !/^[1-9][0-9]*$/.test(String(chainId))) {
301
+ throw new Error('Receipt chainId must be a positive integer string when present.');
302
+ }
303
+ if (proxy !== null && (typeof proxy !== 'string' || !ADDRESS.test(proxy))) {
304
+ throw new Error('Receipt proxy must be a valid 20-byte EVM address when present.');
305
+ }
306
+ if (block !== null && (!Number.isSafeInteger(Number(block)) || Number(block) < 0)) {
307
+ throw new Error('Receipt block must be a non-negative integer when present.');
308
+ }
309
+ if (blockHash !== null && (typeof blockHash !== 'string' || !HEX32.test(blockHash))) {
310
+ throw new Error('Receipt blockHash must be a 32-byte 0x hash when present.');
311
+ }
312
+ if (typeof initCalldataHash !== 'string' || !HEX32.test(initCalldataHash)) {
313
+ throw new Error('Receipt initCalldataHash must be a 32-byte 0x hash.');
314
+ }
315
+ if (sourceEvidenceDigest !== null && (typeof sourceEvidenceDigest !== 'string' || !DIGEST.test(sourceEvidenceDigest))) {
316
+ throw new Error('sourceEvidenceDigest must be a 64-char SHA-256 hex digest when present.');
317
+ }
318
+
319
+ const normalizedClaims = claims.map((raw, index) => {
320
+ const idValue = String(raw.id || raw.name || `claim_${index + 1}`).trim();
321
+ if (!idValue) throw new Error('Every receipt claim must have an id.');
322
+ const classified = raw.epistemicClass && raw.outcome
323
+ ? { epistemicClass: raw.epistemicClass, outcome: raw.outcome, mandatory: raw.mandatory !== false }
324
+ : classifyCheck(raw);
325
+ if (!EPISTEMIC_CLASSES.includes(classified.epistemicClass) || !CLAIM_OUTCOMES.includes(classified.outcome)) {
326
+ throw new Error(`Invalid classification for claim ${idValue}.`);
327
+ }
328
+ if (classified.epistemicClass === 'UNKNOWN' && classified.outcome === 'satisfied') {
329
+ throw new Error(`Claim ${idValue} cannot be UNKNOWN and satisfied simultaneously.`);
330
+ }
331
+ return {
332
+ id: idValue,
333
+ category: String(raw.category || 'verification'),
334
+ source: String(raw.source || 'guardefi-engine'),
335
+ epistemicClass: classified.epistemicClass,
336
+ outcome: classified.outcome,
337
+ mandatory: Boolean(classified.mandatory),
338
+ detail: raw.detail ? String(raw.detail) : null,
339
+ bounds: Array.isArray(raw.bounds) ? raw.bounds.map(String) : [],
340
+ };
341
+ });
342
+
343
+ const epistemicSummary = computeEpistemicSummary(normalizedClaims, openObligations);
344
+ const decision = deriveReleaseDecision(epistemicSummary);
345
+
346
+ const specHash = intent.specHash ? String(intent.specHash).toLowerCase() : null;
347
+ if (!specHash || !HEX32.test(specHash)) {
348
+ throw new Error('Receipt intent.specHash must be a 32-byte 0x hash.');
349
+ }
350
+ const islSha256 = intent.islSha256 ? String(intent.islSha256).toLowerCase() : null;
351
+ if (islSha256 !== null && !DIGEST.test(islSha256)) {
352
+ throw new Error('Receipt intent.islSha256 must be a 64-char SHA-256 hex digest when present.');
353
+ }
354
+
355
+ const normalizedExecution = normalizeExecutionBinding(execution);
356
+ const normalizedAssumptions = normalizeStateAssumptions(stateAssumptions);
357
+ const mergedPolicy = policy || (expiresAt ? { expiresAt } : null);
358
+ const normalizedPolicy = normalizePolicyBinding(mergedPolicy, issuedAt);
359
+
360
+ const useV2 = schemaVersion === 2 || Boolean(normalizedExecution || normalizedAssumptions || normalizedPolicy);
361
+ const chosenSchema = useV2 ? SCHEMA_V2 : SCHEMA_V1;
362
+
363
+ const body = JSON.parse(JSON.stringify({
364
+ schema: chosenSchema,
365
+ id: id.trim(),
366
+ issuedAt,
367
+ subject: {
368
+ protocol: protocol.trim(),
369
+ chainId: chainId === null ? null : String(chainId),
370
+ proxy: proxy === null ? null : proxy.toLowerCase(),
371
+ block: block === null ? (normalizedAssumptions?.block ?? null) : Number(block),
372
+ blockHash: blockHash === null ? (normalizedAssumptions?.blockHash ?? null) : blockHash.toLowerCase(),
373
+ baseline: normalizeContractBinding(baseline, 'baseline', true),
374
+ candidate: normalizeContractBinding(candidate, 'candidate', false),
375
+ initCalldataHash: initCalldataHash.toLowerCase(),
376
+ },
377
+ intent: {
378
+ format: ['isl', 'spec-json', 'generic'].includes(intent.format) ? intent.format : 'generic',
379
+ specHash,
380
+ islSha256,
381
+ declaredInvariants: Array.isArray(intent.declaredInvariants) ? intent.declaredInvariants.map(String) : [],
382
+ },
383
+ ...(useV2 ? {
384
+ execution: normalizedExecution,
385
+ stateAssumptions: normalizedAssumptions,
386
+ policy: normalizedPolicy,
387
+ } : {}),
388
+ decision,
389
+ epistemicSummary,
390
+ claims: normalizedClaims,
391
+ behavioralSummary: behavioralSummary ? {
392
+ privilegeChanges: Number(behavioralSummary.privilegeChanges || 0),
393
+ guardWeakeningCount: Number(behavioralSummary.guardWeakeningCount || 0),
394
+ fundSurfaceChanges: Number(behavioralSummary.fundSurfaceChanges || 0),
395
+ externalCallChanges: Number(behavioralSummary.externalCallChanges || 0),
396
+ storageCompatible: typeof behavioralSummary.storageCompatible === 'boolean' ? behavioralSummary.storageCompatible : null,
397
+ } : null,
398
+ sourceEvidenceDigest,
399
+ scopeNotice: buildScopeNotice(decision, epistemicSummary),
400
+ }));
401
+
402
+ const digest = digestBody(body);
403
+ const receipt = {
404
+ ...body,
405
+ integrity: {
406
+ algorithm: ALGORITHM,
407
+ canonicalization: CANONICALIZATION,
408
+ digest,
409
+ onChainCommitment: onChainReceiptCommitment(digest),
410
+ },
411
+ attestations: [],
412
+ };
413
+ verifyReleaseReceipt(receipt, { skipExpirationCheck: true }); // structural self-check; expiry is checked at verify time
414
+ return receipt;
415
+ }
416
+
417
+ function receiptFromEvidence(evidencePacket, options = {}) {
418
+ if (!evidencePacket?.run || evidencePacket.schema !== 'guardefi.release-evidence.v1') {
419
+ throw new Error('Expected a guardefi.release-evidence.v1 packet.');
420
+ }
421
+ const { run, integrity } = evidencePacket;
422
+ const proposal = run.proposal || null;
423
+ const engineBounds = [];
424
+ if (run.engine?.limits?.boundedCount > 0) engineBounds.push(`${run.engine.limits.boundedCount} bounded model assumption(s)`);
425
+
426
+ const claims = [];
427
+ if (proposal) {
428
+ claims.push({
429
+ id: 'deployment.snapshot',
430
+ category: 'deployment',
431
+ source: 'rpc-observation',
432
+ epistemicClass: 'OBSERVED',
433
+ outcome: 'satisfied',
434
+ mandatory: true,
435
+ detail: `Pinned chain ${proposal.chainId} proxy ${proposal.proxy} at block ${proposal.block}.`,
436
+ bounds: [`block:${proposal.block}`],
437
+ });
438
+ }
439
+
440
+ for (const check of run.checks || []) {
441
+ claims.push({
442
+ id: `prover.${check.name}`,
443
+ category: 'prover',
444
+ source: 'guardefi-prover',
445
+ status: check.status,
446
+ mandatory: true,
447
+ bounds: check.status === 'bounded' ? ['bounded-loops'] : [],
448
+ });
449
+ }
450
+
451
+ for (const check of run.engine?.checks || []) {
452
+ const status = check.unverified > 0 && check.status === 'proven' ? 'unresolved' : check.status;
453
+ claims.push({
454
+ id: `engine.${check.name}`,
455
+ category: 'differential',
456
+ source: run.engine.id || 'guardefi-engine',
457
+ status,
458
+ bounded: check.bounded || 0,
459
+ mandatory: check.mandatory !== false,
460
+ bounds: check.bounded > 0 ? [...engineBounds, `${check.bounded} bounded solver check(s)`] : [],
461
+ });
462
+ }
463
+
464
+ if (claims.length === 0) {
465
+ claims.push({
466
+ id: 'prover.summary',
467
+ category: 'prover',
468
+ source: 'guardefi-prover',
469
+ status: run.verdict === 'SHIP' ? 'proven' : run.verdict === 'NO_SHIP' ? 'violated' : 'unresolved',
470
+ mandatory: true,
471
+ });
472
+ }
473
+
474
+ const openObligations = options.openObligations ?? (
475
+ run.proofIntegrity?.obligations?.length ??
476
+ (run.verdict === 'UNVERIFIED' ? Math.max(1, run.blockingReasonCount || 1) : 0)
477
+ );
478
+
479
+ return createReleaseReceipt({
480
+ schemaVersion: options.schemaVersion || null,
481
+ id: options.id || `rcpt-${run.id}`,
482
+ issuedAt: options.issuedAt || run.completedAt,
483
+ expiresAt: options.expiresAt || null,
484
+ protocol: options.protocol || run.project,
485
+ chainId: proposal?.chainId || options.chainId || null,
486
+ proxy: proposal?.proxy || options.proxy || null,
487
+ block: proposal?.block ?? options.block ?? null,
488
+ blockHash: proposal?.blockHash || options.blockHash || null,
489
+ baseline: run.baseline ? {
490
+ name: run.baseline.name,
491
+ bytecodeHash: run.baseline.bytecodeHash,
492
+ address: proposal?.baseline?.address || options.baselineAddress || null,
493
+ } : null,
494
+ candidate: {
495
+ name: run.candidate.name,
496
+ bytecodeHash: run.candidate.bytecodeHash,
497
+ address: proposal?.candidate?.address || options.candidateAddress || null,
498
+ },
499
+ initCalldataHash: proposal?.initCall ? keccak256(proposal.initCall) : options.initCalldataHash,
500
+ intent: {
501
+ format: options.intentFormat || (run.specHash === '0x7109fc92f9ef857cd9d08bf6659e8d01bd706b8d726397b9c31be82e12ba8d4a' ? 'generic' : 'spec-json'),
502
+ specHash: run.specHash,
503
+ islSha256: options.islSha256 || null,
504
+ declaredInvariants: options.declaredInvariants || [],
505
+ },
506
+ execution: options.execution || null,
507
+ stateAssumptions: options.stateAssumptions || null,
508
+ policy: options.policy || null,
509
+ claims,
510
+ openObligations,
511
+ behavioralSummary: options.behavioralSummary || null,
512
+ sourceEvidenceDigest: integrity?.digest || null,
513
+ });
514
+ }
515
+
516
+ function signingMessage(bodyDigest) {
517
+ return Buffer.from(SIGNING_DOMAIN + bodyDigest, 'utf8');
518
+ }
519
+
520
+ function signReleaseReceipt(receipt, { signer, role = 'verifier', privateKey, signedAt = new Date().toISOString() }) {
521
+ const checked = verifyReleaseReceipt(receipt, { skipExpirationCheck: true });
522
+ if (typeof signer !== 'string' || !signer.trim()) throw new Error('Attestation requires a signer identifier.');
523
+ if (typeof role !== 'string' || !role.trim()) throw new Error('Attestation requires a signer role.');
524
+ if (!Number.isFinite(Date.parse(signedAt))) throw new Error('Attestation requires a valid ISO-8601 signedAt.');
525
+
526
+ const keyObj = privateKey?.type === 'private' ? privateKey : createPrivateKey(privateKey);
527
+ if (keyObj.asymmetricKeyType !== 'ed25519') {
528
+ throw new Error('Release receipt attestations require an Ed25519 private key.');
529
+ }
530
+ const pubDer = createPublicKey(keyObj).export({ format: 'der', type: 'spki' }).toString('base64');
531
+ const sig = sign(null, signingMessage(checked.digest), keyObj).toString('base64');
532
+
533
+ const attestation = {
534
+ signer: signer.trim(),
535
+ role: role.trim(),
536
+ algorithm: 'Ed25519',
537
+ publicKey: pubDer,
538
+ signedAt,
539
+ signature: sig,
540
+ };
541
+
542
+ const next = {
543
+ ...receipt,
544
+ attestations: [...(receipt.attestations || []), attestation],
545
+ };
546
+ verifyReleaseReceipt(next, { skipExpirationCheck: true });
547
+ return next;
548
+ }
549
+
550
+ function verifyAttestation(attestation, bodyDigest, trustedPublicKey = null) {
551
+ if (!attestation || attestation.algorithm !== 'Ed25519' ||
552
+ typeof attestation.signer !== 'string' || !attestation.signer.trim() ||
553
+ typeof attestation.role !== 'string' || !attestation.role.trim() ||
554
+ typeof attestation.publicKey !== 'string' || typeof attestation.signature !== 'string' ||
555
+ !Number.isFinite(Date.parse(attestation.signedAt))) {
556
+ throw new Error('Invalid receipt attestation structure.');
557
+ }
558
+ const embeddedKey = createPublicKey({
559
+ key: Buffer.from(attestation.publicKey, 'base64'),
560
+ format: 'der',
561
+ type: 'spki',
562
+ });
563
+ if (embeddedKey.asymmetricKeyType !== 'ed25519') {
564
+ throw new Error('Receipt attestation key is not Ed25519.');
565
+ }
566
+ if (trustedPublicKey) {
567
+ const trusted = trustedPublicKey?.type === 'public' ? trustedPublicKey : createPublicKey(trustedPublicKey);
568
+ const trustedDer = trusted.export({ format: 'der', type: 'spki' }).toString('base64');
569
+ if (trustedDer !== attestation.publicKey) {
570
+ throw new Error(`Attestation from ${attestation.signer} does not match the trusted public key.`);
571
+ }
572
+ }
573
+ const sigBytes = Buffer.from(attestation.signature, 'base64');
574
+ if (sigBytes.length !== 64 || sigBytes.toString('base64') !== attestation.signature) {
575
+ throw new Error('Invalid Ed25519 signature encoding.');
576
+ }
577
+ if (!verify(null, signingMessage(bodyDigest), embeddedKey, sigBytes)) {
578
+ throw new Error(`Ed25519 signature verification failed for ${attestation.signer}.`);
579
+ }
580
+ return { signer: attestation.signer, role: attestation.role, publicKey: attestation.publicKey, signedAt: attestation.signedAt };
581
+ }
582
+
583
+ /**
584
+ * Verify that an exact candidate transaction envelope matches a verified receipt.
585
+ * Returns `{ valid: boolean, mismatches: string[] }`.
586
+ */
587
+ function verifyReceiptExecutionBinding(receipt, tx = {}) {
588
+ const mismatches = [];
589
+ const exec = receipt.execution;
590
+ if (!exec) {
591
+ mismatches.push('Receipt has no bound execution envelope (v2 execution binding required for transaction authorization).');
592
+ return { valid: false, mismatches };
593
+ }
594
+ if (tx.chainId !== undefined && receipt.subject?.chainId !== String(tx.chainId)) {
595
+ mismatches.push(`chainId mismatch: receipt=${receipt.subject?.chainId}, tx=${tx.chainId}`);
596
+ }
597
+ if (!tx.to || String(tx.to).toLowerCase() !== exec.target) {
598
+ mismatches.push(`target mismatch: receipt=${exec.target}, tx=${tx.to}`);
599
+ }
600
+ const txValue = BigInt(tx.value ?? 0).toString();
601
+ if (txValue !== exec.value) {
602
+ mismatches.push(`value mismatch: receipt=${exec.value}, tx=${txValue}`);
603
+ }
604
+ const txOp = Number(tx.operation ?? 0);
605
+ if (txOp !== exec.operation || txOp !== 0) {
606
+ mismatches.push(`operation mismatch or forbidden DelegateCall: receipt=${exec.operation}, tx=${txOp}`);
607
+ }
608
+ const actualDataHash = tx.dataHash
609
+ ? String(tx.dataHash).toLowerCase()
610
+ : HEX_BYTES.test(tx.data || '') ? keccak256(tx.data) : null;
611
+ if (!actualDataHash || actualDataHash !== exec.calldataHash) {
612
+ mismatches.push(`calldataHash mismatch: receipt=${exec.calldataHash}, tx=${actualDataHash}`);
613
+ }
614
+ if (exec.safeNonce !== null && tx.safeNonce !== undefined && Number(tx.safeNonce) !== exec.safeNonce) {
615
+ mismatches.push(`safeNonce mismatch: receipt=${exec.safeNonce}, tx=${tx.safeNonce}`);
616
+ }
617
+ if (exec.guardNonce !== null && tx.guardNonce !== undefined && Number(tx.guardNonce) !== exec.guardNonce) {
618
+ mismatches.push(`guardNonce mismatch: receipt=${exec.guardNonce}, tx=${tx.guardNonce}`);
619
+ }
620
+ if (tx.candidateAddress && receipt.subject?.candidate?.address &&
621
+ String(tx.candidateAddress).toLowerCase() !== receipt.subject.candidate.address) {
622
+ mismatches.push(`candidate address mismatch: receipt=${receipt.subject.candidate.address}, tx=${tx.candidateAddress}`);
623
+ }
624
+ if (tx.candidateCodehash && String(tx.candidateCodehash).toLowerCase() !== receipt.subject.candidate.bytecodeHash) {
625
+ mismatches.push(`candidate bytecodeHash mismatch: receipt=${receipt.subject.candidate.bytecodeHash}, tx=${tx.candidateCodehash}`);
626
+ }
627
+ if (tx.baselineCodehash && receipt.subject?.baseline?.bytecodeHash &&
628
+ String(tx.baselineCodehash).toLowerCase() !== receipt.subject.baseline.bytecodeHash) {
629
+ mismatches.push(`baseline bytecodeHash mismatch: receipt=${receipt.subject.baseline.bytecodeHash}, tx=${tx.baselineCodehash}`);
630
+ }
631
+ if (tx.specHash && String(tx.specHash).toLowerCase() !== receipt.intent.specHash) {
632
+ mismatches.push(`specHash mismatch: receipt=${receipt.intent.specHash}, tx=${tx.specHash}`);
633
+ }
634
+ if (tx.policyHash && receipt.policy?.policyHash && String(tx.policyHash).toLowerCase() !== receipt.policy.policyHash) {
635
+ mismatches.push(`policyHash mismatch: receipt=${receipt.policy.policyHash}, tx=${tx.policyHash}`);
636
+ }
637
+
638
+ return { valid: mismatches.length === 0, mismatches };
639
+ }
640
+
641
+ function verifyReleaseReceipt(receipt, {
642
+ expectedDigest,
643
+ trustedPublicKey,
644
+ requireDecision,
645
+ now = null,
646
+ skipExpirationCheck = false,
647
+ isRevoked = null,
648
+ transaction = null,
649
+ } = {}) {
650
+ if (!receipt || typeof receipt !== 'object' || Array.isArray(receipt)) {
651
+ throw new Error('Invalid release receipt packet.');
652
+ }
653
+ const { integrity, attestations = [], ...body } = receipt;
654
+ if (!SUPPORTED_SCHEMAS.has(body.schema)) throw new Error(`Unsupported receipt schema: ${body.schema}`);
655
+ if (!RELEASE_DECISIONS.includes(body.decision)) {
656
+ throw new Error(`Invalid release decision: ${body.decision}`);
657
+ }
658
+ if (!integrity || integrity.algorithm !== ALGORITHM || integrity.canonicalization !== CANONICALIZATION ||
659
+ typeof integrity.digest !== 'string' || !DIGEST.test(integrity.digest)) {
660
+ throw new Error('Invalid release receipt integrity header.');
661
+ }
662
+
663
+ const computedDigest = digestBody(body);
664
+ if (computedDigest !== integrity.digest) {
665
+ throw new Error('Release receipt checksum mismatch.');
666
+ }
667
+ if (integrity.onChainCommitment !== onChainReceiptCommitment(computedDigest)) {
668
+ throw new Error('Release receipt on-chain commitment mismatch.');
669
+ }
670
+ if (expectedDigest !== undefined && computedDigest !== String(expectedDigest).toLowerCase()) {
671
+ throw new Error('Release receipt does not match the expected digest.');
672
+ }
673
+
674
+ normalizeContractBinding(body.subject?.baseline ?? null, 'baseline', true);
675
+ normalizeContractBinding(body.subject?.candidate, 'candidate', false);
676
+ if (!HEX32.test(body.intent?.specHash || '')) {
677
+ throw new Error('Release receipt is missing a valid intent.specHash.');
678
+ }
679
+ if (body.execution !== undefined && body.execution !== null) {
680
+ const normExec = normalizeExecutionBinding(body.execution);
681
+ if (canonical(normExec) !== canonical(body.execution)) {
682
+ throw new Error('Release receipt execution binding is non-canonical or invalid.');
683
+ }
684
+ }
685
+ if (body.stateAssumptions !== undefined && body.stateAssumptions !== null) {
686
+ const { assumptionRoot: _r, ...rawAssumptions } = body.stateAssumptions;
687
+ const normAssump = normalizeStateAssumptions(rawAssumptions);
688
+ if (canonical(normAssump) !== canonical(body.stateAssumptions)) {
689
+ throw new Error('Release receipt stateAssumptions or assumptionRoot mismatch.');
690
+ }
691
+ }
692
+ if (body.policy !== undefined && body.policy !== null) {
693
+ const normPolicy = normalizePolicyBinding(body.policy, body.issuedAt);
694
+ if (canonical(normPolicy) !== canonical(body.policy)) {
695
+ throw new Error('Release receipt policy binding is invalid.');
696
+ }
697
+ }
698
+
699
+ if (!Array.isArray(body.claims) || body.claims.length === 0) {
700
+ throw new Error('Release receipt contains no claims.');
701
+ }
702
+ for (const claim of body.claims) {
703
+ if (claim.epistemicClass === 'UNKNOWN' && claim.outcome === 'satisfied') {
704
+ throw new Error(`Claim ${claim.id} illegally marks UNKNOWN evidence as satisfied.`);
705
+ }
706
+ }
707
+
708
+ const recomputedSummary = computeEpistemicSummary(body.claims, body.epistemicSummary?.openObligations ?? 0);
709
+ if (canonical(recomputedSummary) !== canonical(body.epistemicSummary)) {
710
+ throw new Error('Release receipt epistemicSummary does not match its claims.');
711
+ }
712
+
713
+ const intrinsicDecision = deriveReleaseDecision(recomputedSummary);
714
+ if (body.decision !== intrinsicDecision) {
715
+ throw new Error(`Invalid release decision: claimed ${body.decision}, but epistemic evidence requires ${intrinsicDecision}.`);
716
+ }
717
+
718
+ let expired = false;
719
+ // Fail closed: an omitted `now` means the current time. Only skipExpirationCheck skips this.
720
+ if (!skipExpirationCheck && body.policy?.expiresAt) {
721
+ const refMs = now === null || now === undefined ? Date.now() : typeof now === 'number' ? now : Date.parse(String(now));
722
+ if (!Number.isFinite(refMs)) throw new Error('Invalid verification reference time `now`.');
723
+ expired = refMs > Date.parse(body.policy.expiresAt);
724
+ if (expired) throw new Error(`Release receipt expired at ${body.policy.expiresAt}.`);
725
+ }
726
+
727
+ if (typeof isRevoked === 'function') {
728
+ const rev = isRevoked(receipt, computedDigest);
729
+ if (rev?.revoked) {
730
+ throw new Error(`Release receipt is revoked: ${rev.reason || 'revoked by authority'}.`);
731
+ }
732
+ }
733
+
734
+ if (transaction) {
735
+ const envCheck = verifyReceiptExecutionBinding(body, transaction);
736
+ if (!envCheck.valid) {
737
+ throw new Error(`Transaction substitution or binding mismatch: ${envCheck.mismatches.join('; ')}`);
738
+ }
739
+ }
740
+
741
+ if (!Array.isArray(attestations)) throw new Error('Receipt attestations must be an array.');
742
+ const verifiedAttestations = attestations.map((att) => verifyAttestation(att, computedDigest));
743
+ if (trustedPublicKey) {
744
+ const matched = attestations.some((att) => {
745
+ try {
746
+ verifyAttestation(att, computedDigest, trustedPublicKey);
747
+ return true;
748
+ } catch {
749
+ return false;
750
+ }
751
+ });
752
+ if (!matched) throw new Error('No receipt attestation matched the required trusted public key.');
753
+ }
754
+
755
+ if (requireDecision && body.decision !== requireDecision) {
756
+ throw new Error(`Receipt decision is ${body.decision}, required ${requireDecision}.`);
757
+ }
758
+
759
+ return {
760
+ valid: true,
761
+ schema: body.schema,
762
+ id: body.id,
763
+ protocol: body.subject.protocol,
764
+ decision: body.decision,
765
+ digest: computedDigest,
766
+ onChainCommitment: integrity.onChainCommitment,
767
+ epistemicSummary: recomputedSummary,
768
+ hasExecutionBinding: Boolean(body.execution),
769
+ hasStateAssumptions: Boolean(body.stateAssumptions),
770
+ expiresAt: body.policy?.expiresAt || null,
771
+ attestationCount: verifiedAttestations.length,
772
+ attestations: verifiedAttestations,
773
+ scopeNotice: body.scopeNotice,
774
+ };
775
+ }
776
+
777
+ module.exports = {
778
+ SCHEMA,
779
+ SCHEMA_V1,
780
+ SCHEMA_V2,
781
+ EPISTEMIC_CLASSES,
782
+ CLAIM_OUTCOMES,
783
+ RELEASE_DECISIONS,
784
+ classifyCheck,
785
+ computeEpistemicSummary,
786
+ deriveReleaseDecision,
787
+ createReleaseReceipt,
788
+ receiptFromEvidence,
789
+ signReleaseReceipt,
790
+ verifyReleaseReceipt,
791
+ verifyReceiptExecutionBinding,
792
+ onChainReceiptCommitment,
793
+ };