@crediolabs/policy-synth 0.1.18 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +6 -5
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/adapters/interpreter/index.d.ts +1 -1
  5. package/dist/adapters/interpreter/index.js +1 -1
  6. package/dist/adapters/oz/adapter.js +1 -15
  7. package/dist/errors.d.ts +1 -1
  8. package/dist/index.d.ts +1 -4
  9. package/dist/index.js +1 -4
  10. package/dist/install/build-add-context-rule.d.ts +3 -11
  11. package/dist/install/build-add-context-rule.js +2 -97
  12. package/dist/install/build-install-policy.d.ts +4 -53
  13. package/dist/install/build-install-policy.js +44 -123
  14. package/dist/ir/index.d.ts +1 -1
  15. package/dist/ir/types.d.ts +7 -76
  16. package/dist/ir/types.js +0 -2
  17. package/dist/predicate/decode.d.ts +1 -1
  18. package/dist/predicate/decode.js +2 -70
  19. package/dist/predicate/encode.js +45 -229
  20. package/dist/predicate/from-json.js +1 -42
  21. package/dist/record/decode.js +3 -8
  22. package/dist/review-card/builder.d.ts +4 -3
  23. package/dist/review-card/builder.js +18 -162
  24. package/dist/review-card/cross-check.js +2 -105
  25. package/dist/review-card/render-leaf.d.ts +4 -0
  26. package/dist/review-card/render-leaf.js +47 -0
  27. package/dist/run/index.d.ts +35 -53
  28. package/dist/run/index.js +115 -156
  29. package/dist/run/schemas.d.ts +168 -1650
  30. package/dist/run/schemas.js +36 -199
  31. package/dist/seams/types.d.ts +0 -2
  32. package/dist/simulate/deny-cases.d.ts +26 -0
  33. package/dist/simulate/deny-cases.js +282 -0
  34. package/dist/simulate/evaluate.d.ts +18 -0
  35. package/dist/simulate/evaluate.js +271 -0
  36. package/dist/simulate/index.d.ts +4 -0
  37. package/dist/simulate/index.js +8 -0
  38. package/dist/synth/compose-from-recording.d.ts +24 -51
  39. package/dist/synth/compose-from-recording.js +120 -282
  40. package/dist/synth/deny-cases.d.ts +5 -7
  41. package/dist/synth/deny-cases.js +23 -373
  42. package/dist/synth/evaluate.d.ts +0 -21
  43. package/dist/synth/evaluate.js +56 -336
  44. package/dist/synth/index.d.ts +0 -5
  45. package/dist/synth/index.js +0 -5
  46. package/dist/synth/permit-context.d.ts +2 -9
  47. package/dist/synth/permit-context.js +1 -82
  48. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  49. package/dist/synth/synthesize-from-recording.js +41 -356
  50. package/dist/types.d.ts +8 -60
  51. package/dist/types.js +5 -2
  52. package/dist/verify/simulate.d.ts +1 -14
  53. package/dist/verify/simulate.js +2 -88
  54. package/dist/verify/verify.d.ts +1 -7
  55. package/dist/verify/verify.js +0 -8
  56. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  57. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  58. package/dist-cjs/adapters/interpreter/index.d.ts +1 -1
  59. package/dist-cjs/adapters/interpreter/index.js +1 -2
  60. package/dist-cjs/adapters/oz/adapter.js +1 -15
  61. package/dist-cjs/errors.d.ts +1 -1
  62. package/dist-cjs/index.d.ts +1 -4
  63. package/dist-cjs/index.js +1 -4
  64. package/dist-cjs/install/build-add-context-rule.d.ts +3 -11
  65. package/dist-cjs/install/build-add-context-rule.js +1 -96
  66. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  67. package/dist-cjs/install/build-install-policy.js +44 -122
  68. package/dist-cjs/ir/index.d.ts +1 -1
  69. package/dist-cjs/ir/types.d.ts +7 -76
  70. package/dist-cjs/ir/types.js +0 -2
  71. package/dist-cjs/predicate/decode.d.ts +1 -1
  72. package/dist-cjs/predicate/decode.js +2 -70
  73. package/dist-cjs/predicate/encode.js +45 -229
  74. package/dist-cjs/predicate/from-json.js +1 -42
  75. package/dist-cjs/record/decode.js +3 -8
  76. package/dist-cjs/review-card/builder.d.ts +4 -3
  77. package/dist-cjs/review-card/builder.js +23 -167
  78. package/dist-cjs/review-card/cross-check.js +7 -110
  79. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  80. package/dist-cjs/review-card/render-leaf.js +52 -0
  81. package/dist-cjs/run/index.d.ts +35 -53
  82. package/dist-cjs/run/index.js +116 -162
  83. package/dist-cjs/run/schemas.d.ts +168 -1650
  84. package/dist-cjs/run/schemas.js +37 -200
  85. package/dist-cjs/seams/types.d.ts +0 -2
  86. package/dist-cjs/simulate/deny-cases.d.ts +26 -0
  87. package/dist-cjs/simulate/deny-cases.js +286 -0
  88. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  89. package/dist-cjs/simulate/evaluate.js +274 -0
  90. package/dist-cjs/simulate/index.d.ts +4 -0
  91. package/dist-cjs/simulate/index.js +13 -0
  92. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  93. package/dist-cjs/synth/compose-from-recording.js +120 -282
  94. package/dist-cjs/synth/deny-cases.d.ts +5 -7
  95. package/dist-cjs/synth/deny-cases.js +23 -374
  96. package/dist-cjs/synth/evaluate.d.ts +0 -21
  97. package/dist-cjs/synth/evaluate.js +57 -337
  98. package/dist-cjs/synth/index.d.ts +0 -5
  99. package/dist-cjs/synth/index.js +1 -11
  100. package/dist-cjs/synth/permit-context.d.ts +2 -9
  101. package/dist-cjs/synth/permit-context.js +1 -82
  102. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  103. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  104. package/dist-cjs/types.d.ts +8 -60
  105. package/dist-cjs/types.js +6 -3
  106. package/dist-cjs/verify/simulate.d.ts +1 -14
  107. package/dist-cjs/verify/simulate.js +2 -88
  108. package/dist-cjs/verify/verify.d.ts +1 -7
  109. package/dist-cjs/verify/verify.js +0 -8
  110. package/package.json +4 -4
  111. package/src/adapters/interpreter/adapter.ts +76 -572
  112. package/src/errors.ts +0 -19
  113. package/src/index.ts +1 -4
  114. package/src/install/build-add-context-rule.ts +4 -127
  115. package/src/install/build-install-policy.ts +93 -214
  116. package/src/predicate/decode.ts +2 -70
  117. package/src/predicate/encode.ts +49 -261
  118. package/src/predicate/from-json.ts +1 -43
  119. package/src/record/decode.ts +3 -8
  120. package/src/review-card/builder.ts +19 -168
  121. package/src/review-card/cross-check.ts +3 -105
  122. package/src/review-card/render-leaf.ts +48 -0
  123. package/src/run/index.ts +130 -186
  124. package/src/run/schemas.ts +38 -214
  125. package/src/simulate/deny-cases.ts +334 -0
  126. package/src/simulate/evaluate.ts +284 -0
  127. package/src/simulate/index.ts +11 -0
  128. package/src/synth/compose-from-recording.ts +148 -347
  129. package/src/synth/index.ts +0 -13
  130. package/src/synth/synthesize-from-recording.ts +43 -456
  131. package/src/types.ts +13 -49
  132. package/dist/install/build-install-predicate.d.ts +0 -96
  133. package/dist/install/build-install-predicate.js +0 -444
  134. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  135. package/dist-cjs/install/build-install-predicate.js +0 -479
  136. package/src/adapters/interpreter/index.ts +0 -8
  137. package/src/adapters/oz/adapter.ts +0 -376
  138. package/src/adapters/oz/index.ts +0 -9
  139. package/src/codegen/compile-gate.ts +0 -167
  140. package/src/codegen/index.ts +0 -17
  141. package/src/codegen/template.ts +0 -165
  142. package/src/ir/index.ts +0 -13
  143. package/src/ir/types.ts +0 -132
  144. package/src/mandate/index.ts +0 -4
  145. package/src/mandate/to-ir.ts +0 -71
  146. package/src/mandate/types.ts +0 -21
  147. package/src/seams/index.ts +0 -11
  148. package/src/seams/types.ts +0 -81
  149. package/src/synth/deny-cases.ts +0 -663
  150. package/src/synth/evaluate.ts +0 -613
  151. package/src/synth/harness.ts +0 -68
  152. package/src/synth/minimize.ts +0 -48
  153. package/src/synth/permit-context.ts +0 -136
  154. package/src/synth/predicate-literals.ts +0 -27
  155. package/src/synth/synthesize-from-mandate.ts +0 -82
  156. package/src/verify/envelope.ts +0 -28
  157. package/src/verify/index.ts +0 -5
  158. package/src/verify/simulate.ts +0 -311
  159. package/src/verify/verify.ts +0 -243
@@ -0,0 +1,334 @@
1
+ import { Address } from '@stellar/stellar-sdk'
2
+ import type { PredicateLeaf, PredicateNode, ScVal } from '../types.ts'
3
+ import { MAX_SCVAL_CLONE_DEPTH } from '../types.ts'
4
+ import type { EvalContext } from './evaluate.ts'
5
+
6
+ export interface DenyCase {
7
+ dimension: string
8
+ ctx: EvalContext
9
+ /** Canonical reason the Rust interpreter returns for this dimension.
10
+ * Optional: when set, `runHarness` asserts the TS evaluator emits this
11
+ * exact string, so a future TS/Rust reason divergence fails CI. When
12
+ * absent the case is only checked on the boolean decision. */
13
+ expectedReason?: string
14
+ }
15
+
16
+ export interface GeneratedCases {
17
+ permit: EvalContext
18
+ denies: DenyCase[]
19
+ }
20
+
21
+ /** A contract address that is not the pinned one. It must be a REAL strkey:
22
+ * the host rejects a malformed one with `Error(Value, InvalidInput)` before
23
+ * the predicate is ever evaluated, which would make the deny case pass for
24
+ * the wrong reason. */
25
+ const OTHER_CONTRACT = Address.contract(Buffer.alloc(32, 0x5a)).toString()
26
+
27
+ type ComparisonOperator = 'eq' | 'lte'
28
+
29
+ type ComparisonNode = {
30
+ op: ComparisonOperator
31
+ left: PredicateLeaf
32
+ right: PredicateLeaf
33
+ }
34
+
35
+ type MembershipNode = {
36
+ op: 'in'
37
+ needle: PredicateLeaf
38
+ haystack: PredicateLeaf[]
39
+ }
40
+
41
+ interface PredicateFacts {
42
+ comparisons: ComparisonNode[]
43
+ memberships: MembershipNode[]
44
+ }
45
+
46
+ /** Build deterministic model-evaluated alternatives without mutating the intended call.
47
+ *
48
+ * @param predicate - the synthesized predicate
49
+ * @param permitCtx - EvalContext for the intended (permitted) call
50
+ * @param dimensions - optional whitelist of dimension names to emit; when omitted
51
+ * all known dimensions (including over-permissiveness mutations)
52
+ * are emitted. */
53
+ export function generateCases(
54
+ predicate: PredicateNode,
55
+ permitCtx: EvalContext,
56
+ dimensions?: string[]
57
+ ): GeneratedCases {
58
+ const facts = inspectPredicate(predicate)
59
+ const denies: DenyCase[] = []
60
+
61
+ // contract_scope: the same call sent to a different contract. The predicate
62
+ // pins `call_contract`, so this is the most direct bypass attempt there is -
63
+ // point the agent's authorised call at another contract entirely.
64
+ if (facts.comparisons.some((c) => c.op === 'eq' && c.left.kind === 'call_contract')) {
65
+ denies.push({
66
+ dimension: 'contract_scope',
67
+ ctx: { ...permitCtx, contract: OTHER_CONTRACT },
68
+ expectedReason: 'CONTRACT_SCOPE',
69
+ })
70
+ }
71
+
72
+ // function_scope: the same arguments sent to a different method on the
73
+ // pinned contract. `transfer` and `burn` take the same shape; only the
74
+ // `call_fn` pin separates them.
75
+ if (facts.comparisons.some((c) => c.op === 'eq' && c.left.kind === 'call_fn')) {
76
+ denies.push({
77
+ dimension: 'function_scope',
78
+ ctx: { ...permitCtx, fn: `${permitCtx.fn}_not` },
79
+ expectedReason: 'ARG_MISMATCH',
80
+ })
81
+ }
82
+
83
+ // arg_bound: set a constrained arg to an opaque ScVal.
84
+ // The reason depends on the predicate shape:
85
+ // - an `eq(call_arg[i], literal)` denies with ARG_MISMATCH
86
+ // - an `in(call_arg[i], [literals])` denies with NOT_IN_ALLOWLIST
87
+ // Both are correct in the TS evaluator; the reason is predicate-dependent
88
+ // so we cannot pin a single canonical reason here.
89
+ const argumentConstraints: Array<{ index: number }> = []
90
+ for (const comparison of facts.comparisons) {
91
+ if (
92
+ comparison.op === 'eq' &&
93
+ comparison.left.kind === 'call_arg' &&
94
+ comparison.right.kind !== 'literal_vec'
95
+ ) {
96
+ argumentConstraints.push({ index: comparison.left.index })
97
+ }
98
+ }
99
+ for (const membership of facts.memberships) {
100
+ if (membership.needle.kind === 'call_arg') {
101
+ argumentConstraints.push({ index: membership.needle.index })
102
+ }
103
+ }
104
+ for (const constraint of argumentConstraints) {
105
+ const ctx = cloneContext(permitCtx)
106
+ ctx.args[constraint.index] = { type: 'other', value: 'deny-case-opaque-argument' }
107
+ denies.push({ dimension: 'arg_bound', ctx })
108
+ }
109
+
110
+ // soroswap_allowed_path: replace a bound vec arg with a different vector.
111
+ // Still valid for eq comparisons on literal_vec leaves.
112
+ for (const comparison of facts.comparisons) {
113
+ if (
114
+ comparison.op !== 'eq' ||
115
+ comparison.left.kind !== 'call_arg' ||
116
+ comparison.right.kind !== 'literal_vec'
117
+ ) {
118
+ continue
119
+ }
120
+ const ctx = cloneContext(permitCtx)
121
+ ctx.args[comparison.left.index] = differentVector(ctx.args[comparison.left.index])
122
+ denies.push({ dimension: 'soroswap_allowed_path', ctx })
123
+ }
124
+
125
+ // argument_reorder: swap first two address args.
126
+ // Skipped when dimensions filter is active so the synth pipeline can emit a policy;
127
+ // the over-permissiveness harness then tests this mutation as a FINDING.
128
+ const constrainedArgIndices = new Set<number>()
129
+ for (const comparison of facts.comparisons) {
130
+ if (comparison.left.kind === 'call_arg') constrainedArgIndices.add(comparison.left.index)
131
+ }
132
+ for (const membership of facts.memberships) {
133
+ if (membership.needle.kind === 'call_arg') constrainedArgIndices.add(membership.needle.index)
134
+ }
135
+ const hasConstrainedArg = constrainedArgIndices.size > 0
136
+ if (
137
+ (!dimensions || dimensions.includes('argument_reorder')) &&
138
+ hasConstrainedArg &&
139
+ permitCtx.args.length >= 2 &&
140
+ permitCtx.args[0]?.type === 'address' &&
141
+ permitCtx.args[1]?.type === 'address' &&
142
+ (permitCtx.args[0] as { type: 'address'; value: string }).value !==
143
+ (permitCtx.args[1] as { type: 'address'; value: string }).value
144
+ ) {
145
+ const ctx = cloneContext(permitCtx)
146
+ // Guard above guarantees args[0] and args[1] exist and are address-typed.
147
+ const a0 = ctx.args[0] as ScVal
148
+ const a1 = ctx.args[1] as ScVal
149
+ ctx.args[0] = a1
150
+ ctx.args[1] = a0
151
+ denies.push({ dimension: 'argument_reorder', ctx })
152
+ }
153
+
154
+ // map_field_flip: flip a bound map field to a different valid value of
155
+ // the same type. OPT-IN only, never ORIGINAL.
156
+ // Targets each `call_arg_field` leaf and produces a ctx whose vec element
157
+ // has a different value of the recorded field. ---
158
+ if (!dimensions || dimensions.includes('map_field_flip')) {
159
+ for (const comparison of facts.comparisons) {
160
+ const sel = comparison.left
161
+ if (sel.kind !== 'call_arg_field') continue
162
+ const arg = permitCtx.args[sel.index]
163
+ if (arg?.type !== 'vec') continue
164
+ const element = arg.value[sel.element]
165
+ if (element?.type !== 'map' || !Array.isArray(element.value)) continue
166
+ const entry = element.value.find((e) => e.key === sel.field)
167
+ if (!entry) continue
168
+ const flipped = flipFieldValue(entry.val)
169
+ if (flipped === null) continue
170
+ const ctx = cloneContext(permitCtx)
171
+ const clonedVec = arg.value.map(cloneScVal)
172
+ const clonedElement = clonedVec[sel.element]
173
+ if (clonedElement?.type !== 'map' || !Array.isArray(clonedElement.value)) continue
174
+ clonedElement.value = clonedElement.value.map((e) =>
175
+ e.key === sel.field ? { key: e.key, val: flipped } : e
176
+ )
177
+ clonedVec[sel.element] = clonedElement
178
+ ctx.args[sel.index] = { type: 'vec', value: clonedVec }
179
+ denies.push({ dimension: 'map_field_flip', ctx })
180
+ }
181
+ }
182
+
183
+ // amount_over_cap: push a capped value one unit past its cap.
184
+ //
185
+ // Every value bound is an `lte`, and `arg_bound` only targets `eq`, so
186
+ // without this the headline guarantee - "never more than this much per
187
+ // call" - had nothing exercising it. One over the cap is the smallest
188
+ // mutation that must be refused; if the cap held only for larger overshoots
189
+ // it would not be a cap.
190
+ if (!dimensions || dimensions.includes('amount_over_cap')) {
191
+ for (const comparison of facts.comparisons) {
192
+ if (comparison.op !== 'lte') continue
193
+ const cap = literalInteger(comparison.right)
194
+ if (cap === null) continue
195
+ const over: ScVal = { type: 'i128', value: (cap + 1n).toString() }
196
+ const sel = comparison.left
197
+ if (sel.kind === 'call_arg') {
198
+ const ctx = cloneContext(permitCtx)
199
+ ctx.args[sel.index] = over
200
+ denies.push({ dimension: 'amount_over_cap', ctx, expectedReason: 'ARG_MISMATCH' })
201
+ continue
202
+ }
203
+ if (sel.kind !== 'call_arg_field') continue
204
+ const arg = permitCtx.args[sel.index]
205
+ if (arg?.type !== 'vec') continue
206
+ const ctx = cloneContext(permitCtx)
207
+ const clonedVec = arg.value.map(cloneScVal)
208
+ const clonedElement = clonedVec[sel.element]
209
+ if (clonedElement?.type !== 'map' || !Array.isArray(clonedElement.value)) continue
210
+ clonedElement.value = clonedElement.value.map((e) =>
211
+ e.key === sel.field ? { key: e.key, val: over } : e
212
+ )
213
+ clonedVec[sel.element] = clonedElement
214
+ ctx.args[sel.index] = { type: 'vec', value: clonedVec }
215
+ denies.push({ dimension: 'amount_over_cap', ctx, expectedReason: 'ARG_MISMATCH' })
216
+ }
217
+ }
218
+
219
+ // vec_append: append a new element to a bound vec. OPT-IN only, never ORIGINAL.
220
+ // Targets every `call_arg_len` leaf; without the length pin a caller can
221
+ // append an extra element to defeat per-element binds. ---
222
+ if (!dimensions || dimensions.includes('vec_append')) {
223
+ for (const comparison of facts.comparisons) {
224
+ const sel = comparison.left
225
+ if (sel.kind !== 'call_arg_len') continue
226
+ const arg = permitCtx.args[sel.index]
227
+ if (arg?.type !== 'vec') continue
228
+ const ctx = cloneContext(permitCtx)
229
+ ctx.args[sel.index] = {
230
+ type: 'vec',
231
+ value: [...arg.value, { type: 'other', value: 'deny-case-vec-append' }],
232
+ }
233
+ denies.push({ dimension: 'vec_append', ctx })
234
+ }
235
+ }
236
+
237
+ return { permit: cloneContext(permitCtx), denies }
238
+ }
239
+
240
+ function inspectPredicate(predicate: PredicateNode): PredicateFacts {
241
+ const facts: PredicateFacts = { comparisons: [], memberships: [] }
242
+ visit(predicate, facts)
243
+ return facts
244
+ }
245
+
246
+ function visit(node: PredicateNode, facts: PredicateFacts): void {
247
+ switch (node.op) {
248
+ case 'and':
249
+ for (const child of node.children) visit(child, facts)
250
+ return
251
+ case 'in':
252
+ facts.memberships.push(node)
253
+ return
254
+ case 'eq':
255
+ case 'lte':
256
+ facts.comparisons.push(node)
257
+ }
258
+ }
259
+
260
+ /** The integer a numeric literal leaf carries, or null when the leaf is not
261
+ * numeric (an address or a vector has no cap to exceed). */
262
+ function literalInteger(leaf: PredicateLeaf): bigint | null {
263
+ if (leaf.kind === 'literal_i128') return BigInt(leaf.value)
264
+ if (leaf.kind === 'literal_u32') return BigInt(leaf.value)
265
+ return null
266
+ }
267
+
268
+ function differentVector(actual: ScVal | undefined): ScVal {
269
+ if (actual?.type !== 'vec') return { type: 'vec', value: [] }
270
+ if (actual.value.length === 0) {
271
+ return { type: 'vec', value: [{ type: 'other', value: 'deny-case-extra-hop' }] }
272
+ }
273
+ if (actual.value.length > 1) {
274
+ const reversed = actual.value.map(cloneScVal).reverse()
275
+ if (JSON.stringify(reversed) !== JSON.stringify(actual.value)) {
276
+ return { type: 'vec', value: reversed }
277
+ }
278
+ }
279
+ const value = actual.value.map(cloneScVal)
280
+ value[0] = { type: 'other', value: 'deny-case-different-hop' }
281
+ return { type: 'vec', value }
282
+ }
283
+
284
+ function cloneContext(ctx: EvalContext): EvalContext {
285
+ return {
286
+ contract: ctx.contract,
287
+ fn: ctx.fn,
288
+ args: ctx.args.map(cloneScVal),
289
+ }
290
+ }
291
+
292
+ /** Deep-copy an ScVal so a mutation cannot alias the recorded call.
293
+ * Exported so the permit-context builder shares this one implementation. */
294
+ export function cloneScVal(value: ScVal, depth = 0): ScVal {
295
+ if (value.type === 'vec') {
296
+ if (depth >= MAX_SCVAL_CLONE_DEPTH) {
297
+ throw cloneDepthError(value)
298
+ }
299
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) }
300
+ }
301
+ return { ...value }
302
+ }
303
+
304
+ function cloneDepthError(value: ScVal): never {
305
+ const err = new Error(
306
+ `ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`
307
+ ) as Error & { code: string; severity: string; retryable: boolean; depthContext: unknown }
308
+ err.code = 'SYNTHESIS_ERROR'
309
+ err.severity = 'error'
310
+ err.retryable = false
311
+ err.depthContext = value.type
312
+ throw err
313
+ }
314
+
315
+ /** Build a value of the SAME ScVal type that differs from the recorded one,
316
+ * used by the `map_field_flip` mutation to defeat a per-element pin without
317
+ * changing the wire type. Returns null when the ScVal type has no obvious
318
+ * different value (e.g. opaque/other). */
319
+ function flipFieldValue(val: ScVal): ScVal | null {
320
+ switch (val.type) {
321
+ case 'address': {
322
+ const a = 'GBFKRGJYZXLTDEI36ZCQEIM225NMOCR2VDBOIHJTXJ54FEFFVL2FKALE'
323
+ const b = 'GD6XSMQJ47EHHJOWXQOND5YDVZC37JWZJHYHBKE6QJFSLLJ5KQXM5QS5'
324
+ return { type: 'address', value: val.value === a ? b : a }
325
+ }
326
+ case 'i128':
327
+ case 'u32':
328
+ return { type: val.type, value: String(BigInt(val.value) + 1n) }
329
+ case 'symbol':
330
+ return { type: 'symbol', value: `${val.value}x` }
331
+ default:
332
+ return null
333
+ }
334
+ }
@@ -0,0 +1,284 @@
1
+ // src/simulate/evaluate.ts - TypeScript reference evaluator for grammar version 3.
2
+ //
3
+ // Pure function. Determinism: same `(predicate, ctx)` -> byte-identical result,
4
+ // no clock, no randomness. Deny order (deny on FIRST violation, stable reason):
5
+ // 1. contract mismatch -> 'CONTRACT_SCOPE'
6
+ // 2. per-ScVal equality on fn/args; EXACT ordered vector
7
+ // equality; fail-closed on opaque args -> 'ARG_MISMATCH'
8
+ // 3. `in` membership; empty haystack ALWAYS denies -> 'NOT_IN_ALLOWLIST'
9
+ // 4. otherwise permit.
10
+ //
11
+ // Grammar version 3 nodes: and, eq, lte
12
+ // Grammar version 3 leaves: call_contract, call_fn, call_arg(i),
13
+ // call_arg_len(i), call_arg_field(i, element, field),
14
+ // literal_address, literal_i128, literal_symbol, literal_u32, literal_vec
15
+ // Grammar version 3 deny reasons: ARG_MISMATCH, CONTRACT_SCOPE,
16
+ // UNSUPPORTED_NODE, NOT_IN_ALLOWLIST
17
+
18
+ import type { PredicateLeaf, PredicateNode, ScVal } from '../types.ts'
19
+
20
+ export interface EvalContext {
21
+ /** Contract the interpreter is asked to enforce against. */
22
+ contract: string
23
+ /** Function name on that contract. */
24
+ fn: string
25
+ /** Decoded `ScVal[]` of the top-level authorized call. */
26
+ args: ScVal[]
27
+ }
28
+
29
+ export type EvalResult = { permit: true } | { permit: false; reason: string }
30
+
31
+ /** Evaluate a `PredicateNode` against the candidate call described by `ctx`.
32
+ * Pure function. Returns `{ permit: true }` or `{ permit: false; reason }`. */
33
+ export function evaluate(predicate: PredicateNode, ctx: EvalContext): EvalResult {
34
+ return walk(predicate, ctx)
35
+ }
36
+
37
+ /** Walk the predicate tree. Returns the FIRST deny reason encountered on
38
+ * the active branch (so `and` fails-fast). */
39
+ function walk(node: PredicateNode, ctx: EvalContext): EvalResult {
40
+ switch (node.op) {
41
+ case 'and': {
42
+ let lastDeny: EvalResult | null = null
43
+ for (const child of node.children) {
44
+ const r = walk(child, ctx)
45
+ if (!r.permit) return r
46
+ lastDeny = r
47
+ }
48
+ return lastDeny ?? { permit: true }
49
+ }
50
+ case 'eq':
51
+ case 'lte':
52
+ return evalCompare(node.op, node.left, node.right, ctx)
53
+ case 'in':
54
+ return evalIn(node.needle, node.haystack, ctx)
55
+ }
56
+ }
57
+
58
+ /** Comparison leaf evaluation. */
59
+ function evalCompare(
60
+ op: 'eq' | 'lte',
61
+ left: PredicateLeaf,
62
+ right: PredicateLeaf,
63
+ ctx: EvalContext
64
+ ): EvalResult {
65
+ // CONTRACT_SCOPE on call_contract eq
66
+ if (left.kind === 'call_contract' && op === 'eq') {
67
+ if (right.kind !== 'literal_address') return { permit: false, reason: 'CONTRACT_SCOPE' }
68
+ return right.value === ctx.contract
69
+ ? { permit: true }
70
+ : { permit: false, reason: 'CONTRACT_SCOPE' }
71
+ }
72
+
73
+ // call_fn equality
74
+ if (left.kind === 'call_fn' && op === 'eq') {
75
+ if (right.kind !== 'literal_symbol') return { permit: false, reason: 'ARG_MISMATCH' }
76
+ return right.value === ctx.fn ? { permit: true } : { permit: false, reason: 'ARG_MISMATCH' }
77
+ }
78
+
79
+ // call_arg comparison (eq / exact-vec, or lte ordered numeric bound)
80
+ if (left.kind === 'call_arg') {
81
+ const actual = ctx.args[left.index]
82
+ if (op !== 'eq') return evalArgOrderedCompare(op, actual, right)
83
+ return evalArgEq(op, actual, right)
84
+ }
85
+
86
+ // call_arg_len: length of a vec-typed argument as u32.
87
+ // Fails closed on a non-vec / absent arg or a non-u32 literal.
88
+ if (left.kind === 'call_arg_len') {
89
+ const actual = ctx.args[left.index]
90
+ if (actual?.type !== 'vec') return { permit: false, reason: 'ARG_MISMATCH' }
91
+ if (right.kind !== 'literal_u32') return { permit: false, reason: 'ARG_MISMATCH' }
92
+ return actual.value.length === right.value
93
+ ? { permit: true }
94
+ : { permit: false, reason: 'ARG_MISMATCH' }
95
+ }
96
+
97
+ // call_arg_field: value of a field in the map at element i of
98
+ // the vec at argument index. Fails closed on shape / type / range issues.
99
+ if (left.kind === 'call_arg_field') {
100
+ const actual = ctx.args[left.index]
101
+ if (actual?.type !== 'vec') return { permit: false, reason: 'ARG_MISMATCH' }
102
+ const element = actual.value[left.element]
103
+ if (element?.type !== 'map') return { permit: false, reason: 'ARG_MISMATCH' }
104
+ if (!Array.isArray(element.value)) return { permit: false, reason: 'ARG_MISMATCH' }
105
+ const entry = element.value.find((e) => e.key === left.field)
106
+ if (!entry) return { permit: false, reason: 'ARG_MISMATCH' }
107
+ if (op === 'eq') return evalArgEq(op, entry.val, right)
108
+ return evalArgOrderedCompare(op, entry.val, right)
109
+ }
110
+
111
+ // Unknown leaf/op combination - structural fail-closed.
112
+ return { permit: false, reason: 'UNSUPPORTED_NODE' }
113
+ }
114
+
115
+ /** Per-ScVal equality. Handles literal_vec as an EXACT ordered sequence:
116
+ * compare element-by-element in order; deny if length or any element differs.
117
+ * Opaque args (`type: 'other'`) fail closed. */
118
+ function evalArgEq(op: 'eq' | 'lte', actual: ScVal | undefined, right: PredicateLeaf): EvalResult {
119
+ // eq(call_arg[i], literal_vec) -> EXACT ordered vector equality.
120
+ if (op === 'eq' && right.kind === 'literal_vec') {
121
+ if (actual?.type !== 'vec') return { permit: false, reason: 'ARG_MISMATCH' }
122
+ return compareVecExact(actual.value, right.elements)
123
+ ? { permit: true }
124
+ : { permit: false, reason: 'ARG_MISMATCH' }
125
+ }
126
+
127
+ if (op === 'eq' && right.kind === 'literal_address') {
128
+ if (!actual) return { permit: false, reason: 'ARG_MISMATCH' }
129
+ if (actual.type === 'other') return { permit: false, reason: 'ARG_MISMATCH' }
130
+ return actual.type === 'address' && actual.value === right.value
131
+ ? { permit: true }
132
+ : { permit: false, reason: 'ARG_MISMATCH' }
133
+ }
134
+
135
+ if (op === 'eq' && right.kind === 'literal_i128') {
136
+ if (actual?.type !== 'i128') return { permit: false, reason: 'ARG_MISMATCH' }
137
+ return BigInt(actual.value) === BigInt(right.value)
138
+ ? { permit: true }
139
+ : { permit: false, reason: 'ARG_MISMATCH' }
140
+ }
141
+
142
+ if (op === 'eq' && right.kind === 'literal_symbol') {
143
+ if (!actual) return { permit: false, reason: 'ARG_MISMATCH' }
144
+ return actual.type === 'symbol' && actual.value === right.value
145
+ ? { permit: true }
146
+ : { permit: false, reason: 'ARG_MISMATCH' }
147
+ }
148
+
149
+ if (op === 'eq' && right.kind === 'literal_u32') {
150
+ if (!actual) return { permit: false, reason: 'ARG_MISMATCH' }
151
+ return actual.type === 'u32' && actual.value === String(right.value)
152
+ ? { permit: true }
153
+ : { permit: false, reason: 'ARG_MISMATCH' }
154
+ }
155
+
156
+ // Anything else: fail closed on opacity (cannot decode the arg reliably).
157
+ if (!actual || actual.type === 'other') return { permit: false, reason: 'ARG_MISMATCH' }
158
+ return { permit: false, reason: 'ARG_MISMATCH' }
159
+ }
160
+
161
+ /** Ordered numeric comparison (lte) on a `call_arg`. The interpreter reads the
162
+ * arg as an integer (i128 on the recorder's ScVal surface) and compares it
163
+ * to a numeric literal via BigInt. A non-numeric arg or a non-numeric literal
164
+ * fails closed (ARG_MISMATCH) rather than permitting an undecidable bound. */
165
+ function evalArgOrderedCompare(
166
+ op: 'eq' | 'lte',
167
+ actual: ScVal | undefined,
168
+ right: PredicateLeaf
169
+ ): EvalResult {
170
+ const actualInt = argNumericBigInt(actual)
171
+ const literalInt = literalNumericBigInt(right)
172
+ if (actualInt === null || literalInt === null) {
173
+ return { permit: false, reason: 'ARG_MISMATCH' }
174
+ }
175
+ return bigintCmp(op, actualInt.toString(), literalInt.toString())
176
+ ? { permit: true }
177
+ : { permit: false, reason: 'ARG_MISMATCH' }
178
+ }
179
+
180
+ /** BigInt value of a numeric-integer ScVal arg (i128 / u32), or null when
181
+ * the arg is absent, opaque, or a non-numeric type. */
182
+ function argNumericBigInt(actual: ScVal | undefined): bigint | null {
183
+ if (!actual) return null
184
+ if (actual.type === 'i128' || actual.type === 'u32') {
185
+ try {
186
+ return BigInt(actual.value)
187
+ } catch {
188
+ return null
189
+ }
190
+ }
191
+ return null
192
+ }
193
+
194
+ /** BigInt value of a numeric-integer literal leaf (`literal_i128` / `literal_u32`),
195
+ * or null for a non-numeric literal. Callers fail closed on null. */
196
+ function literalNumericBigInt(leaf: PredicateLeaf): bigint | null {
197
+ switch (leaf.kind) {
198
+ case 'literal_i128':
199
+ try {
200
+ return BigInt(leaf.value)
201
+ } catch {
202
+ return null
203
+ }
204
+ case 'literal_u32':
205
+ return BigInt(leaf.value)
206
+ default:
207
+ return null
208
+ }
209
+ }
210
+
211
+ /** Element-by-element ordered comparison of an `ScVal[]` against a
212
+ * `PredicateLeaf[]`. Equal-length and equal at every index => permit.
213
+ * Length mismatch OR any element mismatch => deny ARG_MISMATCH. */
214
+ function compareVecExact(actual: ScVal[], expected: PredicateLeaf[]): boolean {
215
+ if (actual.length !== expected.length) return false
216
+ for (let i = 0; i < expected.length; i++) {
217
+ const e = expected[i]
218
+ const a = actual[i]
219
+ if (!e || !a) return false
220
+ const r = evalArgEq('eq', a, e)
221
+ if (!r.permit) return false
222
+ }
223
+ return true
224
+ }
225
+
226
+ /** `in` membership. Empty haystack ALWAYS denies. Opaque needle fails closed. */
227
+ function evalIn(needle: PredicateLeaf, haystack: PredicateLeaf[], ctx: EvalContext): EvalResult {
228
+ if (haystack.length === 0) return { permit: false, reason: 'NOT_IN_ALLOWLIST' }
229
+ const actual = resolveLeaf(needle, ctx)
230
+ if (!actual || actual.type === 'other') return { permit: false, reason: 'NOT_IN_ALLOWLIST' }
231
+ for (const h of haystack) {
232
+ const r = evalArgEq('eq', actual, h)
233
+ if (r.permit) return { permit: true }
234
+ }
235
+ return { permit: false, reason: 'NOT_IN_ALLOWLIST' }
236
+ }
237
+
238
+ /** Resolve a selector leaf to its current ScVal against the candidate call. */
239
+ function resolveLeaf(leaf: PredicateLeaf, ctx: EvalContext): ScVal | undefined {
240
+ switch (leaf.kind) {
241
+ case 'call_contract':
242
+ return { type: 'address', value: ctx.contract }
243
+ case 'call_fn':
244
+ return { type: 'symbol', value: ctx.fn }
245
+ case 'call_arg':
246
+ return ctx.args[leaf.index]
247
+ case 'call_arg_len':
248
+ // No direct ScVal projection: the length is an integer the comparator
249
+ // resolves against the right-hand literal. Returning undefined keeps
250
+ // the `in` membership path structurally informed (no haystack match).
251
+ return undefined
252
+ case 'call_arg_field': {
253
+ const actual = ctx.args[leaf.index]
254
+ if (actual?.type !== 'vec') return undefined
255
+ const element = actual.value[leaf.element]
256
+ if (element?.type !== 'map') return undefined
257
+ if (!Array.isArray(element.value)) return undefined
258
+ const entry = element.value.find((e) => e.key === leaf.field)
259
+ return entry ? entry.val : undefined
260
+ }
261
+ case 'literal_address':
262
+ return { type: 'address', value: leaf.value }
263
+ case 'literal_i128':
264
+ return { type: 'i128', value: leaf.value }
265
+ case 'literal_symbol':
266
+ return { type: 'symbol', value: leaf.value }
267
+ case 'literal_u32':
268
+ return { type: 'u32', value: String(leaf.value) }
269
+ case 'literal_vec':
270
+ return undefined
271
+ }
272
+ }
273
+
274
+ /** BigInt compare helper. */
275
+ function bigintCmp(op: 'eq' | 'lte', aStr: string, bStr: string): boolean {
276
+ const a = BigInt(aStr)
277
+ const b = BigInt(bStr)
278
+ switch (op) {
279
+ case 'eq':
280
+ return a === b
281
+ case 'lte':
282
+ return a <= b
283
+ }
284
+ }
@@ -0,0 +1,11 @@
1
+ // src/simulate/index.ts - the off-chain evaluation engine.
2
+ //
3
+ // `evaluate` is a second implementation of the on-chain predicate semantics.
4
+ // The conformance harness runs it and the Rust interpreter against the same
5
+ // predicate and asserts the verdicts match, so a divergence between the two
6
+ // fails CI rather than reaching a user as a wrong simulation.
7
+
8
+ export type { DenyCase, GeneratedCases } from './deny-cases.ts'
9
+ export { generateCases } from './deny-cases.ts'
10
+ export type { EvalContext, EvalResult } from './evaluate.ts'
11
+ export { evaluate } from './evaluate.ts'