-
Notifications
You must be signed in to change notification settings - Fork 595
Expand file tree
/
Copy pathprivate_kernel_execution_prover.test.ts
More file actions
387 lines (334 loc) · 14.1 KB
/
private_kernel_execution_prover.test.ts
File metadata and controls
387 lines (334 loc) · 14.1 KB
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
377
378
379
380
381
382
383
384
385
386
387
import { BackendType, BarretenbergSync } from '@aztec/bb.js';
import {
MAX_KEY_VALIDATION_REQUESTS_PER_TX,
MAX_NOTE_HASH_READ_REQUESTS_PER_TX,
MAX_TX_LIFETIME,
MEGA_VK_LENGTH_IN_FIELDS,
VK_TREE_HEIGHT,
} from '@aztec/constants';
import { Fr } from '@aztec/foundation/curves/bn254';
import { createLogger } from '@aztec/foundation/log';
import { MembershipWitness } from '@aztec/foundation/trees';
import { FunctionSelector } from '@aztec/stdlib/abi';
import { AztecAddress } from '@aztec/stdlib/aztec-address';
import type { PrivateKernelProver } from '@aztec/stdlib/interfaces/client';
import { PrivateCircuitPublicInputs, PrivateKernelTailCircuitPublicInputs } from '@aztec/stdlib/kernel';
import { PublicKeys } from '@aztec/stdlib/keys';
import { makeTxRequest } from '@aztec/stdlib/testing';
import { PrivateCallExecutionResult, PrivateExecutionResult, type TxRequest } from '@aztec/stdlib/tx';
import { VerificationKeyData } from '@aztec/stdlib/vks';
import { mock } from 'jest-mock-extended';
import times from 'lodash.times';
import {
PrivateCircuitPublicInputsBuilder,
PrivateKernelCircuitPublicInputsBuilder,
makeKernelOutput,
} from './hints/test_utils.js';
import { PrivateKernelExecutionProver } from './private_kernel_execution_prover.js';
import type { PrivateKernelOracle } from './private_kernel_oracle.js';
const logger = createLogger('private_kernel_execution_prover');
describe('Private Kernel Sequencer', () => {
let txRequest: TxRequest;
let oracle: ReturnType<typeof mock<PrivateKernelOracle>>;
let proofCreator: ReturnType<typeof mock<PrivateKernelProver>>;
let prover: PrivateKernelExecutionProver;
let dependencies: { [name: string]: string[] } = {};
const contractAddress = AztecAddress.fromBigInt(987654n);
const blockTimestamp = 12345n;
const expirationTimestamp = blockTimestamp + BigInt(MAX_TX_LIFETIME);
beforeAll(async () => {
await BarretenbergSync.initSingleton({ backend: BackendType.NativeSharedMemory, logger: logger.debug });
});
const createExecutionResult = (fnName: string): PrivateExecutionResult => {
return new PrivateExecutionResult(createCallExecutionResult(fnName), Fr.zero(), []);
};
const createCallExecutionResult = (
fnName: string,
{
publicInputs,
childPublicInputs = [],
address = contractAddress,
nestedResults,
}: {
publicInputs?: PrivateCircuitPublicInputs;
childPublicInputs?: PrivateCircuitPublicInputs[];
address?: AztecAddress;
nestedResults?: PrivateCallExecutionResult[];
} = {},
): PrivateCallExecutionResult => {
if (!publicInputs) {
publicInputs = PrivateCircuitPublicInputs.empty();
}
publicInputs.callContext.functionSelector = new FunctionSelector(fnName.charCodeAt(0));
publicInputs.callContext.contractAddress = address;
return new PrivateCallExecutionResult(
Buffer.alloc(0),
Buffer.alloc(MEGA_VK_LENGTH_IN_FIELDS * Fr.SIZE_IN_BYTES),
new Map(),
publicInputs,
[],
new Map(),
[],
[],
[],
nestedResults ??
(dependencies[fnName] || []).map((name, i) =>
createCallExecutionResult(name, { publicInputs: childPublicInputs[i] }),
),
[],
);
};
/** Creates a mock kernel output. Optionally accepts a callback to configure the builder before building. */
const simulateProofOutput = (configure?: (builder: PrivateKernelCircuitPublicInputsBuilder) => void) => {
const builder = new PrivateKernelCircuitPublicInputsBuilder(contractAddress);
// Every tx has at least one nullifier (the first nullifier), which needs siloing in the final reset.
builder.addNullifier();
configure?.(builder);
const publicInputs = builder.build();
publicInputs.constants.anchorBlockHeader.globalVariables.timestamp = blockTimestamp;
publicInputs.expirationTimestamp = expirationTimestamp;
return makeKernelOutput(publicInputs);
};
/** Creates a mock kernel output for the final iteration. Returns empty result as we don't care about it in the tests */
const simulateProofOutputFinal = () => ({
publicInputs: PrivateKernelTailCircuitPublicInputs.empty(),
outputWitness: new Map(),
verificationKey: VerificationKeyData.empty(),
bytecode: Buffer.from([]),
});
const prove = (executionResult: PrivateExecutionResult) => prover.proveWithKernels(txRequest, executionResult);
beforeEach(async () => {
txRequest = makeTxRequest();
oracle = mock<PrivateKernelOracle>();
oracle.getVkMembershipWitness.mockResolvedValue(MembershipWitness.random(VK_TREE_HEIGHT));
oracle.getMasterSecretKey.mockResolvedValue(Fr.random() as any);
oracle.getContractAddressPreimage.mockResolvedValue({
version: 1 as const,
salt: Fr.random(),
deployer: await AztecAddress.random(),
currentContractClassId: Fr.random(),
originalContractClassId: Fr.random(),
initializationHash: Fr.random(),
publicKeys: await PublicKeys.random(),
address: await AztecAddress.random(),
saltedInitializationHash: Fr.random(),
});
oracle.getContractClassIdPreimage.mockResolvedValue({
artifactHash: Fr.random(),
publicBytecodeCommitment: Fr.random(),
privateFunctionsRoot: Fr.random(),
});
oracle.getDebugFunctionName.mockImplementation((_, selector) =>
Promise.resolve(String.fromCharCode(selector.value)),
);
proofCreator = mock<PrivateKernelProver>();
proofCreator.simulateInit.mockResolvedValue(simulateProofOutput());
proofCreator.simulateInner.mockResolvedValue(simulateProofOutput());
proofCreator.simulateReset.mockResolvedValue(simulateProofOutput());
proofCreator.simulateTail.mockResolvedValue(simulateProofOutputFinal());
prover = new PrivateKernelExecutionProver(oracle, proofCreator, true);
});
it('should execute private functions in correct order', async () => {
{
dependencies = { a: [] };
const executionResult = createExecutionResult('a');
await prove(executionResult);
expect(proofCreator.simulateInit).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateInner).not.toHaveBeenCalled();
proofCreator.simulateInit.mockClear();
}
{
// a {
// b {
// c {}
// }
// d {}
// }
dependencies = {
a: ['b', 'd'],
b: ['c'],
};
const executionResult = createExecutionResult('a');
await prove(executionResult);
// Init for 'a', inner for 'b', 'c', 'd'.
expect(proofCreator.simulateInit).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateInner).toHaveBeenCalledTimes(3);
proofCreator.simulateInit.mockClear();
proofCreator.simulateInner.mockClear();
}
{
// a {
// b {
// d {
// h {}
// }
// }
// c {
// e {}
// f {
// i {}
// j {
// l {
// n {}
// }
// m {}
// }
// k {}
// }
// g {}
// }
dependencies = {
a: ['b', 'c'],
b: ['d'],
d: ['h'],
c: ['e', 'f', 'g'],
f: ['i', 'j', 'k'],
j: ['l', 'm'],
l: ['n'],
};
const executionResult = createExecutionResult('a');
await prove(executionResult);
// Init for 'a', inner for the remaining 13 functions.
expect(proofCreator.simulateInit).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateInner).toHaveBeenCalledTimes(13);
}
});
it('executes init, final reset, and tail for a single function', async () => {
dependencies = { a: [] };
const executionResult = createExecutionResult('a');
const result = await prove(executionResult);
const stepNames = result.executionSteps.map(s => s.functionName);
expect(stepNames).toEqual(['a', 'private_kernel_init', 'private_kernel_reset', 'private_kernel_tail']);
expect(proofCreator.simulateInit).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateInner).not.toHaveBeenCalled();
expect(proofCreator.simulateReset).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateTail).toHaveBeenCalledTimes(1);
});
it('executes init, inners, final reset, and tail for nested functions', async () => {
// a {
// b {
// c {}
// }
// d {}
// }
dependencies = { a: ['b', 'd'], b: ['c'] };
const executionResult = createExecutionResult('a');
const result = await prove(executionResult);
const stepNames = result.executionSteps.map(s => s.functionName);
expect(stepNames).toEqual([
'a',
'private_kernel_init',
'b',
'private_kernel_inner',
'c',
'private_kernel_inner',
'd',
'private_kernel_inner',
'private_kernel_reset',
'private_kernel_tail',
]);
});
it('runs inner reset before next iteration when key validation requests overflow', async () => {
// Set up: init output has MAX key validation requests.
proofCreator.simulateInit.mockResolvedValue(
simulateProofOutput(b => times(MAX_KEY_VALIDATION_REQUESTS_PER_TX, () => b.addKeyValidationRequest())),
);
// Child function b adds 1 key validation request → total exceeds MAX → inner reset needed.
const childBuilder = new PrivateCircuitPublicInputsBuilder(contractAddress);
childBuilder.addKeyValidationRequest();
const childPublicInputs = childBuilder.build();
// a { b {} }
dependencies = { a: ['b'] };
const entryExecResult = createCallExecutionResult('a', { childPublicInputs: [childPublicInputs] });
const executionResult = new PrivateExecutionResult(entryExecResult, Fr.zero(), []);
const result = await prove(executionResult);
const stepNames = result.executionSteps.map(s => s.functionName);
expect(stepNames).toEqual([
'a',
'private_kernel_init',
// Inner reset to clear key validation requests before processing b.
'private_kernel_reset',
'b',
'private_kernel_inner',
// Final reset for siloing.
'private_kernel_reset',
'private_kernel_tail',
]);
expect(proofCreator.simulateInit).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateInner).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateReset).toHaveBeenCalledTimes(2);
expect(proofCreator.simulateTail).toHaveBeenCalledTimes(1);
});
it('rounds the expiration timestamp down before passing it to the tail circuit', async () => {
// Raw offset 7265s (1h + 1805s) should round down to the 1-hour bucket.
const rawOffset = 7265n;
const expectedRoundedOffset = 7200n;
const customOutput = simulateProofOutput();
customOutput.publicInputs.expirationTimestamp = blockTimestamp + rawOffset;
proofCreator.simulateInit.mockResolvedValue(customOutput);
proofCreator.simulateReset.mockResolvedValue(customOutput);
dependencies = { a: [] };
const executionResult = createExecutionResult('a');
await prove(executionResult);
expect(proofCreator.simulateTail).toHaveBeenCalledTimes(1);
const tailInputs = proofCreator.simulateTail.mock.calls[0][0];
expect(tailInputs.expirationTimestampUpperBound).toBe(blockTimestamp + expectedRoundedOffset);
});
it('runs two consecutive inner resets when first reset output still overflows', async () => {
// Set up: init output has MAX note hash read requests and key validation requests.
proofCreator.simulateInit.mockResolvedValue(
simulateProofOutput(b => {
times(MAX_NOTE_HASH_READ_REQUESTS_PER_TX, i => {
b.addNoteHash({ value: new Fr(i + 1) });
b.addPendingNoteHashReadRequest({ value: new Fr(i + 1) });
});
times(MAX_KEY_VALIDATION_REQUESTS_PER_TX, () => b.addKeyValidationRequest());
}),
);
// First inner reset clears the note hash read requests, but still returns MAX key validation requests → second inner reset needed.
proofCreator.simulateReset.mockResolvedValueOnce(
simulateProofOutput(b => times(MAX_KEY_VALIDATION_REQUESTS_PER_TX, () => b.addKeyValidationRequest())),
);
// Child function b adds 1 note hash read request and 1 key validation request → total exceeds MAX → inner reset triggered.
const childBuilder = new PrivateCircuitPublicInputsBuilder(contractAddress);
childBuilder.addPendingNoteHashReadRequest();
childBuilder.addKeyValidationRequest();
const childPublicInputs = childBuilder.build();
// a { b {} }
dependencies = { a: ['b'] };
const entryExecResult = createCallExecutionResult('a', { childPublicInputs: [childPublicInputs] });
const executionResult = new PrivateExecutionResult(entryExecResult, Fr.zero(), []);
const result = await prove(executionResult);
const stepNames = result.executionSteps.map(s => s.functionName);
expect(stepNames).toEqual([
'a',
'private_kernel_init',
// Two consecutive inner resets to clear note hash read requests and key validation requests before processing b.
'private_kernel_reset',
'private_kernel_reset',
'b',
'private_kernel_inner',
// Final reset for siloing.
'private_kernel_reset',
'private_kernel_tail',
]);
expect(proofCreator.simulateInit).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateInner).toHaveBeenCalledTimes(1);
expect(proofCreator.simulateReset).toHaveBeenCalledTimes(3);
expect(proofCreator.simulateTail).toHaveBeenCalledTimes(1);
});
it('fetches updated class id hints once per unique contract address', async () => {
const contractAddressB = AztecAddress.fromBigInt(111111n);
// a { b {} c {} }
// a and c use contractAddress, b uses contractAddressB → 2 unique contracts, 3 executions.
dependencies = {};
const bExec = createCallExecutionResult('b', { address: contractAddressB });
const cExec = createCallExecutionResult('c');
const aExec = createCallExecutionResult('a', { nestedResults: [bExec, cExec] });
const executionResult = new PrivateExecutionResult(aExec, Fr.zero(), []);
await prove(executionResult);
expect(oracle.getUpdatedClassIdHints).toHaveBeenCalledTimes(2);
expect(oracle.getUpdatedClassIdHints).toHaveBeenCalledWith(contractAddress);
expect(oracle.getUpdatedClassIdHints).toHaveBeenCalledWith(contractAddressB);
});
});