-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathprecondition.ts
376 lines (342 loc) · 11.4 KB
/
precondition.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import {
Circuit,
AsFieldElements,
Bool,
Field,
jsLayout,
Types,
} from '../snarky';
import { circuitValueEquals } from './circuit_value';
import { PublicKey } from './signature';
import * as Mina from './mina';
import { Party, Preconditions } from './party';
import * as GlobalContext from './global-context';
import { UInt32, UInt64 } from './int';
export {
preconditions,
Account,
Network,
assertPreconditionInvariants,
cleanPreconditionsCache,
AccountValue,
NetworkValue,
};
function preconditions(party: Party, isSelf: boolean) {
initializePreconditions(party, isSelf);
return { account: Account(party), network: Network(party) };
}
// note: please keep the two precondition implementations separate
// so we can add customized fields easily
function Network(party: Party): Network {
// TODO there should be a less error-prone way of typing js layout
// e.g. separate keys list and value object, so that we can access by key
let layout = (jsLayout as any).Party.layout[0].value.layout[9].value.layout[0]
.value as Layout;
let context = getPreconditionContextExn(party);
return preconditionClass(layout, 'network', party, context);
}
function Account(party: Party): Account {
// TODO there should be a less error-prone way of typing js layout
// e.g. separate keys list and value object, so that we can access by key
let layout = (jsLayout as any).Party.layout[0].value.layout[9].value.layout[1]
.value as Layout;
let context = getPreconditionContextExn(party);
return preconditionClass(layout, 'account', party, context);
}
function preconditionClass(
layout: Layout,
baseKey: any,
party: Party,
context: PreconditionContext
): any {
if (layout.type === 'option') {
// range condition
if (layout.optionType === 'implicit' && layout.inner.type === 'object') {
let lower = layout.inner.layout[0].value.type;
let baseType = baseMap[lower];
return {
...preconditionSubclass(party, baseKey, baseType as any, context),
assertBetween(lower: any, upper: any) {
context.constrained.add(baseKey);
let property = getPath(party.body.preconditions, baseKey);
property.lower = lower;
property.upper = upper;
},
};
}
// value condition
else if (layout.optionType === 'flaggedOption') {
let baseType = baseMap[layout.inner.type];
return preconditionSubclass(party, baseKey, baseType as any, context);
} else if (layout.inner.type !== 'object') {
let baseType = baseMap[layout.inner.type];
return preconditionSubclass(party, baseKey, baseType as any, context);
}
} else if (layout.type === 'array') {
return {}; // not applicable yet, TODO if we implement state
} else if (layout.type === 'object') {
// for each field, create a recursive object
return Object.fromEntries(
layout.layout.map(({ key, value }) => {
return [
key,
preconditionClass(value, `${baseKey}.${key}`, party, context),
];
})
);
} else throw Error('bug');
}
function preconditionSubclass<
K extends LongKey,
U extends FlatPreconditionValue[K]
>(
party: Party,
longKey: K,
fieldType: AsFieldElements<U>,
context: PreconditionContext
) {
return {
get() {
let { read, vars } = context;
read.add(longKey);
return (vars[longKey] ??
(vars[longKey] = getVariable(party, longKey, fieldType))) as U;
},
assertEquals(value: U) {
context.constrained.add(longKey);
let property = getPath(
party.body.preconditions,
longKey
) as AnyCondition<U>;
if ('isSome' in property) {
property.isSome = Bool(true);
property.value = value;
} else if ('lower' in property) {
property.lower = value;
property.upper = value;
} else {
setPath(party.body.preconditions, longKey, value);
}
},
assertNothing() {
context.constrained.add(longKey);
},
};
}
function getVariable<K extends LongKey, U extends FlatPreconditionValue[K]>(
party: Party,
longKey: K,
fieldType: AsFieldElements<U>
): U {
// in compile, just return an empty variable
if (GlobalContext.inCompile()) {
return Circuit.witness(fieldType, (): U => {
throw Error(
`This error is thrown because you are reading out the value of a variable, when that value is not known.
To write a correct circuit, you must avoid any dependency on the concrete value of variables.`
);
});
}
// if not in compile, get the variable's value first
let [accountOrNetwork, ...rest] = longKey.split('.');
let key = rest.join('.');
let value: U;
if (accountOrNetwork === 'account') {
let address = party.body.publicKey;
let account: any = Mina.getAccount(address);
value = account[key];
if (value === undefined)
throw Error(
`Could not get \`${key}\` on account with public key ${address.toBase58()}. The property may not be available on this account.`
);
} else if (accountOrNetwork === 'network') {
let networkState = Mina.getNetworkState();
value = getPath(networkState, key);
} else {
throw Error('impossible');
}
// in prover, return a new variable which holds the value
// outside, just return the value
if (GlobalContext.inProver()) {
return Circuit.witness(fieldType, () => value);
} else {
return value;
}
}
// per-party context for checking invariants on precondition construction
type PreconditionContext = {
isSelf: boolean;
vars: Partial<FlatPreconditionValue>;
read: Set<LongKey>;
constrained: Set<LongKey>;
};
function initializePreconditions(party: Party, isSelf: boolean) {
preconditionContexts.set(party, {
read: new Set(),
constrained: new Set(),
vars: {},
isSelf,
});
}
function cleanPreconditionsCache(party: Party) {
let context = preconditionContexts.get(party);
if (context !== undefined) context.vars = {};
}
function assertPreconditionInvariants(party: Party) {
let context = getPreconditionContextExn(party);
let self = context.isSelf ? 'this' : 'party';
let dummyPreconditions = Preconditions.ignoreAll();
for (let preconditionPath of context.read) {
// check if every precondition that was read was also contrained
if (context.constrained.has(preconditionPath)) continue;
// check if the precondition was modified manually, which is also a valid way of avoiding an error
let precondition = getPath(party.body.preconditions, preconditionPath);
let dummy = getPath(dummyPreconditions, preconditionPath);
if (!circuitValueEquals(precondition, dummy)) continue;
// we accessed a precondition field but not constrained it explicitly - throw an error
let hasAssertBetween = isRangeCondition(precondition);
let shortPath = preconditionPath.split('.').pop();
let errorMessage = `You used \`${self}.${preconditionPath}.get()\` without adding a precondition that links it to the actual ${shortPath}.
Consider adding this line to your code:
${self}.${preconditionPath}.assertEquals(${self}.${preconditionPath}.get());${
hasAssertBetween
? `
You can also add more flexible preconditions with \`${self}.${preconditionPath}.assertBetween(...)\`.`
: ''
}`;
throw Error(errorMessage);
}
}
function getPreconditionContextExn(party: Party) {
let c = preconditionContexts.get(party);
if (c === undefined) throw Error('bug: precondition context not found');
return c;
}
const preconditionContexts = new WeakMap<Party, PreconditionContext>();
// exported types
// TODO actually fetch network preconditions
type NetworkPrecondition = Preconditions['network'];
type NetworkValue = PreconditionBaseTypes<NetworkPrecondition>;
type Network = PreconditionClassType<NetworkPrecondition>;
// TODO: OK how we read delegate from delegateAccount?
// TODO: no graphql field for provedState yet
// TODO: figure out serialization of receiptChainHash
// TODO: should we add account.state? then we should change the structure on `Fetch.Account` which is stupid anyway
// then can just use circuitArray(Field, 8) as the type
type AccountPrecondition = Omit<Preconditions['account'], 'state'>;
// TODO to use this type as account type everywhere, need to add publicKey
type AccountValue = PreconditionBaseTypes<AccountPrecondition>;
type Account = PreconditionClassType<AccountPrecondition>;
type PreconditionBaseTypes<T> = {
[K in keyof T]: T[K] extends RangeCondition<infer U>
? BasicToFull<U>
: T[K] extends FlaggedOptionCondition<infer U>
? BasicToFull<U>
: T[K] extends AsFieldElements<infer U>
? BasicToFull<U>
: PreconditionBaseTypes<T[K]>;
};
type PreconditionSubclassType<U> = {
get(): BasicToFull<U>;
assertEquals(value: BasicToFull<U>): void;
assertNothing(): void;
};
type PreconditionClassType<T> = {
[K in keyof T]: T[K] extends RangeCondition<infer U>
? PreconditionSubclassType<U> & {
assertBetween(lower: BasicToFull<U>, upper: BasicToFull<U>): void;
}
: T[K] extends FlaggedOptionCondition<infer U>
? PreconditionSubclassType<U>
: T[K] extends AsFieldElements<infer U>
? PreconditionSubclassType<U>
: PreconditionClassType<T[K]>;
};
type BasicToFull<K> = K extends Types.UInt32
? UInt32
: K extends Types.UInt64
? UInt64
: K extends Field
? Field
: K extends Bool
? Bool
: K extends Types.PublicKey
? PublicKey
: never;
// layout types
type BaseLayout = { type: 'UInt64' | 'UInt32' | 'Field' | 'Bool' };
let baseMap = { UInt64, UInt32, Field, Bool };
type RangeLayout<T extends BaseLayout> = {
type: 'object';
layout: [{ key: 'lower'; value: T }, { key: 'upper'; value: T }];
};
type OptionLayout<T extends BaseLayout> = { type: 'option' } & (
| {
optionType: 'flaggedOption';
inner: T;
}
| {
optionType: 'implicit';
inner: RangeLayout<T>;
}
| {
optionType: 'implicit';
inner: T;
}
);
type Layout =
| {
type: 'object';
layout: {
key: string;
value: Layout;
}[];
}
| {
type: 'array';
inner: Layout;
}
| OptionLayout<BaseLayout>
| BaseLayout;
// TS magic for computing flattened precondition types
type JoinEntries<K, P> = K extends string
? P extends [string, unknown, unknown]
? [`${K}${P[0] extends '' ? '' : '.'}${P[0]}`, P[1], P[2]]
: never
: never;
type PreconditionFlatEntry<T> = T extends AnyCondition<infer U>
? ['', T, U]
: { [K in keyof T]: JoinEntries<K, PreconditionFlatEntry<T[K]>> }[keyof T];
type FlatPreconditionValue = {
[S in PreconditionFlatEntry<NetworkPrecondition> as `network.${S[0]}`]: S[2];
} & {
[S in PreconditionFlatEntry<AccountPrecondition> as `account.${S[0]}`]: S[2];
};
type LongKey = keyof FlatPreconditionValue;
// types for the two kinds of conditions
type RangeCondition<T> = { lower: T; upper: T };
type FlaggedOptionCondition<T> = { isSome: Bool; value: T };
type AnyCondition<T> =
| RangeCondition<T>
| FlaggedOptionCondition<T>
| AsFieldElements<T>;
function isRangeCondition<T>(
condition: AnyCondition<T>
): condition is RangeCondition<T> {
return 'lower' in condition;
}
// helper. getPath({a: {b: 'x'}}, 'a.b') === 'x'
// TODO: would be awesome to type this
function getPath(obj: any, path: string) {
let pathArray = path.split('.').reverse();
while (pathArray.length > 0) {
let key = pathArray.pop();
obj = obj[key as any];
}
return obj;
}
function setPath(obj: any, path: string, value: any) {
let pathArray = path.split('.');
let key = pathArray.pop()!;
getPath(obj, pathArray.join('.'))[key] = value;
}