@crediolabs/policy-synth 0.1.18 → 0.2.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 (42) hide show
  1. package/README.md +3 -2
  2. package/dist/install/authority-overlap.d.ts +134 -0
  3. package/dist/install/authority-overlap.js +0 -0
  4. package/dist/install/build-add-context-rule.d.ts +8 -0
  5. package/dist/install/build-add-context-rule.js +1 -1
  6. package/dist/install/build-merge-policy.d.ts +70 -0
  7. package/dist/install/build-merge-policy.js +130 -0
  8. package/dist/install/index.d.ts +2 -0
  9. package/dist/install/index.js +7 -0
  10. package/dist/install/plan-merge-policy.d.ts +49 -0
  11. package/dist/install/plan-merge-policy.js +86 -0
  12. package/dist/install/read-account-rules.d.ts +100 -0
  13. package/dist/install/read-account-rules.js +283 -0
  14. package/dist/run/index.d.ts +93 -8
  15. package/dist/run/index.js +282 -11
  16. package/dist/run/schemas.d.ts +290 -11
  17. package/dist/run/schemas.js +77 -11
  18. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  19. package/dist-cjs/install/authority-overlap.js +0 -0
  20. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  21. package/dist-cjs/install/build-add-context-rule.js +1 -0
  22. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  23. package/dist-cjs/install/build-merge-policy.js +134 -0
  24. package/dist-cjs/install/index.d.ts +2 -0
  25. package/dist-cjs/install/index.js +23 -2
  26. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  27. package/dist-cjs/install/plan-merge-policy.js +90 -0
  28. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  29. package/dist-cjs/install/read-account-rules.js +296 -0
  30. package/dist-cjs/run/index.d.ts +93 -8
  31. package/dist-cjs/run/index.js +283 -10
  32. package/dist-cjs/run/schemas.d.ts +290 -11
  33. package/dist-cjs/run/schemas.js +78 -12
  34. package/package.json +1 -1
  35. package/src/install/authority-overlap.ts +0 -0
  36. package/src/install/build-add-context-rule.ts +12 -1
  37. package/src/install/build-merge-policy.ts +219 -0
  38. package/src/install/index.ts +34 -0
  39. package/src/install/plan-merge-policy.ts +133 -0
  40. package/src/install/read-account-rules.ts +376 -0
  41. package/src/run/index.ts +386 -14
  42. package/src/run/schemas.ts +84 -11
@@ -0,0 +1,376 @@
1
+ //! Reading an OpenZeppelin smart account's context rules back off chain.
2
+ //!
3
+ //! `authority-overlap.ts` needs to know what a signer can already do before a
4
+ //! new policy is installed. That means every rule on the account: its context
5
+ //! type, its signers, its attached policies, and - for rules our interpreter
6
+ //! polices - the predicate itself.
7
+ //!
8
+ //! The predicate is NOT reachable through a contract call. The interpreter
9
+ //! exposes no getter for `StoredDoc` (`lib.rs` publishes only `grammar_version`,
10
+ //! `install`, `enforce`, the pause pair, `uninstall` and
11
+ //! `rotate_master_signer_set`), so it is read as a ledger entry instead. That
12
+ //! keeps this a pure client-side capability: adding a getter would change a
13
+ //! deployed contract's ABI and force a redeploy plus re-audit to obtain data
14
+ //! the ledger already exposes.
15
+ //!
16
+ //! The decoders here are pure so they can be tested without a network; the
17
+ //! caller supplies raw `ScVal`s.
18
+
19
+ import {
20
+ Account,
21
+ Address,
22
+ BASE_FEE,
23
+ Contract,
24
+ Keypair,
25
+ rpc,
26
+ TransactionBuilder,
27
+ xdr,
28
+ } from '@stellar/stellar-sdk'
29
+ import { decodePredicate } from '../predicate/decode.ts'
30
+ import type { SignerDraft } from '../types.ts'
31
+ import type { ContextType, ObservedRule } from './authority-overlap.ts'
32
+
33
+ /** `storage.rs:295` - the third element of the persistent doc key tuple. */
34
+ export const K_DOC = 1
35
+
36
+ /** Persistent-storage key for a rule's stored document:
37
+ * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
38
+ export function docKeyScVal(smartAccount: string, ruleId: number): xdr.ScVal {
39
+ return xdr.ScVal.scvVec([
40
+ new Address(smartAccount).toScVal(),
41
+ xdr.ScVal.scvU32(ruleId),
42
+ xdr.ScVal.scvU32(K_DOC),
43
+ ])
44
+ }
45
+
46
+ /** Ledger key for the interpreter's persistent entry holding that document. */
47
+ export function docLedgerKey(
48
+ interpreter: string,
49
+ smartAccount: string,
50
+ ruleId: number
51
+ ): xdr.LedgerKey {
52
+ return xdr.LedgerKey.contractData(
53
+ new xdr.LedgerKeyContractData({
54
+ contract: new Address(interpreter).toScAddress(),
55
+ key: docKeyScVal(smartAccount, ruleId),
56
+ durability: xdr.ContractDataDurability.persistent(),
57
+ })
58
+ )
59
+ }
60
+
61
+ // ---- ScVal helpers -----
62
+
63
+ /** Field of a `#[contracttype]` struct, which the host encodes as a map keyed
64
+ * by field-name symbol. Returns undefined when the field is absent so a
65
+ * caller can distinguish "not there" from "there and empty". */
66
+ function mapField(v: xdr.ScVal, name: string): xdr.ScVal | undefined {
67
+ if (v.switch() !== xdr.ScValType.scvMap()) return undefined
68
+ for (const entry of v.map() ?? []) {
69
+ const key = entry.key()
70
+ if (key.switch() === xdr.ScValType.scvSymbol() && key.sym().toString() === name) {
71
+ return entry.val()
72
+ }
73
+ }
74
+ return undefined
75
+ }
76
+
77
+ function u32Of(v: xdr.ScVal | undefined): number | undefined {
78
+ return v?.switch() === xdr.ScValType.scvU32() ? v.u32() : undefined
79
+ }
80
+
81
+ function addressOf(v: xdr.ScVal | undefined): string | undefined {
82
+ if (!v || v.switch() !== xdr.ScValType.scvAddress()) return undefined
83
+ return Address.fromScAddress(v.address()).toString()
84
+ }
85
+
86
+ /** An enum variant of a `#[contracttype]` enum: `ScVal::Vec([Symbol, ...args])`. */
87
+ function enumVariant(v: xdr.ScVal | undefined): { tag: string; args: xdr.ScVal[] } | undefined {
88
+ if (!v || v.switch() !== xdr.ScValType.scvVec()) return undefined
89
+ const items = v.vec() ?? []
90
+ const head = items[0]
91
+ if (!head || head.switch() !== xdr.ScValType.scvSymbol()) return undefined
92
+ return { tag: head.sym().toString(), args: items.slice(1) }
93
+ }
94
+
95
+ // ---- decoders -----
96
+
97
+ /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
98
+ * is the widest reading and therefore the safe one: it makes the rule look
99
+ * like it could serve any call, so overlap is over-reported, never missed. */
100
+ export function decodeContextType(v: xdr.ScVal | undefined): ContextType {
101
+ const variant = enumVariant(v)
102
+ if (!variant) return { kind: 'default' }
103
+ if (variant.tag === 'CallContract') {
104
+ const addr = addressOf(variant.args[0])
105
+ return addr ? { kind: 'call_contract', address: addr } : { kind: 'default' }
106
+ }
107
+ if (variant.tag === 'CreateContract') {
108
+ const arg = variant.args[0]
109
+ const hash = arg?.switch() === xdr.ScValType.scvBytes() ? arg.bytes().toString('hex') : ''
110
+ return { kind: 'create_contract', wasmHash: hash }
111
+ }
112
+ return { kind: 'default' }
113
+ }
114
+
115
+ /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
116
+ export function decodeSigner(v: xdr.ScVal): SignerDraft | undefined {
117
+ const variant = enumVariant(v)
118
+ if (!variant) return undefined
119
+ if (variant.tag === 'Delegated') {
120
+ const addr = addressOf(variant.args[0])
121
+ return addr ? { kind: 'delegated', address: addr } : undefined
122
+ }
123
+ if (variant.tag === 'External') {
124
+ const verifier = addressOf(variant.args[0])
125
+ const keyArg = variant.args[1]
126
+ const keyBytes =
127
+ keyArg?.switch() === xdr.ScValType.scvBytes() ? keyArg.bytes().toString('hex') : ''
128
+ return verifier ? { kind: 'external', verifier, keyBytes } : undefined
129
+ }
130
+ return undefined
131
+ }
132
+
133
+ /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
134
+ * `predicate` is filled in separately from the ledger entry. */
135
+ export function decodeContextRule(v: xdr.ScVal): ObservedRule | undefined {
136
+ const id = u32Of(mapField(v, 'id'))
137
+ if (id === undefined) return undefined
138
+
139
+ const signersVal = mapField(v, 'signers')
140
+ const signers: SignerDraft[] = []
141
+ if (signersVal?.switch() === xdr.ScValType.scvVec()) {
142
+ for (const s of signersVal.vec() ?? []) {
143
+ const decoded = decodeSigner(s)
144
+ if (decoded) signers.push(decoded)
145
+ }
146
+ }
147
+
148
+ const policiesVal = mapField(v, 'policies')
149
+ const policyAddresses: string[] = []
150
+ if (policiesVal?.switch() === xdr.ScValType.scvVec()) {
151
+ for (const p of policiesVal.vec() ?? []) {
152
+ const addr = addressOf(p)
153
+ if (addr) policyAddresses.push(addr)
154
+ }
155
+ }
156
+
157
+ // `policy_ids` is index-aligned with `policies` in OZ's ContextRule. Only
158
+ // the ids can be passed to `remove_policy`, so a detach is impossible
159
+ // without them; they are read here rather than looked up again later.
160
+ const policyIdsVal = mapField(v, 'policy_ids')
161
+ const policyIds: number[] = []
162
+ if (policyIdsVal?.switch() === xdr.ScValType.scvVec()) {
163
+ for (const pid of policyIdsVal.vec() ?? []) {
164
+ const n = u32Of(pid)
165
+ if (n !== undefined) policyIds.push(n)
166
+ }
167
+ }
168
+
169
+ return {
170
+ id,
171
+ contextType: decodeContextType(mapField(v, 'context_type')),
172
+ signers,
173
+ policyAddresses,
174
+ ...(policyIds.length > 0 ? { policyIds } : {}),
175
+ }
176
+ }
177
+
178
+ /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
179
+ export const K_NONCE = 2
180
+
181
+ /** Ledger key for a rule's stored install nonce. Read directly for the same
182
+ * reason as the document: the interpreter publishes no getter. */
183
+ export function nonceLedgerKey(
184
+ interpreter: string,
185
+ smartAccount: string,
186
+ ruleId: number
187
+ ): xdr.LedgerKey {
188
+ return xdr.LedgerKey.contractData(
189
+ new xdr.LedgerKeyContractData({
190
+ contract: new Address(interpreter).toScAddress(),
191
+ key: xdr.ScVal.scvVec([
192
+ new Address(smartAccount).toScVal(),
193
+ xdr.ScVal.scvU32(ruleId),
194
+ xdr.ScVal.scvU32(K_NONCE),
195
+ ]),
196
+ durability: xdr.ContractDataDurability.persistent(),
197
+ })
198
+ )
199
+ }
200
+
201
+ /** Per-policy oracle bounds carried on a `StoredDoc`.
202
+ *
203
+ * These must survive a merge. They are tighten-only overrides against the
204
+ * wasm defaults, so dropping them does not fail loudly: the rule keeps
205
+ * working and silently tolerates staler prices and wider deviation than its
206
+ * author chose. */
207
+ export interface StoredOracleBounds {
208
+ maxStalenessSeconds?: number
209
+ maxDeviationBps?: number
210
+ maxCrossFeedDeviationBps?: number
211
+ }
212
+
213
+ export function decodeStoredOracleBounds(v: xdr.ScVal): StoredOracleBounds {
214
+ const read = (name: string): number | undefined => u32Of(mapField(v, name))
215
+ const staleness = read('oracle_max_staleness_seconds')
216
+ const deviation = read('oracle_max_deviation_bps')
217
+ const xfeed = read('oracle_max_xfeed_dev_bps')
218
+ return {
219
+ ...(staleness !== undefined ? { maxStalenessSeconds: staleness } : {}),
220
+ ...(deviation !== undefined ? { maxDeviationBps: deviation } : {}),
221
+ ...(xfeed !== undefined ? { maxCrossFeedDeviationBps: xfeed } : {}),
222
+ }
223
+ }
224
+
225
+ /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
226
+ export function decodeStoredPredicateBytes(v: xdr.ScVal): Buffer | undefined {
227
+ const field = mapField(v, 'predicate_bytes')
228
+ if (!field || field.switch() !== xdr.ScValType.scvBytes()) return undefined
229
+ return field.bytes()
230
+ }
231
+
232
+ // ---- collection -----
233
+
234
+ /** The three reads the scan needs. Kept as an interface so the collection
235
+ * below is testable without a network, matching the `InstallRpcClient`
236
+ * pattern in `build-install-policy.ts`. */
237
+ export interface AccountRuleReader {
238
+ /** OZ `get_context_rules_count()`. */
239
+ getContextRuleCount(smartAccount: string): Promise<number>
240
+ /** OZ `get_context_rule(id)`. Undefined when the id is absent. */
241
+ getContextRule(smartAccount: string, ruleId: number): Promise<xdr.ScVal | undefined>
242
+ /** The interpreter's persistent `StoredDoc` entry, read as a ledger entry.
243
+ * Undefined when no document is stored for that rule. */
244
+ getStoredDoc(
245
+ interpreter: string,
246
+ smartAccount: string,
247
+ ruleId: number
248
+ ): Promise<xdr.ScVal | undefined>
249
+ }
250
+
251
+ /** How far the id scan will probe before giving up. OZ imposes no per-account
252
+ * rule cap, so there is no exact bound to derive; this one is far above any
253
+ * realistic account and keeps a malformed `Count` from spinning forever. */
254
+ export const MAX_RULE_ID_SCAN = 512
255
+
256
+ export interface CollectedRules {
257
+ rules: ObservedRule[]
258
+ /** Rule ids whose stored predicate could not be read even though the
259
+ * interpreter is attached. Such a rule is reported without a predicate,
260
+ * which classifies it as opaque rather than as safely narrow. */
261
+ unreadablePredicateRuleIds: number[]
262
+ /** True when the scan stopped before accounting for every live rule. The
263
+ * result is then a SUBSET of the account's rules, so an empty overlap list
264
+ * proves nothing and the caller must not present it as safety. */
265
+ incomplete: boolean
266
+ }
267
+
268
+ /**
269
+ * Every context rule on the account, with predicates filled in for the rules
270
+ * our interpreter polices.
271
+ *
272
+ * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
273
+ * decrements `Count` on removal without ever reusing an id
274
+ * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
275
+ * `remove_context_rule` only lowers `Count`), so after any removal
276
+ * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
277
+ * silently skip live rules at higher ids, and a skipped rule is a missed
278
+ * overlap - the one error that reports safety which does not exist. Instead
279
+ * the scan walks ids upward until it has accounted for `Count` live rules.
280
+ *
281
+ * A rule whose predicate cannot be read is deliberately left without one. That
282
+ * demotes it to the `foreign` class, so the scan reports it as opaque instead
283
+ * of assuming it is narrow.
284
+ */
285
+ export async function collectObservedRules(args: {
286
+ reader: AccountRuleReader
287
+ smartAccount: string
288
+ interpreterAddress: string
289
+ maxRuleIdScan?: number
290
+ }): Promise<CollectedRules> {
291
+ const count = await args.reader.getContextRuleCount(args.smartAccount)
292
+ const limit = args.maxRuleIdScan ?? MAX_RULE_ID_SCAN
293
+ const rules: ObservedRule[] = []
294
+ const unreadablePredicateRuleIds: number[] = []
295
+
296
+ let id = 0
297
+ while (rules.length < count && id < limit) {
298
+ const raw = await args.reader.getContextRule(args.smartAccount, id)
299
+ id++
300
+ if (!raw) continue
301
+ const rule = decodeContextRule(raw)
302
+ if (!rule) continue
303
+
304
+ if (rule.policyAddresses.includes(args.interpreterAddress)) {
305
+ const doc = await args.reader.getStoredDoc(
306
+ args.interpreterAddress,
307
+ args.smartAccount,
308
+ rule.id
309
+ )
310
+ const bytes = doc ? decodeStoredPredicateBytes(doc) : undefined
311
+ if (bytes) {
312
+ try {
313
+ rule.predicate = decodePredicate(bytes)
314
+ // Carried so a merge can re-install the SAME bounds. They are
315
+ // tighten-only overrides, so losing them widens the policy quietly.
316
+ if (doc) rule.oracleBounds = decodeStoredOracleBounds(doc)
317
+ } catch {
318
+ unreadablePredicateRuleIds.push(rule.id)
319
+ }
320
+ } else {
321
+ unreadablePredicateRuleIds.push(rule.id)
322
+ }
323
+ }
324
+ rules.push(rule)
325
+ }
326
+
327
+ return { rules, unreadablePredicateRuleIds, incomplete: rules.length < count }
328
+ }
329
+
330
+ /**
331
+ * An `AccountRuleReader` over a live RPC server.
332
+ *
333
+ * The two OZ getters are read-only simulations, built the same way as
334
+ * `getContractVersion` in `build-install-policy.ts`: the source account is
335
+ * constructed locally because a simulation never checks its sequence number,
336
+ * and asking the network for a random key would 404.
337
+ *
338
+ * The stored document is fetched as a ledger entry rather than a contract
339
+ * call, because the interpreter publishes no getter for it.
340
+ */
341
+ export function accountRuleReaderFromServer(
342
+ server: rpc.Server,
343
+ networkPassphrase: string
344
+ ): AccountRuleReader {
345
+ async function simulateCall(
346
+ contract: string,
347
+ method: string,
348
+ ...args: xdr.ScVal[]
349
+ ): Promise<xdr.ScVal | undefined> {
350
+ const account = new Account(Keypair.random().publicKey(), '0')
351
+ const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase })
352
+ .addOperation(new Contract(contract).call(method, ...args))
353
+ .setTimeout(30)
354
+ .build()
355
+ const sim = await server.simulateTransaction(tx)
356
+ if (rpc.Api.isSimulationError(sim)) return undefined
357
+ return sim.result?.retval
358
+ }
359
+
360
+ return {
361
+ async getContextRuleCount(smartAccount) {
362
+ const val = await simulateCall(smartAccount, 'get_context_rules_count')
363
+ return u32Of(val) ?? 0
364
+ },
365
+ async getContextRule(smartAccount, ruleId) {
366
+ return simulateCall(smartAccount, 'get_context_rule', xdr.ScVal.scvU32(ruleId))
367
+ },
368
+ async getStoredDoc(interpreter, smartAccount, ruleId) {
369
+ const key = docLedgerKey(interpreter, smartAccount, ruleId)
370
+ const res = await server.getLedgerEntries(key)
371
+ const entry = res.entries?.[0]?.val
372
+ if (!entry || entry.switch() !== xdr.LedgerEntryType.contractData()) return undefined
373
+ return entry.contractData().val()
374
+ },
375
+ }
376
+ }